diff --git a/config/releaser.yml b/config/releaser.yml deleted file mode 100644 index 26e5e8c2..00000000 --- a/config/releaser.yml +++ /dev/null @@ -1,3 +0,0 @@ -releaser: - maven: - buildCommand: ./scripts/build.sh {{systemProps}} diff --git a/docs/pom.xml b/docs/pom.xml index f94598fa..18d453df 100644 --- a/docs/pom.xml +++ b/docs/pom.xml @@ -4,17 +4,17 @@ 4.0.0 org.springframework.cloud - spring-cloud-netflix + spring-cloud-openfeign 2.0.0.BUILD-SNAPSHOT - spring-cloud-netflix-docs + spring-cloud-openfeign-docs pom - Spring Cloud Netflix Docs + Spring Cloud OpenFeign Docs Spring Cloud Docs - spring-cloud-netflix + spring-cloud-openfeign ${basedir}/.. - 1.2.x,1.3.x,1.4.x + 2.0.x diff --git a/docs/src/main/asciidoc/README.adoc b/docs/src/main/asciidoc/README.adoc index 6e0d6947..0f493a8f 100644 --- a/docs/src/main/asciidoc/README.adoc +++ b/docs/src/main/asciidoc/README.adoc @@ -1,20 +1,8 @@ -image::https://circleci.com/gh/spring-cloud/spring-cloud-netflix/tree/master.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-netflix/tree/master"] -image::https://codecov.io/gh/spring-cloud/spring-cloud-netflix/branch/master/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-netflix/branch/master"] -image::https://api.codacy.com/project/badge/Grade/a6885a06921e4f72a0df0b7aabd6d118["Codacy code quality", link="https://www.codacy.com/app/Spring-Cloud/spring-cloud-netflix?utm_source=github.com&utm_medium=referral&utm_content=spring-cloud/spring-cloud-netflix&utm_campaign=Badge_Grade"] - - include::intro.adoc[] == Features -* Service Discovery: Eureka instances can be registered and clients can discover the instances using Spring-managed beans -* Service Discovery: an embedded Eureka server can be created with declarative Java configuration -* Circuit Breaker: Hystrix clients can be built with a simple annotation-driven method decorator -* Circuit Breaker: embedded Hystrix dashboard with declarative Java configuration * Declarative REST Client: Feign creates a dynamic implementation of an interface decorated with JAX-RS or Spring MVC annotations -* Client Side Load Balancer: Ribbon -* External Configuration: a bridge from the Spring Environment to Archaius (enables native configuration of Netflix components using Spring Boot conventions) -* Router and Filter: automatic registration of Zuul filters, and a simple convention over configuration approach to reverse proxy creation == Building diff --git a/docs/src/main/asciidoc/intro.adoc b/docs/src/main/asciidoc/intro.adoc index b2425626..a69a78c5 100644 --- a/docs/src/main/asciidoc/intro.adoc +++ b/docs/src/main/asciidoc/intro.adoc @@ -1,7 +1,3 @@ -This project provides Netflix OSS integrations for Spring Boot apps through autoconfiguration -and binding to the Spring Environment and other Spring programming model idioms. With a few -simple annotations you can quickly enable and configure the common patterns inside your -application and build large distributed systems with battle-tested Netflix components. The -patterns provided include Service Discovery (Eureka), Circuit Breaker (Hystrix), -Intelligent Routing (Zuul) and Client Side Load Balancing (Ribbon). +This project provides OpenFeign integrations for Spring Boot apps through autoconfiguration +and binding to the Spring Environment and other Spring programming model idioms. diff --git a/docs/src/main/asciidoc/spring-cloud-netflix.adoc b/docs/src/main/asciidoc/spring-cloud-netflix.adoc index 29548712..81f7fea5 100644 --- a/docs/src/main/asciidoc/spring-cloud-netflix.adoc +++ b/docs/src/main/asciidoc/spring-cloud-netflix.adoc @@ -1,987 +1,17 @@ :github-tag: master -:github-repo: spring-cloud/spring-cloud-netflix +:github-repo: spring-cloud/spring-cloud-openfeign :github-raw: http://raw.github.com/{github-repo}/{github-tag} :github-code: http://github.com/{github-repo}/tree/{github-tag} :all: {asterisk}{asterisk} :nofooter: :branch: master -= Spring Cloud Netflix += Spring Cloud OpenFeign *{spring-cloud-version}* include::intro.adoc[] -== Service Discovery: Eureka Clients - -Service Discovery is one of the key tenets of a microservice based architecture. Trying to hand configure each client or some form of convention can be very difficult to do and can be very brittle. Eureka is the Netflix Service Discovery Server and Client. The server can be configured and deployed to be highly available, with each server replicating state about the registered services to the others. - -[[netflix-eureka-client-starter]] -=== How to Include Eureka Client - -To include Eureka Client in your project use the starter with group `org.springframework.cloud` -and artifact id `spring-cloud-starter-netflix-eureka-client`. See the http://projects.spring.io/spring-cloud/[Spring Cloud Project page] -for details on setting up your build system with the current Spring Cloud Release Train. - -=== Registering with Eureka - -When a client registers with Eureka, it provides meta-data about itself -such as host and port, health indicator URL, home page etc. Eureka -receives heartbeat messages from each instance belonging to a service. -If the heartbeat fails over a configurable timetable, the instance is -normally removed from the registry. - -Example eureka client: - -[source,java,indent=0] ----- -@SpringBootApplication -@RestController -public class Application { - - @RequestMapping("/") - public String home() { - return "Hello world"; - } - - public static void main(String[] args) { - new SpringApplicationBuilder(Application.class).web(true).run(args); - } - -} ----- - -(i.e. utterly normal Spring Boot app). By having `spring-cloud-starter-netflix-eureka-client` - on the classpath your application will automatically register with the Eureka Server. Configuration is required to -locate the Eureka server. Example: - - -.application.yml ----- -eureka: - client: - serviceUrl: - defaultZone: http://localhost:8761/eureka/ ----- - -where "defaultZone" is a magic string fallback value that provides the -service URL for any client that doesn't express a preference -(i.e. it's a useful default). - -The default application name (service ID), virtual host and non-secure -port, taken from the `Environment`, are `${spring.application.name}`, -`${spring.application.name}` and `${server.port}` respectively. - -Having `spring-cloud-starter-netflix-eureka-client` on the classpath -makes the app into both a Eureka "instance" -(i.e. it registers itself) and a "client" (i.e. it can query the -registry to locate other services). The instance behaviour is driven -by `eureka.instance.*` configuration keys, but the defaults will be -fine if you ensure that your application has a -`spring.application.name` (this is the default for the Eureka service -ID, or VIP). - -See {github-code}/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBean.java[EurekaInstanceConfigBean] and {github-code}/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBean.java[EurekaClientConfigBean] for more details of the configurable options. - -To disable the Eureka Discovery Client you can set `eureka.client.enabled` to `false`. - -=== Authenticating with the Eureka Server - -HTTP basic authentication will be automatically added to your eureka -client if one of the `eureka.client.serviceUrl.defaultZone` URLs has -credentials embedded in it (curl style, like -`http://user:password@localhost:8761/eureka`). For more complex needs -you can create a `@Bean` of type `DiscoveryClientOptionalArgs` and -inject `ClientFilter` instances into it, all of which will be applied -to the calls from the client to the server. - -NOTE: Because of a limitation in Eureka it isn't possible to support -per-server basic auth credentials, so only the first set that are -found will be used. - -=== Status Page and Health Indicator - -The status page and health indicators for a Eureka instance default to -"/info" and "/health" respectively, which are the default locations of -useful endpoints in a Spring Boot Actuator application. You need to -change these, even for an Actuator application if you use a -non-default context path or servlet path -(e.g. `server.servletPath=/foo`) or management endpoint path -(e.g. `management.contextPath=/admin`). Example: - -.application.yml ----- -eureka: - instance: - statusPageUrlPath: ${management.context-path}/info - healthCheckUrlPath: ${management.context-path}/health ----- - -These links show up in the metadata that is consumed by clients, and -used in some scenarios to decide whether to send requests to your -application, so it's helpful if they are accurate. - -=== Registering a Secure Application - -If your app wants to be contacted over HTTPS you can set two flags in -the `EurekaInstanceConfig`, _viz_ -`eureka.instance.[nonSecurePortEnabled,securePortEnabled]=[false,true]` -respectively. This will make Eureka publish instance information -showing an explicit preference for secure communication. The Spring -Cloud `DiscoveryClient` will always return a URI starting with `https` for a -service configured this way, and the Eureka (native) instance -information will have a secure health check URL. - -Because of the way -Eureka works internally, it will still publish a non-secure URL for -status and home page unless you also override those explicitly. -You can use placeholders to configure the eureka instance urls, -e.g. - -.application.yml ----- -eureka: - instance: - statusPageUrl: https://${eureka.hostname}/info - healthCheckUrl: https://${eureka.hostname}/health - homePageUrl: https://${eureka.hostname}/ ----- - -(Note that `${eureka.hostname}` is a native placeholder only available -in later versions of Eureka. You could achieve the same thing with -Spring placeholders as well, e.g. using `${eureka.instance.hostName}`.) - -NOTE: If your app is running behind a proxy, and the SSL termination -is in the proxy (e.g. if you run in Cloud Foundry or other platforms -as a service) then you will need to ensure that the proxy "forwarded" -headers are intercepted and handled by the application. An embedded -Tomcat container in a Spring Boot app does this automatically if it -has explicit configuration for the 'X-Forwarded-\*` headers. A sign -that you got this wrong will be that the links rendered by your app to -itself will be wrong (the wrong host, port or protocol). - -=== Eureka's Health Checks - -By default, Eureka uses the client heartbeat to determine if a client is up. -Unless specified otherwise the Discovery Client will not propagate the -current health check status of the application per the Spring Boot Actuator. Which means -that after successful registration Eureka will always announce that the -application is in 'UP' state. This behaviour can be altered by enabling -Eureka health checks, which results in propagating application status -to Eureka. As a consequence every other application won't be sending -traffic to application in state other then 'UP'. - -.application.yml ----- -eureka: - client: - healthcheck: - enabled: true ----- - -WARNING: `eureka.client.healthcheck.enabled=true` should only be set in `application.yml`. Setting the value in `bootstrap.yml` will cause undesirable side effects like registering in eureka with an `UNKNOWN` status. - -If you require more control over the health checks, you may consider -implementing your own `com.netflix.appinfo.HealthCheckHandler`. - -=== Eureka Metadata for Instances and Clients - -It's worth spending a bit of time understanding how the Eureka metadata works, so you can use it in a way that makes sense in your platform. There is standard metadata for things like hostname, IP address, port numbers, status page and health check. These are published in the service registry and used by clients to contact the services in a straightforward way. Additional metadata can be added to the instance registration in the `eureka.instance.metadataMap`, and this will be accessible in the remote clients, but in general will not change the behaviour of the client, unless it is made aware of the meaning of the metadata. There are a couple of special cases described below where Spring Cloud already assigns meaning to the metadata map. - -==== Using Eureka on Cloudfoundry - -Cloudfoundry has a global router so that all instances of the same app have the same hostname (it's the same in other PaaS solutions with a similar architecture). This isn't necessarily a barrier to using Eureka, but if you use the router (recommended, or even mandatory depending on the way your platform was set up), you need to explicitly set the hostname and port numbers (secure or non-secure) so that they use the router. You might also want to use instance metadata so you can distinguish between the instances on the client (e.g. in a custom load balancer). By default, the `eureka.instance.instanceId` is `vcap.application.instance_id`. For example: - -.application.yml ----- -eureka: - instance: - hostname: ${vcap.application.uris[0]} - nonSecurePort: 80 ----- - -Depending on the way the security rules are set up in your Cloudfoundry instance, you might be able to register and use the IP address of the host VM for direct service-to-service calls. This feature is not (yet) available on Pivotal Web Services (https://run.pivotal.io[PWS]). - -==== Using Eureka on AWS - -If the application is planned to be deployed to an AWS cloud, then the Eureka instance will have to be configured to be AWS aware and this can be done by customizing the {github-code}/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBean.java[EurekaInstanceConfigBean] the following way: - -[source,java,indent=0] ----- -@Bean -@Profile("!default") -public EurekaInstanceConfigBean eurekaInstanceConfig(InetUtils inetUtils) { - EurekaInstanceConfigBean b = new EurekaInstanceConfigBean(inetUtils); - AmazonInfo info = AmazonInfo.Builder.newBuilder().autoBuild("eureka"); - b.setDataCenterInfo(info); - return b; -} ----- - -==== Changing the Eureka Instance ID - -A vanilla Netflix Eureka instance is registered with an ID that is equal to its host name (i.e. only one service per host). Spring Cloud Eureka provides a sensible default that looks like this: `${spring.cloud.client.hostname}:${spring.application.name}:${spring.application.instance_id:${server.port}}}`. For example `myhost:myappname:8080`. - -Using Spring Cloud you can override this by providing a unique identifier in `eureka.instance.instanceId`. For example: - -.application.yml ----- -eureka: - instance: - instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}} ----- - -With this metadata, and multiple service instances deployed on -localhost, the random value will kick in there to make the instance -unique. In Cloudfoundry the `vcap.application.instance_id` will be -populated automatically in a Spring Boot application, so the -random value will not be needed. - -=== Using the EurekaClient - -Once you have an app that is a discovery client you can use it to -discover service instances from the <>. One way to do that is to use the native -`com.netflix.discovery.EurekaClient` (as opposed to the Spring -Cloud `DiscoveryClient`), e.g. - ----- -@Autowired -private EurekaClient discoveryClient; - -public String serviceUrl() { - InstanceInfo instance = discoveryClient.getNextServerFromEureka("STORES", false); - return instance.getHomePageUrl(); -} ----- - -[TIP] -==== -Don't use the `EurekaClient` in `@PostConstruct` method or in a -`@Scheduled` method (or anywhere where the `ApplicationContext` might -not be started yet). It is initialized in a `SmartLifecycle` (with -`phase=0`) so the earliest you can rely on it being available is in -another `SmartLifecycle` with higher phase. -==== - -==== EurekaClient without Jersey - -By default, EurekaClient uses Jersey for HTTP communication. If you wish -to avoid dependencies from Jersey, you can exclude it from your dependencies. -Spring Cloud will auto configure a transport client based on Spring -`RestTemplate`. - ----- - - org.springframework.cloud - spring-cloud-starter-netflix-eureka-client - - - com.sun.jersey - jersey-client - - - com.sun.jersey - jersey-core - - - com.sun.jersey.contribs - jersey-apache-client4 - - - ----- - -=== Alternatives to the native Netflix EurekaClient - -You don't have to use the raw Netflix `EurekaClient` and usually it -is more convenient to use it behind a wrapper of some sort. Spring -Cloud has support for <> (a REST client -builder) and also <> using -the logical Eureka service identifiers (VIPs) instead of physical -URLs. To configure Ribbon with a fixed list of physical servers you -can simply set `.ribbon.listOfServers` to a comma-separated -list of physical addresses (or hostnames), where `` is the ID -of the client. - -You can also use the `org.springframework.cloud.client.discovery.DiscoveryClient` -which provides a simple API for discovery clients that is not specific -to Netflix, e.g. - ----- -@Autowired -private DiscoveryClient discoveryClient; - -public String serviceUrl() { - List list = discoveryClient.getInstances("STORES"); - if (list != null && list.size() > 0 ) { - return list.get(0).getUri(); - } - return null; -} ----- - -=== Why is it so Slow to Register a Service? - -Being an instance also involves a periodic heartbeat to the registry -(via the client's `serviceUrl`) with default duration 30 seconds. A -service is not available for discovery by clients until the instance, -the server and the client all have the same metadata in their local -cache (so it could take 3 heartbeats). You can change the period using -`eureka.instance.leaseRenewalIntervalInSeconds` and this will speed up -the process of getting clients connected to other services. In -production it's probably better to stick with the default because -there are some computations internally in the server that make -assumptions about the lease renewal period. - - -=== Zones - -If you have deployed Eureka clients to multiple zones than you may prefer that -those clients leverage services within the same zone before trying services -in another zone. To do this you need to configure your Eureka clients correctly. - -First, you need to make sure you have Eureka servers deployed to each zone and that -they are peers of each other. See the section on <> -for more information. - -Next you need to tell Eureka which zone your service is in. You can do this using -the `metadataMap` property. For example if `service 1` is deployed to both `zone 1` -and `zone 2` you would need to set the following Eureka properties in `service 1` - -*Service 1 in Zone 1* -``` -eureka.instance.metadataMap.zone = zone1 -eureka.client.preferSameZoneEureka = true -``` - -*Service 1 in Zone 2* -``` -eureka.instance.metadataMap.zone = zone2 -eureka.client.preferSameZoneEureka = true -``` - -[[spring-cloud-eureka-server]] -== Service Discovery: Eureka Server - -[[netflix-eureka-server-starter]] -=== How to Include Eureka Server - -To include Eureka Server in your project use the starter with group `org.springframework.cloud` -and artifact id `spring-cloud-starter-netflix-eureka-server`. See the http://projects.spring.io/spring-cloud/[Spring Cloud Project page] -for details on setting up your build system with the current Spring Cloud Release Train. - -[[spring-cloud-running-eureka-server]] -=== How to Run a Eureka Server - -Example eureka server; - -[source,java,indent=0] ----- -@SpringBootApplication -@EnableEurekaServer -public class Application { - - public static void main(String[] args) { - new SpringApplicationBuilder(Application.class).web(true).run(args); - } - -} ----- - -The server has a home page with a UI, and HTTP API endpoints per the -normal Eureka functionality under `/eureka/*`. - -Eureka background reading: see https://github.com/cfregly/fluxcapacitor/wiki/NetflixOSS-FAQ#eureka-service-discovery-load-balancer[flux capacitor] and https://groups.google.com/forum/?fromgroups#!topic/eureka_netflix/g3p2r7gHnN0[google group discussion]. - - -[TIP] -==== -Due to Gradle's dependency resolution rules and the lack of a parent bom feature, simply depending on spring-cloud-starter-netflix-eureka-server can cause failures on application startup. To remedy this the Spring Boot Gradle plugin must be added and the Spring cloud starter parent bom must be imported like so: - -.build.gradle -[source,java,indent=0] ----- -buildscript { - dependencies { - classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.5.RELEASE") - } -} - -apply plugin: "spring-boot" - -dependencyManagement { - imports { - mavenBom "org.springframework.cloud:spring-cloud-dependencies:Brixton.RELEASE" - } -} ----- -==== - -[[spring-cloud-eureka-server-zones-and-regions]] -=== High Availability, Zones and Regions - -The Eureka server does not have a backend store, but the service -instances in the registry all have to send heartbeats to keep their -registrations up to date (so this can be done in memory). Clients also -have an in-memory cache of eureka registrations (so they don't have to -go to the registry for every single request to a service). - -By default every Eureka server is also a Eureka client and requires -(at least one) service URL to locate a peer. If you don't provide it -the service will run and work, but it will shower your logs with a lot -of noise about not being able to register with the peer. - -See also <> on the client side for Zones and Regions. - -=== Standalone Mode - -The combination of the two caches (client and server) and the -heartbeats make a standalone Eureka server fairly resilient to -failure, as long as there is some sort of monitor or elastic runtime -keeping it alive (e.g. Cloud Foundry). In standalone mode, you might -prefer to switch off the client side behaviour, so it doesn't keep -trying and failing to reach its peers. Example: - -.application.yml (Standalone Eureka Server) ----- -server: - port: 8761 - -eureka: - instance: - hostname: localhost - client: - registerWithEureka: false - fetchRegistry: false - serviceUrl: - defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ ----- - -Notice that the `serviceUrl` is pointing to the same host as the local -instance. - -=== Peer Awareness - -Eureka can be made even more resilient and available by running -multiple instances and asking them to register with each other. In -fact, this is the default behaviour, so all you need to do to make it -work is add a valid `serviceUrl` to a peer, e.g. - -.application.yml (Two Peer Aware Eureka Servers) ----- - ---- -spring: - profiles: peer1 -eureka: - instance: - hostname: peer1 - client: - serviceUrl: - defaultZone: http://peer2/eureka/ - ---- -spring: - profiles: peer2 -eureka: - instance: - hostname: peer2 - client: - serviceUrl: - defaultZone: http://peer1/eureka/ ----- - -In this example we have a YAML file that can be used to run the same -server on 2 hosts (peer1 and peer2), by running it in different -Spring profiles. You could use this configuration to test the peer -awareness on a single host (there's not much value in doing that in -production) by manipulating `/etc/hosts` to resolve the host names. In -fact, the `eureka.instance.hostname` is not needed if you are running -on a machine that knows its own hostname (it is looked up using -`java.net.InetAddress` by default). - -You can add multiple peers to a system, and as long as they are all -connected to each other by at least one edge, they will synchronize -the registrations amongst themselves. If the peers are physically -separated (inside a data centre or between multiple data centres) then -the system can in principle survive split-brain type failures. - -=== Prefer IP Address - -In some cases, it is preferable for Eureka to advertise the IP Adresses -of services rather than the hostname. Set `eureka.instance.preferIpAddress` -to `true` and when the application registers with eureka, it will use its -IP Address rather than its hostname. - -[TIP] -==== -If hostname can't be determined by Java, then IP address is sent to Eureka. -Only explict way of setting hostname is by using `eureka.instance.hostname`. -You can set your hostname at the run time using environment variable, for -example `eureka.instance.hostname=${HOST_NAME}`. -==== - -== Circuit Breaker: Hystrix Clients - -Netflix has created a library called https://github.com/Netflix/Hystrix[Hystrix] that implements the http://martinfowler.com/bliki/CircuitBreaker.html[circuit breaker pattern]. In a microservice architecture it is common to have multiple layers of service calls. - -.Microservice Graph -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-netflix/{branch}/docs/src/main/asciidoc/images/Hystrix.png[] - -A service failure in the lower level of services can cause cascading failure all the way up to the user. When calls to a particular service is greater than `circuitBreaker.requestVolumeThreshold` (default: 20 requests) and failue percentage is greater than `circuitBreaker.errorThresholdPercentage` (default: >50%) in a rolling window defined by `metrics.rollingStats.timeInMilliseconds` (default: 10 seconds), the circuit opens and the call is not made. In cases of error and an open circuit a fallback can be provided by the developer. - -.Hystrix fallback prevents cascading failures -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-netflix/{branch}/docs/src/main/asciidoc/images/HystrixFallback.png[] - -Having an open circuit stops cascading failures and allows overwhelmed or failing services time to heal. The fallback can be another Hystrix protected call, static data or a sane empty value. Fallbacks may be chained so the first fallback makes some other business call which in turn falls back to static data. - - -[[netflix-hystrix-starter]] -=== How to Include Hystrix - -To include Hystrix in your project use the starter with group `org.springframework.cloud` -and artifact id `spring-cloud-starter-netflix-hystrix`. See the http://projects.spring.io/spring-cloud/[Spring Cloud Project page] -for details on setting up your build system with the current Spring Cloud Release Train. - -Example boot app: - ----- -@SpringBootApplication -@EnableCircuitBreaker -public class Application { - - public static void main(String[] args) { - new SpringApplicationBuilder(Application.class).web(true).run(args); - } - -} - -@Component -public class StoreIntegration { - - @HystrixCommand(fallbackMethod = "defaultStores") - public Object getStores(Map parameters) { - //do stuff that might fail - } - - public Object defaultStores(Map parameters) { - return /* something useful */; - } -} - ----- - -The `@HystrixCommand` is provided by a Netflix contrib library called -https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica["javanica"]. -Spring Cloud automatically wraps Spring beans with that -annotation in a proxy that is connected to the Hystrix circuit -breaker. The circuit breaker calculates when to open and close the -circuit, and what to do in case of a failure. - -To configure the `@HystrixCommand` you can use the `commandProperties` -attribute with a list of `@HystrixProperty` annotations. See -https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica#configuration[here] -for more details. See the https://github.com/Netflix/Hystrix/wiki/Configuration[Hystrix wiki] -for details on the properties available. - -=== Propagating the Security Context or using Spring Scopes - -If you want some thread local context to propagate into a `@HystrixCommand` the default declaration will not work because it executes the command in a thread pool (in case of timeouts). You can switch Hystrix to use the same thread as the caller using some configuration, or directly in the annotation, by asking it to use a different "Isolation Strategy". For example: - -[source,java] ----- -@HystrixCommand(fallbackMethod = "stubMyService", - commandProperties = { - @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE") - } -) -... ----- - -The same thing applies if you are using `@SessionScope` or `@RequestScope`. You will know when you need to do this because of a runtime exception that says it can't find the scoped context. - -You also have the option to set the `hystrix.shareSecurityContext` property to `true`. Doing so will auto configure an Hystrix concurrency strategy plugin hook who will transfer the `SecurityContext` from your main thread to the one used by the Hystrix command. Hystrix does not allow multiple hystrix concurrency strategy to be registered so an extension mechanism is available by declaring your own `HystrixConcurrencyStrategy` as a Spring bean. Spring Cloud will lookup for your implementation within the Spring context and wrap it inside its own plugin. - -### Health Indicator - -The state of the connected circuit breakers are also exposed in the -`/health` endpoint of the calling application. - -[source,json,indent=0] ----- -{ - "hystrix": { - "openCircuitBreakers": [ - "StoreIntegration::getStoresByLocationLink" - ], - "status": "CIRCUIT_OPEN" - }, - "status": "UP" -} ----- - -=== Hystrix Metrics Stream - -To enable the Hystrix metrics stream include a dependency on `spring-boot-starter-actuator`. This will expose the `/hystrix.stream` as a management endpoint. - -[source,xml] ----- - - org.springframework.boot - spring-boot-starter-actuator - ----- - -== Circuit Breaker: Hystrix Dashboard - -One of the main benefits of Hystrix is the set of metrics it gathers about each HystrixCommand. The Hystrix Dashboard displays the health of each circuit breaker in an efficient manner. - -.Hystrix Dashboard -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-netflix/{branch}/docs/src/main/asciidoc/images/Hystrix.png[] - -== Hystrix Timeouts And Ribbon Clients - -When using Hystrix commands that wrap Ribbon clients you want to make sure your Hystrix timeout -is configured to be longer than the configured Ribbon timeout, including any potential -retries that might be made. For example, if your Ribbon connection timeout is one second and -the Ribbon client might retry the request three times, than your Hystrix timeout should -be slightly more than three seconds. - - -[[netflix-hystrix-dashboard-starter]] -=== How to Include Hystrix Dashboard - -To include the Hystrix Dashboard in your project use the starter with group `org.springframework.cloud` -and artifact id `spring-cloud-starter-netflix-hystrix-dashboard`. See the http://projects.spring.io/spring-cloud/[Spring Cloud Project page] -for details on setting up your build system with the current Spring Cloud Release Train. - -To run the Hystrix Dashboard annotate your Spring Boot main class with `@EnableHystrixDashboard`. You then visit `/hystrix` and point the dashboard to an individual instances `/hystrix.stream` endpoint in a Hystrix client application. - -NOTE: When connecting to a `/hystrix.stream` endpoint which uses HTTPS the certificate used by the server -must be trusted by the JVM. If the certificate is not trusted you must import the certificate into the JVM -in order for the Hystrix Dashboard to make a successful connection to the stream endpoint. - -=== Turbine - -Looking at an individual instances Hystrix data is not very useful in terms of the overall health of the system. https://github.com/Netflix/Turbine[Turbine] is an application that aggregates all of the relevant `/hystrix.stream` endpoints into a combined `/turbine.stream` for use in the Hystrix Dashboard. Individual instances are located via Eureka. Running Turbine is as simple as annotating your main class with the `@EnableTurbine` annotation (e.g. using spring-cloud-starter-netflix-turbine to set up the classpath). All of the documented configuration properties from https://github.com/Netflix/Turbine/wiki/Configuration-(1.x)[the Turbine 1 wiki] apply. The only difference is that the `turbine.instanceUrlSuffix` does not need the port prepended as this is handled automatically unless `turbine.instanceInsertPort=false`. - -NOTE: By default, Turbine looks for the `/hystrix.stream` endpoint on a registered instance by looking up its `hostName` and `port` entries in Eureka, then appending `/hystrix.stream` to it. -If the instance's metadata contains `management.port`, it will be used instead of the `port` value for the `/hystrix.stream` endpoint. -By default, metadata entry `management.port` is equal to the `management.port` configuration property, it can be overridden though with following configuration: ----- -eureka: - instance: - metadata-map: - management.port: ${management.port:8081} ----- - - -The configuration key `turbine.appConfig` is a list of eureka serviceIds that turbine will use to lookup instances. The turbine stream is then used in the Hystrix dashboard using a url that looks like: `http://my.turbine.server:8080/turbine.stream?cluster=CLUSTERNAME` (the cluster parameter can be omitted if the name is "default"). The `cluster` parameter must match an entry in `turbine.aggregator.clusterConfig`. Values returned from eureka are uppercase, thus we expect this example to work if there is an app registered with Eureka called "customers": - ----- -turbine: - aggregator: - clusterConfig: CUSTOMERS - appConfig: customers ----- - -If you need to customize which cluster names should be used by Turbine (you don't want to store cluster names in -`turbine.aggregator.clusterConfig` configuration) provide a bean of type `TurbineClustersProvider`. - -The `clusterName` can be customized by a SPEL expression in `turbine.clusterNameExpression` with root an instance of `InstanceInfo`. The default value is `appName`, which means that the Eureka serviceId ends up as the cluster key (i.e. the `InstanceInfo` for customers has an `appName` of "CUSTOMERS"). A different example would be `turbine.clusterNameExpression=aSGName`, which would get the cluster name from the AWS ASG name. Another example: - ----- -turbine: - aggregator: - clusterConfig: SYSTEM,USER - appConfig: customers,stores,ui,admin - clusterNameExpression: metadata['cluster'] ----- - -In this case, the cluster name from 4 services is pulled from their metadata map, and is expected to have values that include "SYSTEM" and "USER". - -To use the "default" cluster for all apps you need a string literal expression (with single quotes, and escaped with double quotes if it is in YAML as well): - ----- -turbine: - appConfig: customers,stores - clusterNameExpression: "'default'" ----- - -Spring Cloud provides a `spring-cloud-starter-netflix-turbine` that has all the dependencies you need to get a Turbine server running. Just create a Spring Boot application and annotate it with `@EnableTurbine`. - -NOTE: by default Spring Cloud allows Turbine to use the host and port to allow multiple processes per host, per cluster. If you want the native Netflix behaviour built into Turbine that does _not_ allow multiple processes per host, per cluster (the key to the instance id is the hostname), then set the property `turbine.combineHostPort=false`. - -=== Turbine Stream - -In some environments (e.g. in a PaaS setting), the classic Turbine model of pulling metrics from all the distributed Hystrix commands doesn't work. In that case you might want to have your Hystrix commands push metrics to Turbine, and Spring Cloud enables that with messaging. All you need to do on the client is add a dependency to `spring-cloud-netflix-hystrix-stream` and the `spring-cloud-starter-stream-*` of your choice (see Spring Cloud Stream documentation for details on the brokers, and how to configure the client credentials, but it should work out of the box for a local broker). - -On the server side Just create a Spring Boot application and annotate it with `@EnableTurbineStream` and by default it will come up on port 8989 (point your Hystrix dashboard to that port, any path). You can customize the port using either `server.port` or `turbine.stream.port`. If you have `spring-boot-starter-web` and `spring-boot-starter-actuator` on the classpath as well, then you can open up the Actuator endpoints on a separate port (with Tomcat by default) by providing a `management.port` which is different. - -You can then point the Hystrix Dashboard to the Turbine Stream Server instead of individual Hystrix streams. If Turbine Stream is running on port 8989 on myhost, then put `http://myhost:8989` in the stream input field in the Hystrix Dashboard. Circuits will be prefixed by their respective serviceId, followed by a dot, then the circuit name. - -Spring Cloud provides a `spring-cloud-starter-netflix-turbine-stream` that has all the dependencies you need to get a Turbine Stream server running - just add the Stream binder of your choice, e.g. `spring-cloud-starter-stream-rabbit`. You need Java 8 to run the app because it is Netty-based. - -[[spring-cloud-ribbon]] -== Client Side Load Balancer: Ribbon - -Ribbon is a client side load balancer which gives you a lot of control -over the behaviour of HTTP and TCP clients. Feign already uses Ribbon, -so if you are using `@FeignClient` then this section also applies. - -A central concept in Ribbon is that of the named client. Each load -balancer is part of an ensemble of components that work together to -contact a remote server on demand, and the ensemble has a name that -you give it as an application developer (e.g. using the `@FeignClient` -annotation). Spring Cloud creates a new ensemble as an -`ApplicationContext` on demand for each named client using -`RibbonClientConfiguration`. This contains (amongst other things) an -`ILoadBalancer`, a `RestClient`, and a `ServerListFilter`. - -[[netflix-ribbon-starter]] -=== How to Include Ribbon - -To include Ribbon in your project use the starter with group `org.springframework.cloud` -and artifact id `spring-cloud-starter-netflix-ribbon`. See the http://projects.spring.io/spring-cloud/[Spring Cloud Project page] -for details on setting up your build system with the current Spring Cloud Release Train. - -=== Customizing the Ribbon Client - -You can configure some bits of a Ribbon client using external -properties in `.ribbon.*`, which is no different than using -the Netflix APIs natively, except that you can use Spring Boot -configuration files. The native options can -be inspected as static fields in https://github.com/Netflix/ribbon/blob/master/ribbon-core/src/main/java/com/netflix/client/config/CommonClientConfigKey.java[`CommonClientConfigKey`] (part of -ribbon-core). - -Spring Cloud also lets you take full control of the client by -declaring additional configuration (on top of the -`RibbonClientConfiguration`) using `@RibbonClient`. Example: - -[source,java,indent=0] ----- -@Configuration -@RibbonClient(name = "foo", configuration = FooConfiguration.class) -public class TestConfiguration { -} ----- - -In this case the client is composed from the components already in -`RibbonClientConfiguration` together with any in `FooConfiguration` -(where the latter generally will override the former). - -WARNING: The `FooConfiguration` has to be `@Configuration` but take -care that it is not in a `@ComponentScan` for the main application -context, otherwise it will be shared by all the `@RibbonClients`. If -you use `@ComponentScan` (or `@SpringBootApplication`) you need to -take steps to avoid it being included (for instance put it in a -separate, non-overlapping package, or specify the packages to scan -explicitly in the `@ComponentScan`). - -Spring Cloud Netflix provides the following beans by default for ribbon -(`BeanType` beanName: `ClassName`): - -* `IClientConfig` ribbonClientConfig: `DefaultClientConfigImpl` -* `IRule` ribbonRule: `ZoneAvoidanceRule` -* `IPing` ribbonPing: `DummyPing` -* `ServerList` ribbonServerList: `ConfigurationBasedServerList` -* `ServerListFilter` ribbonServerListFilter: `ZonePreferenceServerListFilter` -* `ILoadBalancer` ribbonLoadBalancer: `ZoneAwareLoadBalancer` -* `ServerListUpdater` ribbonServerListUpdater: `PollingServerListUpdater` - -Creating a bean of one of those type and placing it in a `@RibbonClient` -configuration (such as `FooConfiguration` above) allows you to override each -one of the beans described. Example: - -[source,java,indent=0] ----- -include::../../../../spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientsPreprocessorIntegrationTests.java[tags=sample_override_ribbon_config,indent=0] ----- - -This replaces the `NoOpPing` with `PingUrl` and provides a custom `serverListFilter` - -=== Customizing default for all Ribbon Clients -A default configuration can be provided for all Ribbon Clients using the `@RibbonClients` annotation and registering a default configuration as shown in the following example: -[source,java,indent=0] ----- -include::../../../../spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/ribbon/test/RibbonClientDefaultConfigurationTestsConfig.java[tags=sample_default_ribbon_config,indent=0] - ----- - -=== Customizing the Ribbon Client using properties - -Starting with version 1.2.0, Spring Cloud Netflix now supports customizing Ribbon clients using properties to be compatible with the https://github.com/Netflix/ribbon/wiki/Working-with-load-balancers#components-of-load-balancer[Ribbon documentation]. - -This allows you to change behavior at start up time in different environments. - -The supported properties are listed below and should be prefixed by `.ribbon.`: - -* `NFLoadBalancerClassName`: should implement `ILoadBalancer` -* `NFLoadBalancerRuleClassName`: should implement `IRule` -* `NFLoadBalancerPingClassName`: should implement `IPing` -* `NIWSServerListClassName`: should implement `ServerList` -* `NIWSServerListFilterClassName` should implement `ServerListFilter` - -NOTE: Classes defined in these properties have precedence over beans defined using `@RibbonClient(configuration=MyRibbonConfig.class)` and the defaults provided by Spring Cloud Netflix. - -To set the `IRule` for a service name `users` you could set the following: - -.application.yml ----- -users: - ribbon: - NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList - NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule ----- - -See the https://github.com/Netflix/ribbon/wiki/Working-with-load-balancers[Ribbon documentation] for implementations provided by Ribbon. - -=== Using Ribbon with Eureka - -When Eureka is used in conjunction with Ribbon (i.e., both are on the classpath) the `ribbonServerList` -is overridden with an extension of `DiscoveryEnabledNIWSServerList` -which populates the list of servers from Eureka. It also replaces the -`IPing` interface with `NIWSDiscoveryPing` which delegates to Eureka -to determine if a server is up. The `ServerList` that is installed by -default is a `DomainExtractingServerList` and the purpose of this is -to make physical metadata available to the load balancer without using -AWS AMI metadata (which is what Netflix relies on). By default the -server list will be constructed with "zone" information as provided in -the instance metadata (so on the remote clients set -`eureka.instance.metadataMap.zone`), and if that is missing it can use -the domain name from the server hostname as a proxy for zone (if the -flag `approximateZoneFromHostname` is set). Once the zone information -is available it can be used in a `ServerListFilter`. By default it -will be used to locate a server in the same zone as the client because -the default is a `ZonePreferenceServerListFilter`. The zone of the -client is determined the same way as the remote instances by default, -i.e. via `eureka.instance.metadataMap.zone`. - -NOTE: The orthodox "archaius" way to set the client zone is via a -configuration property called "@zone", and Spring Cloud will use that -in preference to all other settings if it is available (note that the -key will have to be quoted in YAML configuration). - -NOTE: If there is no other source of zone data then a guess is made -based on the client configuration (as opposed to the instance -configuration). We take `eureka.client.availabilityZones`, which is a -map from region name to a list of zones, and pull out the first zone -for the instance's own region (i.e. the `eureka.client.region`, which -defaults to "us-east-1" for comatibility with native Netflix). - -[[spring-cloud-ribbon-without-eureka]] -=== Example: How to Use Ribbon Without Eureka - -Eureka is a convenient way to abstract the discovery of remote servers -so you don't have to hard code their URLs in clients, but if you -prefer not to use it, Ribbon and Feign are still quite -amenable. Suppose you have declared a `@RibbonClient` for "stores", -and Eureka is not in use (and not even on the classpath). The Ribbon -client defaults to a configured server list, and you can supply the -configuration like this - -.application.yml ----- -stores: - ribbon: - listOfServers: example.com,google.com ----- - -=== Example: Disable Eureka use in Ribbon - -Setting the property `ribbon.eureka.enabled = false` will explicitly -disable the use of Eureka in Ribbon. - -.application.yml ----- -ribbon: - eureka: - enabled: false ----- - -=== Using the Ribbon API Directly - -You can also use the `LoadBalancerClient` directly. Example: - -[source,java,indent=0] ----- -public class MyClass { - @Autowired - private LoadBalancerClient loadBalancer; - - public void doStuff() { - ServiceInstance instance = loadBalancer.choose("stores"); - URI storesUri = URI.create(String.format("http://%s:%s", instance.getHost(), instance.getPort())); - // ... do something with the URI - } -} ----- - -[[ribbon-child-context-eager-load]] -=== Caching of Ribbon Configuration - -Each Ribbon named client has a corresponding child Application Context that Spring Cloud maintains, this application context is lazily loaded up on the first request to the named client. -This lazy loading behavior can be changed to instead eagerly load up these child Application contexts at startup by specifying the names of the Ribbon clients. - -.application.yml ----- -ribbon: - eager-load: - enabled: true - clients: client1, client2, client3 ----- - -[[how-to-configure-hystrix-thread-pools]] -=== How to Configure Hystrix thread pools -If you change `zuul.ribbonIsolationStrategy` to THREAD, the thread isolation strategy for Hystrix will be used for all routes. In this case, the HystrixThreadPoolKey is set to "RibbonCommand" as default. It means that HystrixCommands for all routes will be executed in the same Hystrix thread pool. This behavior can be changed using the following configuration and it will result in HystrixCommands being executed in the Hystrix thread pool for each route. - -.application.yml ----- -zuul: - threadPool: - useSeparateThreadPools: true ----- - -The default HystrixThreadPoolKey in this case is same with service ID for each route. To add a prefix to HystrixThreadPoolKey, set `zuul.threadPool.threadPoolKeyPrefix` to a value that you want to add. For example: - -.application.yml ----- -zuul: - threadPool: - useSeparateThreadPools: true - threadPoolKeyPrefix: zuulgw ----- - -[[how-to-provdie-a-key-to-ribbon]] -=== How to Provide a Key to Ribbon's `IRule` - -If you need to provide your own `IRule` implementation to handle a special routing requirement like a canary test, -you probably want to pass some information to the `choose` method of `IRule`. - -.com.netflix.loadbalancer.IRule.java ----- -public interface IRule{ - public Server choose(Object key); - : ----- - -You can provide some information that will be used to choose a target server by your `IRule` implementation like -the following: - ----- -RequestContext.getCurrentContext() - .set(FilterConstants.LOAD_BALANCER_KEY, "canary-test"); ----- - -If you put any object into the `RequestContext` with a key `FilterConstants.LOAD_BALANCER_KEY`, it will -be passed to the `choose` method of `IRule` implementation. Above code must be executed before `RibbonRoutingFilter` -is executed and Zuul's pre filter is the best place to do that. You can easily access HTTP headers and query parameters -via `RequestContext` in pre filter, so it can be used to determine `LOAD_BALANCER_KEY` that will be passed to Ribbon. -If you don't put any value with `LOAD_BALANCER_KEY` in `RequestContext`, null will be passed as a parameter of `choose` -method. - [[spring-cloud-feign]] == Declarative REST Client: Feign @@ -1393,1353 +423,11 @@ public class FooConfiguration { } } ---- - -== External Configuration: Archaius - -https://github.com/Netflix/archaius[Archaius] is the Netflix client side configuration library. It is the library used by all of the Netflix OSS components for configuration. Archaius is an extension of the http://commons.apache.org/proper/commons-configuration[Apache Commons Configuration] project. It allows updates to configuration by either polling a source for changes or for a source to push changes to the client. Archaius uses DynamicProperty classes as handles to properties. - -.Archaius Example -[source,java] ----- -class ArchaiusTest { - DynamicStringProperty myprop = DynamicPropertyFactory - .getInstance() - .getStringProperty("my.prop"); - - void doSomething() { OtherClass.someMethod(myprop.get()); } } ----- - -Archaius has its own set of configuration files and loading priorities. Spring applications should generally not use Archaius directly, but the need to configure the Netflix tools natively remains. Spring Cloud has a Spring Environment Bridge so Archaius can read properties from the Spring Environment. This allows Spring Boot projects to use the normal configuration toolchain, while allowing them to configure the Netflix tools, for the most part, as documented. - -== Router and Filter: Zuul - -Routing is an integral part of a microservice architecture. For example, `/` may be mapped to your web application, `/api/users` is mapped to the user service and `/api/shop` is mapped to the shop service. https://github.com/Netflix/zuul[Zuul] is a JVM based router and server side load balancer by Netflix. - -http://www.slideshare.net/MikeyCohen1/edge-architecture-ieee-international-conference-on-cloud-engineering-32240146/27[Netflix uses Zuul] for the following: - -* Authentication -* Insights -* Stress Testing -* Canary Testing -* Dynamic Routing -* Service Migration -* Load Shedding -* Security -* Static Response handling -* Active/Active traffic management - -Zuul's rule engine allows rules and filters to be written in essentially any JVM language, with built in support for Java and Groovy. - -NOTE: The configuration property `zuul.max.host.connections` has been replaced by two new properties, `zuul.host.maxTotalConnections` and `zuul.host.maxPerRouteConnections` which default to 200 and 20 respectively. - -NOTE: Default Hystrix isolation pattern (ExecutionIsolationStrategy) for all routes is SEMAPHORE. `zuul.ribbonIsolationStrategy` can be changed to THREAD if this isolation pattern is preferred. - -[[netflix-zuul-starter]] -=== How to Include Zuul - -To include Zuul in your project use the starter with group `org.springframework.cloud` -and artifact id `spring-cloud-starter-netflix-zuul`. See the http://projects.spring.io/spring-cloud/[Spring Cloud Project page] -for details on setting up your build system with the current Spring Cloud Release Train. - -[[netflix-zuul-reverse-proxy]] -=== Embedded Zuul Reverse Proxy - -Spring Cloud has created an embedded Zuul proxy to ease the -development of a very common use case where a UI application wants to -proxy calls to one or more back end services. This feature is useful -for a user interface to proxy to the backend services it requires, -avoiding the need to manage CORS and authentication concerns -independently for all the backends. - -To enable it, annotate a Spring Boot main class with -`@EnableZuulProxy`, and this forwards local calls to the appropriate -service. By convention, a service with the ID "users", will -receive requests from the proxy located at `/users` (with the prefix stripped). The proxy uses Ribbon to locate an instance to forward to via discovery, and all requests are executed in a <>, so failures will show up in Hystrix metrics, and once the circuit is open the proxy will not try to contact the service. - -NOTE: the Zuul starter does not include a discovery client, so for -routes based on service IDs you need to provide one of those -on the classpath as well (e.g. Eureka is one choice). - -To skip having a service automatically added, set -`zuul.ignored-services` to a list of service id patterns. If a service -matches a pattern that is ignored, but also included in the explicitly -configured routes map, then it will be unignored. Example: - -.application.yml -[source,yaml] ----- - zuul: - ignoredServices: '*' - routes: - users: /myusers/** ----- - -In this example, all services are ignored *except* "users". - -To augment or change -the proxy routes, you can add external configuration like the -following: - -.application.yml -[source,yaml] ----- - zuul: - routes: - users: /myusers/** ----- - -This means that http calls to "/myusers" get forwarded to the "users" -service (for example "/myusers/101" is forwarded to "/101"). - -To get more fine-grained control over a route you can specify the path -and the serviceId independently: - -.application.yml -[source,yaml] ----- - zuul: - routes: - users: - path: /myusers/** - serviceId: users_service ----- - -This means that http calls to "/myusers" get forwarded to the -"users_service" service. The route has to have a "path" which can be -specified as an ant-style pattern, so "/myusers/{asterisk}" only matches one -level, but "/myusers/{all}" matches hierarchically. - -The location of the backend can be specified as either a "serviceId" -(for a service from discovery) or a "url" (for a physical location), e.g. - -.application.yml -[source,yaml] ----- - zuul: - routes: - users: - path: /myusers/** - url: http://example.com/users_service ----- - -These simple url-routes don't get executed as a `HystrixCommand` nor do they loadbalance multiple URLs with Ribbon. -To achieve this, you can specify a `serviceId` with a static list of servers: - -.application.yml -[source,yaml] ----- -zuul: - routes: - echo: - path: /myusers/** - serviceId: myusers-service - stripPrefix: true - -hystrix: - command: - myusers-service: - execution: - isolation: - thread: - timeoutInMilliseconds: ... - -myusers-service: - ribbon: - NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList - ListOfServers: http://example1.com,http://example2.com - ConnectTimeout: 1000 - ReadTimeout: 3000 - MaxTotalHttpConnections: 500 - MaxConnectionsPerHost: 100 ----- - -Another method is specifiying a service-route and configure a Ribbon client for the -serviceId (this requires disabling Eureka support in Ribbon: -see <>), e.g. - -.application.yml -[source,yaml] ----- -zuul: - routes: - users: - path: /myusers/** - serviceId: users - -ribbon: - eureka: - enabled: false - -users: - ribbon: - listOfServers: example.com,google.com ----- - -You can provide convention between serviceId and routes using -regexmapper. It uses regular expression named groups to extract -variables from serviceId and inject them into a route pattern. - -.ApplicationConfiguration.java -[source,java] ----- -@Bean -public PatternServiceRouteMapper serviceRouteMapper() { - return new PatternServiceRouteMapper( - "(?^.+)-(?v.+$)", - "${version}/${name}"); -} ----- - -This means that a serviceId "myusers-v1" will be mapped to route -"/v1/myusers/{all}". Any regular expression is accepted but all named -groups must be present in both servicePattern and routePattern. If -servicePattern does not match a serviceId, the default behavior is -used. In the example above, a serviceId "myusers" will be mapped to route -"/myusers/{all}" (no version detected) This feature is disabled by -default and only applies to discovered services. - -To add a prefix to all mappings, set `zuul.prefix` to a value, such as -`/api`. The proxy prefix is stripped from the request before the -request is forwarded by default (switch this behaviour off with -`zuul.stripPrefix=false`). You can also switch off the stripping of -the service-specific prefix from individual routes, e.g. - -.application.yml -[source,yaml] ----- - zuul: - routes: - users: - path: /myusers/** - stripPrefix: false ----- - -NOTE: `zuul.stripPrefix` only applies to the prefix set in `zuul.prefix`. It does not have any effect on prefixes -defined within a given route's `path`. - -In this example, requests to "/myusers/101" will be forwarded to "/myusers/101" on the "users" service. - -The `zuul.routes` entries actually bind to an object of type `ZuulProperties`. If you -look at the properties of that object you will see that it also has a "retryable" flag. -Set that flag to "true" to have the Ribbon client automatically retry failed requests -(and if you need to you can modify the parameters of the retry operations using -the Ribbon client configuration). - -The `X-Forwarded-Host` header is added to the forwarded requests by -default. To turn it off set `zuul.addProxyHeaders = false`. The -prefix path is stripped by default, and the request to the backend -picks up a header "X-Forwarded-Prefix" ("/myusers" in the examples -above). - -An application with `@EnableZuulProxy` could act as a standalone -server if you set a default route ("/"), for example `zuul.route.home: -/` would route all traffic (i.e. "/{all}") to the "home" service. - -If more fine-grained ignoring is needed, you can specify specific patterns to ignore. -These patterns are evaluated at the start of the route location process, which -means prefixes should be included in the pattern to warrant a match. Ignored patterns -span all services and supersede any other route specification. - -.application.yml -[source,yaml] ----- - zuul: - ignoredPatterns: /**/admin/** - routes: - users: /myusers/** ----- - -This means that all calls such as "/myusers/101" will be forwarded to "/101" on the "users" service. -But calls including "/admin/" will not resolve. - -WARNING: If you need your routes to have their order preserved you need to use a YAML -file as the ordering will be lost using a properties file. For example: - -.application.yml -[source,yaml] ----- - zuul: - routes: - users: - path: /myusers/** - legacy: - path: /** ----- - -If you were to use a properties file, the `legacy` path may end up in front of the `users` -path rendering the `users` path unreachable. - -=== Zuul Http Client - -The default HTTP client used by zuul is now backed by the Apache HTTP Client instead of the -deprecated Ribbon `RestClient`. To use `RestClient` or to use the `okhttp3.OkHttpClient` set -`ribbon.restclient.enabled=true` or `ribbon.okhttp.enabled=true` respectively. If you would -like to customize the Apache HTTP client or the OK HTTP client provide a bean of type -`ClosableHttpClient` or `OkHttpClient`. - -=== Cookies and Sensitive Headers - -It's OK to share headers between services in the same system, but you -probably don't want sensitive headers leaking downstream into external -servers. You can specify a list of ignored headers as part of the -route configuration. Cookies play a special role because they have -well-defined semantics in browsers, and they are always to be treated -as sensitive. If the consumer of your proxy is a browser, then cookies -for downstream services also cause problems for the user because they -all get jumbled up (all downstream services look like they come from -the same place). - -If you are careful with the design of your services, for example if -only one of the downstream services sets cookies, then you might be -able to let them flow from the backend all the way up to the -caller. Also, if your proxy sets cookies and all your back end -services are part of the same system, it can be natural to simply -share them (and for instance use Spring Session to link them up to some -shared state). Other than that, any cookies that get set by downstream -services are likely to be not very useful to the caller, so it is -recommended that you make (at least) "Set-Cookie" and "Cookie" into -sensitive headers for routes that are not part of your domain. Even -for routes that *are* part of your domain, try to think carefully -about what it means before allowing cookies to flow between them and -the proxy. - -The sensitive headers can be configured as a comma-separated list per -route, e.g. - -.application.yml -[source,yaml] ----- - zuul: - routes: - users: - path: /myusers/** - sensitiveHeaders: Cookie,Set-Cookie,Authorization - url: https://downstream ----- - -NOTE: this is the default value for `sensitiveHeaders`, so you don't -need to set it unless you want it to be different. N.B. this is new in -Spring Cloud Netflix 1.1 (in 1.0 the user had no control over headers -and all cookies flow in both directions). - -The `sensitiveHeaders` are a blacklist and the default is not empty, -so to make Zuul send all headers (except the "ignored" ones) you would -have to explicitly set it to the empty list. This is necessary if you -want to pass cookie or authorization headers to your back end. Example: - -.application.yml -[source,yaml] ----- - zuul: - routes: - users: - path: /myusers/** - sensitiveHeaders: - url: https://downstream ----- - -Sensitive headers can also be set globally by setting `zuul.sensitiveHeaders`. If `sensitiveHeaders` is set on a route, this will override the global `sensitiveHeaders` setting. - -=== Ignored Headers - -In addition to the per-route sensitive headers, you can set a global -value for `zuul.ignoredHeaders` for values that should be discarded -(both request and response) during interactions with downstream -services. By default these are empty, if Spring Security is not on the -classpath, and otherwise they are initialized to a set of well-known -"security" headers (e.g. involving caching) as specified by Spring -Security. The assumption in this case is that the downstream services -might add these headers too, and we want the values from the proxy. -To not discard these well known security headers in case Spring Security is on the classpath you can set `zuul.ignoreSecurityHeaders` to `false`. This can be useful if you disabled the HTTP Security response headers in Spring Security and want the values provided by downstream services - -=== Management Endpoints - -If you are using `@EnableZuulProxy` with the Spring Boot Actuator you -will enable (by default) two additional endpoints: - -* Routes -* Filters - -==== Routes Endpoint - -A GET to the routes endpoint at `/routes` will return a list of the mapped -routes: - -.GET /routes -[source,json] ----- -{ - /stores/**: "http://localhost:8081" -} ----- - -Additional route details can be requested through the `/routes/details` endpoint. This will produce the following output: - -.GET /routes/details -[source,json] ----- -{ - "/stores/**": { - "id": "stores", - "fullPath": "/stores/**", - "location": "http://localhost:8081", - "path": "/**", - "prefix": "/stores", - "retryable": false, - "customSensitiveHeaders": false, - "prefixStripped": true - } -} ----- - -A POST to `/routes` will force a refresh of the existing routes (e.g. in -case there have been changes in the service catalog). You can disable -this endpoint by setting `endpoints.routes.enabled` to `false`. - -NOTE: the routes should respond automatically to changes in the -service catalog, but the POST to `/routes` is a way to force the change -to happen immediately. - -==== Filters Endpoint - -A GET to the filters endpoint at `/filters` will return a map of Zuul -filters by type. For each filter type in the map, you will find a list -of all the filters of that type, along with their details. - -=== Strangulation Patterns and Local Forwards - -A common pattern when migrating an existing application or API is to -"strangle" old endpoints, slowly replacing them with different -implementations. The Zuul proxy is a useful tool for this because you -can use it to handle all traffic from clients of the old endpoints, -but redirect some of the requests to new ones. - -Example configuration: - -.application.yml -[source,yaml] ----- - zuul: - routes: - first: - path: /first/** - url: http://first.example.com - second: - path: /second/** - url: forward:/second - third: - path: /third/** - url: forward:/3rd - legacy: - path: /** - url: http://legacy.example.com ----- - -In this example we are strangling the "legacy" app which is mapped to -all requests that do not match one of the other patterns. Paths in -`/first/{all}` have been extracted into a new service with an external -URL. And paths in `/second/{all}` are forwarded so they can be handled -locally, e.g. with a normal Spring `@RequestMapping`. Paths in -`/third/{all}` are also forwarded, but with a different prefix -(i.e. `/third/foo` is forwarded to `/3rd/foo`). - -NOTE: The ignored patterns aren't completely ignored, they just -aren't handled by the proxy (so they are also effectively forwarded -locally). - -=== Uploading Files through Zuul - -If you use `@EnableZuulProxy`, you can use the proxy paths to -upload files and it should just work as long as the files -are small. For large files there is an alternative path -which bypasses the Spring `DispatcherServlet` (to -avoid multipart processing) in "/zuul/{asterisk}". I.e. if -`zuul.routes.customers=/customers/{all}` then you can -POST large files to "/zuul/customers/*". The servlet -path is externalized via `zuul.servletPath`. Extremely -large files will also require elevated timeout settings -if the proxy route takes you through a Ribbon load -balancer, e.g. - -.application.yml -[source,yaml] ----- -hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000 -ribbon: - ConnectTimeout: 3000 - ReadTimeout: 60000 ----- - -Note that for streaming to work with large files, you need to use chunked encoding in the request (which some browsers -do not do by default). E.g. on the command line: - ----- -$ curl -v -H "Transfer-Encoding: chunked" \ - -F "file=@mylarge.iso" localhost:9999/zuul/simple/file ----- - -=== Query String Encoding -When processing the incoming request, query params are decoded so they can be available for possible modifications in -Zuul filters. They are then re-encoded when building the backend request in the route filters. The result -can be different than the original input if it was encoded using Javascript's `encodeURIComponent()` method for example. -While this causes no issues in most cases, some web servers can be picky with the encoding of complex query string. - -To force the original encoding of the query string, it is possible to pass a special flag to `ZuulProperties` so -that the query string is taken as is with the `HttpServletRequest::getQueryString` method : - -.application.yml -[source,yaml] ----- - zuul: - forceOriginalQueryStringEncoding: true ----- - -*Note:* This special flag only works with `SimpleHostRoutingFilter` and you loose the ability to easily override -query parameters with `RequestContext.getCurrentContext().setRequestQueryParams(someOverriddenParameters)` since -the query string is now fetched directly on the original `HttpServletRequest`. - -=== Plain Embedded Zuul - -You can also run a Zuul server without the proxying, or switch on parts of the proxying platform selectively, if you -use `@EnableZuulServer` (instead of `@EnableZuulProxy`). Any beans that you add to the application of type `ZuulFilter` -will be installed automatically, as they are with `@EnableZuulProxy`, but without any of the proxy filters being added -automatically. - -In this case the routes into the Zuul server are still specified by -configuring "zuul.routes.{asterisk}", but there is no service -discovery and no proxying, so the "serviceId" and "url" settings are -ignored. For example: - -.application.yml -[source,yaml] ----- - zuul: - routes: - api: /api/** ----- - -maps all paths in "/api/{all}" to the Zuul filter chain. - -=== Disable Zuul Filters - -Zuul for Spring Cloud comes with a number of `ZuulFilter` beans enabled by default -in both proxy and server mode. See https://github.com/spring-cloud/spring-cloud-netflix/tree/master/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters[the zuul filters package] for the -possible filters that are enabled. If you want to disable one, simply set -`zuul...disable=true`. By convention, the package after -`filters` is the Zuul filter type. For example to disable -`org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter` set -`zuul.SendResponseFilter.post.disable=true`. - -[[hystrix-fallbacks-for-routes]] -=== Providing Hystrix Fallbacks For Routes - -When a circuit for a given route in Zuul is tripped you can provide a fallback response -by creating a bean of type `FallbackProvider`. Within this bean you need to specify -the route ID the fallback is for and provide a `ClientHttpResponse` to return -as a fallback. Here is a very simple `FallbackProvider` implementation. - -[source,java] ----- -class MyFallbackProvider implements FallbackProvider { - - @Override - public String getRoute() { - return "customers"; - } - - @Override - public ClientHttpResponse fallbackResponse(String route, final Throwable cause) { - if (cause instanceof HystrixTimeoutException) { - return response(HttpStatus.GATEWAY_TIMEOUT); - } else { - return response(HttpStatus.INTERNAL_SERVER_ERROR); - } - } - - private ClientHttpResponse response(final HttpStatus status) { - return new ClientHttpResponse() { - @Override - public HttpStatus getStatusCode() throws IOException { - return status; - } - - @Override - public int getRawStatusCode() throws IOException { - return status.value(); - } - - @Override - public String getStatusText() throws IOException { - return status.getReasonPhrase(); - } - - @Override - public void close() { - } - - @Override - public InputStream getBody() throws IOException { - return new ByteArrayInputStream("fallback".getBytes()); - } - - @Override - public HttpHeaders getHeaders() { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - return headers; - } - }; - } -} ----- - -And here is what the route configuration would look like. - -[source,yaml] ----- -zuul: - routes: - customers: /customers/** ----- - -If you would like to provide a default fallback for all routes than you can create a bean of -type `FallbackProvider` and have the `getRoute` method return `*` or `null`. - -[source,java] ----- -class MyFallbackProvider implements FallbackProvider { - @Override - public String getRoute() { - return "*"; - } - - @Override - public ClientHttpResponse fallbackResponse(String route, Throwable throwable) { - return new ClientHttpResponse() { - @Override - public HttpStatus getStatusCode() throws IOException { - return HttpStatus.OK; - } - - @Override - public int getRawStatusCode() throws IOException { - return 200; - } - - @Override - public String getStatusText() throws IOException { - return "OK"; - } - - @Override - public void close() { - - } - - @Override - public InputStream getBody() throws IOException { - return new ByteArrayInputStream("fallback".getBytes()); - } - - @Override - public HttpHeaders getHeaders() { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - return headers; - } - }; - } -} ----- - -=== Zuul Timeouts - -If you want to configure the socket timeouts and read timeouts for requests proxied through -Zuul there are two options based on your configuration. - -If Zuul is using service discovery then you need to configure these timeouts via Ribbon properties, -`ribbon.ReadTimeout` and `ribbon.SocketTimeout`. - -If you have configured Zuul routes by specifying URLs then you will need to use -`zuul.host.connect-timeout-millis` and `zuul.host.socket-timeout-millis`. - -[[zuul-redirect-location-rewrite]] -=== Rewriting `Location` header - -If Zuul is fronting a web application then there may be a need to re-write the `Location` header when the web application redirects through a http status code of 3XX, otherwise the browser will end up redirecting to the web application's url instead of the Zuul url. -A `LocationRewriteFilter` Zuul filter can be configured to re-write the Location header to the Zuul's url, it also adds back the stripped global and route specific prefixes. The filter can be added the following way via a Spring Configuration file: - -[source,java] ----- -import org.springframework.cloud.netflix.zuul.filters.post.LocationRewriteFilter; -... - -@Configuration -@EnableZuulProxy -public class ZuulConfig { - @Bean - public LocationRewriteFilter locationRewriteFilter() { - return new LocationRewriteFilter(); - } -} ----- - -[WARNING] -==== -Use this filter with caution though, the filter acts on the `Location` header of ALL 3XX response codes which may not be appropriate in all scenarios, say if the user is redirecting to an external URL. -==== - -[[zuul-developer-guide]] -=== Zuul Developer Guide - -For a general overview of how Zuul works, please see https://github.com/Netflix/zuul/wiki/How-it-Works[the Zuul Wiki]. - -==== The Zuul Servlet - -Zuul is implemented as a Servlet. For the general cases, Zuul is embedded into the Spring Dispatch mechanism. This allows Spring MVC to be in control of the routing. In this case, Zuul is configured to buffer requests. If there is a need to go through Zuul without buffering requests (e.g. for large file uploads), the Servlet is also installed outside of the Spring Dispatcher. By default, this is located at `/zuul`. This path can be changed with the `zuul.servlet-path` property. - -==== Zuul RequestContext - -To pass information between filters, Zuul uses a https://github.com/Netflix/zuul/blob/1.x/zuul-core/src/main/java/com/netflix/zuul/context/RequestContext.java[`RequestContext`]. Its data is held in a `ThreadLocal` specific to each request. Information about where to route requests, errors and the actual `HttpServletRequest` and `HttpServletResponse` are stored there. The `RequestContext` extends `ConcurrentHashMap`, so anything can be stored in the context. https://github.com/spring-cloud/spring-cloud-netflix/blob/master/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/zuul/filters/support/FilterConstants.java[`FilterConstants`] contains the keys that are used by the filters installed by Spring Cloud Netflix (more on these later). - -==== `@EnableZuulProxy` vs. `@EnableZuulServer` - -Spring Cloud Netflix installs a number of filters based on which annotation was used to enable Zuul. `@EnableZuulProxy` is a superset of `@EnableZuulServer`. In other words, `@EnableZuulProxy` contains all filters installed by `@EnableZuulServer`. The additional filters in the "proxy" enable routing functionality. If you want a "blank" Zuul, you should use `@EnableZuulServer`. - -==== `@EnableZuulServer` Filters - -Creates a `SimpleRouteLocator` that loads route definitions from Spring Boot configuration files. - -The following filters are installed (as normal Spring Beans): - -Pre filters: - -- `ServletDetectionFilter`: Detects if the request is through the Spring Dispatcher. Sets boolean with key `FilterConstants.IS_DISPATCHER_SERVLET_REQUEST_KEY`. -- `FormBodyWrapperFilter`: Parses form data and reencodes it for downstream requests. -- `DebugFilter`: if the `debug` request parameter is set, this filter sets `RequestContext.setDebugRouting()` and `RequestContext.setDebugRequest()` to true. - -Route filters: - -- `SendForwardFilter`: This filter forwards requests using the Servlet `RequestDispatcher`. The forwarding location is stored in the `RequestContext` attribute `FilterConstants.FORWARD_TO_KEY`. This is useful for forwarding to endpoints in the current application. - -Post filters: - -- `SendResponseFilter`: Writes responses from proxied requests to the current response. - -Error filters: - -- `SendErrorFilter`: Forwards to /error (by default) if `RequestContext.getThrowable()` is not null. The default forwarding path (`/error`) can be changed by setting the `error.path` property. - -==== `@EnableZuulProxy` Filters - -Creates a `DiscoveryClientRouteLocator` that loads route definitions from a `DiscoveryClient` (like Eureka), as well as from properties. A route is created for each `serviceId` from the `DiscoveryClient`. As new services are added, the routes will be refreshed. - -In addition to the filters described above, the following filters are installed (as normal Spring Beans): - -Pre filters: - -- `PreDecorationFilter`: This filter determines where and how to route based on the supplied `RouteLocator`. It also sets various proxy-related headers for downstream requests. - -Route filters: - -* `RibbonRoutingFilter`: This filter uses Ribbon, Hystrix and pluggable HTTP clients to send requests. Service ids are found in the `RequestContext` attribute `FilterConstants.SERVICE_ID_KEY`. This filter can use different HTTP clients. They are: -** Apache `HttpClient`. This is the default client. -** Squareup `OkHttpClient` v3. This is enabled by having the `com.squareup.okhttp3:okhttp` library on the classpath and setting `ribbon.okhttp.enabled=true`. -** Netflix Ribbon HTTP client. This is enabled by setting `ribbon.restclient.enabled=true`. This client has limitations, such as it doesn't support the PATCH method, but also has built-in retry. - -* `SimpleHostRoutingFilter`: This filter sends requests to predetermined URLs via an Apache HttpClient. URLs are found in `RequestContext.getRouteHost()`. - -==== Custom Zuul Filter examples - -Most of the following "How to Write" examples below are included https://github.com/spring-cloud-samples/sample-zuul-filters[Sample Zuul Filters] project. There are also examples of manipulating the request or response body in that repository. - -==== How to Write a Pre Filter - -Pre filters are used to set up data in the `RequestContext` for use in filters downstream. The main use case is to set information required for route filters. - -[source,java] ----- -public class QueryParamPreFilter extends ZuulFilter { - @Override - public int filterOrder() { - return PRE_DECORATION_FILTER_ORDER - 1; // run before PreDecoration - } - - @Override - public String filterType() { - return PRE_TYPE; - } - - @Override - public boolean shouldFilter() { - RequestContext ctx = RequestContext.getCurrentContext(); - return !ctx.containsKey(FORWARD_TO_KEY) // a filter has already forwarded - && !ctx.containsKey(SERVICE_ID_KEY); // a filter has already determined serviceId - } - @Override - public Object run() { - RequestContext ctx = RequestContext.getCurrentContext(); - HttpServletRequest request = ctx.getRequest(); - if (request.getParameter("foo") != null) { - // put the serviceId in `RequestContext` - ctx.put(SERVICE_ID_KEY, request.getParameter("foo")); - } - return null; - } -} ----- - -The filter above populates `SERVICE_ID_KEY` from the `foo` request parameter. In reality, it's not a good idea to do that kind of direct mapping, but the service id should be looked up from the value of `foo` instead. - -Now that `SERVICE_ID_KEY` is populated, `PreDecorationFilter` won't run and `RibbonRoutingFilter` will. If you wanted to route to a full URL instead, call `ctx.setRouteHost(url)` instead. - -To modify the path that routing filters will forward to, set the `REQUEST_URI_KEY`. - -==== How to Write a Route Filter - -Route filters are run after pre filters and are used to make requests to other services. Much of the work here is to translate request and response data to and from the client required model. - -[source,java] ----- -public class OkHttpRoutingFilter extends ZuulFilter { - @Autowired - private ProxyRequestHelper helper; - - @Override - public String filterType() { - return ROUTE_TYPE; - } - - @Override - public int filterOrder() { - return SIMPLE_HOST_ROUTING_FILTER_ORDER - 1; - } - - @Override - public boolean shouldFilter() { - return RequestContext.getCurrentContext().getRouteHost() != null - && RequestContext.getCurrentContext().sendZuulResponse(); - } - - @Override - public Object run() { - OkHttpClient httpClient = new OkHttpClient.Builder() - // customize - .build(); - - RequestContext context = RequestContext.getCurrentContext(); - HttpServletRequest request = context.getRequest(); - - String method = request.getMethod(); - - String uri = this.helper.buildZuulRequestURI(request); - - Headers.Builder headers = new Headers.Builder(); - Enumeration headerNames = request.getHeaderNames(); - while (headerNames.hasMoreElements()) { - String name = headerNames.nextElement(); - Enumeration values = request.getHeaders(name); - - while (values.hasMoreElements()) { - String value = values.nextElement(); - headers.add(name, value); - } - } - - InputStream inputStream = request.getInputStream(); - - RequestBody requestBody = null; - if (inputStream != null && HttpMethod.permitsRequestBody(method)) { - MediaType mediaType = null; - if (headers.get("Content-Type") != null) { - mediaType = MediaType.parse(headers.get("Content-Type")); - } - requestBody = RequestBody.create(mediaType, StreamUtils.copyToByteArray(inputStream)); - } - - Request.Builder builder = new Request.Builder() - .headers(headers.build()) - .url(uri) - .method(method, requestBody); - - Response response = httpClient.newCall(builder.build()).execute(); - - LinkedMultiValueMap responseHeaders = new LinkedMultiValueMap<>(); - - for (Map.Entry> entry : response.headers().toMultimap().entrySet()) { - responseHeaders.put(entry.getKey(), entry.getValue()); - } - - this.helper.setResponse(response.code(), response.body().byteStream(), - responseHeaders); - context.setRouteHost(null); // prevent SimpleHostRoutingFilter from running - return null; - } -} ----- - -The above filter translates Servlet request information into OkHttp3 request information, executes an HTTP request, then translates OkHttp3 reponse information to the Servlet response. WARNING: this filter might have bugs and not function correctly. - -==== How to Write a Post Filter - -Post filters typically manipulate the response. In the filter below, we add a random `UUID` as the `X-Foo` header. Other manipulations, such as transforming the response body, are much more complex and compute-intensive. - -[source,java] ----- -public class AddResponseHeaderFilter extends ZuulFilter { - @Override - public String filterType() { - return POST_TYPE; - } - - @Override - public int filterOrder() { - return SEND_RESPONSE_FILTER_ORDER - 1; - } - - @Override - public boolean shouldFilter() { - return true; - } - - @Override - public Object run() { - RequestContext context = RequestContext.getCurrentContext(); - HttpServletResponse servletResponse = context.getResponse(); - servletResponse.addHeader("X-Foo", UUID.randomUUID().toString()); - return null; - } -} ----- - -==== How Zuul Errors Work - -If an exception is thrown during any portion of the Zuul filter lifecycle, the error filters are executed. The `SendErrorFilter` is only run if `RequestContext.getThrowable()` is not `null`. It then sets specific `javax.servlet.error.*` attributes in the request and forwards the request to the Spring Boot error page. - -==== Zuul Eager Application Context Loading - -Zuul internally uses Ribbon for calling the remote url's and Ribbon clients are by default lazily loaded up by Spring Cloud on first call. -This behavior can be changed for Zuul using the following configuration and will result in the child Ribbon related Application contexts being eagerly loaded up at application startup time. - -.application.yml ----- -zuul: - ribbon: - eager-load: - enabled: true ----- - -== Polyglot support with Sidecar - -Do you have non-jvm languages you want to take advantage of Eureka, Ribbon and -Config Server? The Spring Cloud Netflix Sidecar was inspired by -https://github.com/Netflix/Prana[Netflix Prana]. It includes a simple http api -to get all of the instances (ie host and port) for a given service. You can -also proxy service calls through an embedded Zuul proxy which gets its route -entries from Eureka. The Spring Cloud Config Server can be accessed directly -via host lookup or through the Zuul Proxy. The non-jvm app should implement -a health check so the Sidecar can report to eureka if the app is up or down. - -To include Sidecar in your project use the dependency with group `org.springframework.cloud` -and artifact id `spring-cloud-netflix-sidecar`. - -To enable the Sidecar, create a Spring Boot application with `@EnableSidecar`. -This annotation includes `@EnableCircuitBreaker`, `@EnableDiscoveryClient`, -and `@EnableZuulProxy`. Run the resulting application on the same host as the -non-jvm application. - -To configure the side car add `sidecar.port` and `sidecar.health-uri` to `application.yml`. -The `sidecar.port` property is the port the non-jvm app is listening on. This -is so the Sidecar can properly register the app with Eureka. The `sidecar.health-uri` -is a uri accessible on the non-jvm app that mimicks a Spring Boot health -indicator. It should return a json document like the following: - -.health-uri-document -[source,json] ----- -{ - "status":"UP" -} ----- - -Here is an example application.yml for a Sidecar application: - -.application.yml -[source,yaml] ----- -server: - port: 5678 -spring: - application: - name: sidecar - -sidecar: - port: 8000 - health-uri: http://localhost:8000/health.json ----- - -The api for the `DiscoveryClient.getInstances()` method is `/hosts/{serviceId}`. -Here is an example response for `/hosts/customers` that returns two instances on -different hosts. This api is accessible to the non-jvm app (if the sidecar is -on port 5678) at `http://localhost:5678/hosts/{serviceId}`. - -./hosts/customers -[source,json] ----- -[ - { - "host": "myhost", - "port": 9000, - "uri": "http://myhost:9000", - "serviceId": "CUSTOMERS", - "secure": false - }, - { - "host": "myhost2", - "port": 9000, - "uri": "http://myhost2:9000", - "serviceId": "CUSTOMERS", - "secure": false - } -] ----- - -The Zuul proxy automatically adds routes for each service known in eureka to -`/`, so the customers service is available at `/customers`. The -Non-jvm app can access the customer service via `http://localhost:5678/customers` -(assuming the sidecar is listening on port 5678). - -If the Config Server is registered with Eureka, non-jvm application can access -it via the Zuul proxy. If the serviceId of the ConfigServer is `configserver` -and the Sidecar is on port 5678, then it can be accessed at -http://localhost:5678/configserver - -Non-jvm app can take advantage of the Config Server's ability to return YAML -documents. For example, a call to http://sidecar.local.spring.io:5678/configserver/default-master.yml -might result in a YAML document like the following - -[source,yaml] ----- -eureka: - client: - serviceUrl: - defaultZone: http://localhost:8761/eureka/ - password: password -info: - description: Spring Cloud Samples - url: https://github.com/spring-cloud-samples ----- - -[[netflix-metrics]] -== Metrics: Spectator, Servo, and Atlas - -When used together, Spectator/Servo and Atlas provide a near real-time operational insight platform. - -Spectator and Servo are Netflix's metrics collection libraries. Atlas is a Netflix metrics backend to manage dimensional time series data. - -Servo served Netflix for several years and is still usable, but is gradually being phased out in favor of Spectator, which is only designed to work with Java 8. Spring Cloud Netflix provides support for both, but Java 8 based applications are encouraged to use Spectator. - -=== Dimensional vs. Hierarchical Metrics - -Spring Boot Actuator metrics are hierarchical and metrics are separated only by name. These names often follow a naming convention that embeds key/value attribute pairs (dimensions) into the name separated by periods. Consider the following metrics for two endpoints, root and star-star: - -[source,json] ----- -{ - "counter.status.200.root": 20, - "counter.status.400.root": 3, - "counter.status.200.star-star": 5, -} ----- - -The first metric gives us a normalized count of successful requests against the root endpoint per unit of time. But what if the system had 20 endpoints and you want to get a count of successful requests against all the endpoints? Some hierarchical metrics backends would allow you to specify a wild card such as `counter.status.200.\*` that would read all 20 metrics and aggregate the results. Alternatively, you could provide a `HandlerInterceptorAdapter` that intercepts and records a metric like `counter.status.200.all` for all successful requests irrespective of the endpoint, but now you must write 20+1 different metrics. Similarly if you want to know the total number of successful requests for all endpoints in the service, you could specify a wild card such as `counter.status.2*.*`. - -Even in the presence of wildcarding support on a hierarchical metrics backend, naming consistency can be difficult. Specifically the position of these tags in the name string can slip with time, breaking queries. For example, suppose we add an additional dimension to the hierarchical metrics above for HTTP method. Then `counter.status.200.root` becomes `counter.status.200.method.get.root`, etc. Our `counter.status.200.*` suddenly no longer has the same semantic meaning. Furthermore, if the new dimension is not applied uniformly across the codebase, certain queries may become impossible. This can quickly get out of hand. - -Netflix metrics are tagged (a.k.a. dimensional). Each metric has a name, but this single named metric can contain multiple statistics and 'tag' key/value pairs that allows more querying flexibility. In fact, the statistics themselves are recorded in a special tag. - -Recorded with Netflix Servo or Spectator, a timer for the root endpoint described above contains 4 statistics per status code, where the count statistic is identical to Spring Boot Actuator's counter. In the event that we have encountered an HTTP 200 and 400 thus far, there will be 8 available data points: - -[source,json] ----- -{ - "root(status=200,stastic=count)": 20, - "root(status=200,stastic=max)": 0.7265630630000001, - "root(status=200,stastic=totalOfSquares)": 0.04759702862580789, - "root(status=200,stastic=totalTime)": 0.2093076914666667, - "root(status=400,stastic=count)": 1, - "root(status=400,stastic=max)": 0, - "root(status=400,stastic=totalOfSquares)": 0, - "root(status=400,stastic=totalTime)": 0, -} ----- - -=== Default Metrics Collection - -Without any additional dependencies or configuration, a Spring Cloud based service will autoconfigure a Servo `MonitorRegistry` and begin collecting metrics on every Spring MVC request. By default, a Servo timer with the name `rest` will be recorded for each MVC request which is tagged with: - -1. HTTP method -2. HTTP status (e.g. 200, 400, 500) -3. URI (or "root" if the URI is empty), sanitized for Atlas -4. The exception class name, if the request handler threw an exception -5. The caller, if a request header with a key matching `netflix.metrics.rest.callerHeader` is set on the request. There is no default key for `netflix.metrics.rest.callerHeader`. You must add it to your application properties if you wish to collect caller information. - -Set the `netflix.metrics.rest.metricName` property to change the name of the metric from `rest` to a name you provide. - -If Spring AOP is enabled and `org.aspectj:aspectjweaver` is present on your runtime classpath, Spring Cloud will also collect metrics on every client call made with `RestTemplate`. A Servo timer with the name of `restclient` will be recorded for each MVC request which is tagged with: - -1. HTTP method -2. HTTP status (e.g. 200, 400, 500), "CLIENT_ERROR" if the response returned null, or "IO_ERROR" if an `IOException` occurred during the execution of the `RestTemplate` method -3. URI, sanitized for Atlas -4. Client name - -WARNING: Avoid using hardcoded url parameters within `RestTemplate`. When targeting dynamic endpoints use URL variables. This will avoid potential "GC Overhead Limit Reached" issues where `ServoMonitorCache` treats each url as a unique key. - -[source,java,indent=0] ----- -// recommended -String orderid = "1"; -restTemplate.getForObject("http://testeurekabrixtonclient/orders/{orderid}", String.class, orderid) - -// avoid -restTemplate.getForObject("http://testeurekabrixtonclient/orders/1", String.class) ----- - -[[netflix-metrics-spectator]] -=== Metrics Collection: Spectator - -To enable Spectator metrics, include a dependency on `spring-boot-starter-spectator`: - -[source,xml] ----- - - org.springframework.cloud - spring-cloud-starter-netflix-spectator - ----- - -In Spectator parlance, a meter is a named, typed, and tagged configuration and a metric represents the value of a given meter at a point in time. Spectator meters are created and controlled by a registry, which currently has several different implementations. Spectator provides 4 meter types: counter, timer, gauge, and distribution summary. - -Spring Cloud Spectator integration configures an injectable `com.netflix.spectator.api.Registry` instance for you. Specifically, it configures a `ServoRegistry` instance in order to unify the collection of REST metrics and the exporting of metrics to the Atlas backend under a single Servo API. Practically, this means that your code may use a mixture of Servo monitors and Spectator meters and both will be scooped up by Spring Boot Actuator `MetricReader` instances and both will be shipped to the Atlas backend. - -==== Spectator Counter - -A counter is used to measure the rate at which some event is occurring. - -[source,java] ----- -// create a counter with a name and a set of tags -Counter counter = registry.counter("counterName", "tagKey1", "tagValue1", ...); -counter.increment(); // increment when an event occurs -counter.increment(10); // increment by a discrete amount ----- - -The counter records a single time-normalized statistic. - -==== Spectator Timer - -A timer is used to measure how long some event is taking. Spring Cloud automatically records timers for Spring MVC requests and conditionally `RestTemplate` requests, which can later be used to create dashboards for request related metrics like latency: - -.Request Latency -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-netflix/{branch}/docs/src/main/asciidoc/images/RequestLatency.png[] - -[source,java] ----- -// create a timer with a name and a set of tags -Timer timer = registry.timer("timerName", "tagKey1", "tagValue1", ...); - -// execute an operation and time it at the same time -T result = timer.record(() -> fooReturnsT()); - -// alternatively, if you must manually record the time -Long start = System.nanoTime(); -T result = fooReturnsT(); -timer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS); ----- - -The timer simultaneously records 4 statistics: count, max, totalOfSquares, and totalTime. The count statistic will always match the single normalized value provided by a counter if you had called `increment()` once on the counter for each time you recorded a timing, so it is rarely necessary to count and time separately for a single operation. - -For link:https://github.com/Netflix/spectator/wiki/Timer-Usage#longtasktimer[long running operations], Spectator provides a special `LongTaskTimer`. - -==== Spectator Gauge - -Gauges are used to determine some current value like the size of a queue or number of threads in a running state. Since gauges are sampled, they provide no information about how these values fluctuate between samples. - -The normal use of a gauge involves registering the gauge once in initialization with an id, a reference to the object to be sampled, and a function to get or compute a numeric value based on the object. The reference to the object is passed in separately and the Spectator registry will keep a weak reference to the object. If the object is garbage collected, then Spectator will automatically drop the registration. See link:https://github.com/Netflix/spectator/wiki/Gauge-Usage#using-lambda[the note] in Spectator's documentation about potential memory leaks if this API is misused. - -[source,java] ----- -// the registry will automatically sample this gauge periodically -registry.gauge("gaugeName", pool, Pool::numberOfRunningThreads); - -// manually sample a value in code at periodic intervals -- last resort! -registry.gauge("gaugeName", Arrays.asList("tagKey1", "tagValue1", ...), 1000); ----- - -==== Spectator Distribution Summaries - -A distribution summary is used to track the distribution of events. It is similar to a timer, but more general in that the size does not have to be a period of time. For example, a distribution summary could be used to measure the payload sizes of requests hitting a server. - -[source,java] ----- -// the registry will automatically sample this gauge periodically -DistributionSummary ds = registry.distributionSummary("dsName", "tagKey1", "tagValue1", ...); -ds.record(request.sizeInBytes()); ----- - -[[netflix-metrics-servo]] -=== Metrics Collection: Servo - -WARNING: If your code is compiled on Java 8, please use Spectator instead of Servo as Spectator is destined to replace Servo entirely in the long term. - -In Servo parlance, a monitor is a named, typed, and tagged configuration and a metric represents the value of a given monitor at a point in time. Servo monitors are logically equivalent to Spectator meters. Servo monitors are created and controlled by a `MonitorRegistry`. In spite of the above warning, Servo does have a link:https://github.com/Netflix/servo/wiki/Getting-Started[wider array] of monitor options than Spectator has meters. - -Spring Cloud integration configures an injectable `com.netflix.servo.MonitorRegistry` instance for you. Once you have created the appropriate `Monitor` type in Servo, the process of recording data is wholly similar to Spectator. - -==== Creating Servo Monitors - -If you are using the Servo `MonitorRegistry` instance provided by Spring Cloud (specifically, an instance of `DefaultMonitorRegistry`), Servo provides convenience classes for retrieving link:https://github.com/Netflix/spectator/wiki/Servo-Comparison#dynamiccounter[counters] and link:https://github.com/Netflix/spectator/wiki/Servo-Comparison#dynamictimer[timers]. These convenience classes ensure that only one `Monitor` is registered for each unique combination of name and tags. - -To manually create a Monitor type in Servo, especially for the more exotic monitor types for which convenience methods are not provided, instantiate the appropriate type by providing a `MonitorConfig` instance: - -[source,java] ----- -MonitorConfig config = MonitorConfig.builder("timerName").withTag("tagKey1", "tagValue1").build(); - -// somewhere we should cache this Monitor by MonitorConfig -Timer timer = new BasicTimer(config); -monitorRegistry.register(timer); ----- - -[[netflix-metrics-atlas]] -=== Metrics Backend: Atlas - -Atlas was developed by Netflix to manage dimensional time series data for near real-time operational insight. Atlas features in-memory data storage, allowing it to gather and report very large numbers of metrics, very quickly. - -Atlas captures operational intelligence. Whereas business intelligence is data gathered for analyzing trends over time, operational intelligence provides a picture of what is currently happening within a system. - -Spring Cloud provides a `spring-cloud-starter-netflix-atlas` that has all the dependencies you need. Then just annotate your Spring Boot application with `@EnableAtlas` and provide a location for your running Atlas server with the `netflix.atlas.uri` property. - -==== Global tags - -Spring Cloud enables you to add tags to every metric sent to the Atlas backend. Global tags can be used to separate metrics by application name, environment, region, etc. - -Each bean implementing `AtlasTagProvider` will contribute to the global tag list: - -[source,java] ----- -@Bean -AtlasTagProvider atlasCommonTags( - @Value("${spring.application.name}") String appName) { - return () -> Collections.singletonMap("app", appName); -} ----- - -==== Using Atlas - -To bootstrap a in-memory standalone Atlas instance: - -[source,bash] ----- -$ curl -LO https://github.com/Netflix/atlas/releases/download/v1.4.2/atlas-1.4.2-standalone.jar -$ java -jar atlas-1.4.2-standalone.jar ----- - -TIP: An Atlas standalone node running on an r3.2xlarge (61GB RAM) can handle roughly 2 million metrics per minute for a given 6 hour window. - -Once running and you have collected a handful of metrics, verify that your setup is correct by listing tags on the Atlas server: - -[source,bash] ----- -$ curl http://ATLAS/api/v1/tags ----- - -TIP: After executing several requests against your service, you can gather some very basic information on the request latency of every request by pasting the following url in your browser: `http://ATLAS/api/v1/graph?q=name,rest,:eq,:avg` - -The Atlas wiki contains a link:https://github.com/Netflix/atlas/wiki/Single-Line[compilation of sample queries] for various scenarios. - -Make sure to check out the link:https://github.com/Netflix/atlas/wiki/Alerting-Philosophy[alerting philosophy] and docs on using link:https://github.com/Netflix/atlas/wiki/DES[double exponential smoothing] to generate dynamic alert thresholds. - -[[retrying-failed-requests]] -=== Retrying Failed Requests - -Spring Cloud Netflix offers a variety of ways to make HTTP requests. You can use a load balanced -`RestTemplate`, Ribbon, or Feign. No matter how you choose to your HTTP requests, there is always -a chance the request may fail. When a request fails you may want to have the request retried -automatically. To accomplish this when using Sping Cloud Netflix you need to include -https://github.com/spring-projects/spring-retry[Spring Retry] on your application's classpath. -When Spring Retry is present load balanced `RestTemplates`, Feign, and Zuul will automatically -retry any failed requests (assuming you configuration allows it to). - -==== BackOff Policies -By default no backoff policy is used when retrying requests. If you would like to configure -a backoff policy you will need to create a bean of type `LoadBalancedBackOffPolicyFactory` -which will be used to create a `BackOffPolicy` for a given service. - -[source,java,indent=0] ----- -@Configuration -public class MyConfiguration { - @Bean - LoadBalancedBackOffPolicyFactory backOffPolciyFactory() { - return new LoadBalancedBackOffPolicyFactory() { - @Override - public BackOffPolicy createBackOffPolicy(String service) { - return new ExponentialBackOffPolicy(); - } - }; - } -} ----- - -==== Configuration - -Anytime Ribbon is used with Spring Retry you can control the retry functionality by configuring -certain Ribbon properties. The properties you can use are -`client.ribbon.MaxAutoRetries`, `client.ribbon.MaxAutoRetriesNextServer`, and -`client.ribbon.OkToRetryOnAllOperations`. See the https://github.com/Netflix/ribbon/wiki/Getting-Started#the-properties-file-sample-clientproperties[Ribbon documentation] -for a description of what there properties do. - -WARNING: Enabling `client.ribbon.OkToRetryOnAllOperations` includes retring POST requests wich can have a impact -on the server's resources due to the buffering of the request's body. - -In addition you may want to retry requests when certain status codes are returned in the -response. You can list the response codes you would like the Ribbon client to retry using the - property `clientName.ribbon.retryableStatusCodes`. For example - -[source,yaml] ----- -clientName: - ribbon: - retryableStatusCodes: 404,502 ----- - -You can also create a bean of type `LoadBalancedRetryPolicy` and implement the `retryableStatusCode` -method to determine whether you want to retry a request given the status code. - - - -==== Zuul - -You can turn off Zuul's retry functionality by setting `zuul.retryable` to `false`. You -can also disable retry functionality on route by route basis by setting -`zuul.routes.routename.retryable` to `false`. - -== HTTP Clients - -Spring Cloud Netflix will automatically create the HTTP client used by Ribbon, Feign, and -Zuul for you. However you can also provide your own HTTP clients customized how you please -yourself. To do this you can either create a bean of type `ClosableHttpClient` if you -are using the Apache Http Cient, or `OkHttpClient` if you are using OK HTTP. - -NOTE: When you create your own HTTP client you are also responsible for implementing -the correct connection management strategies for these clients. Doing this improperly -can result in resource management issues. diff --git a/eclipse/eclipse-code-formatter.xml b/eclipse/eclipse-code-formatter.xml deleted file mode 100644 index 4694d7f2..00000000 --- a/eclipse/eclipse-code-formatter.xml +++ /dev/null @@ -1,295 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/eclipse/org.eclipse.jdt.core.prefs b/eclipse/org.eclipse.jdt.core.prefs deleted file mode 100644 index 63d59166..00000000 --- a/eclipse/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,389 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.codeComplete.argumentPrefixes= -org.eclipse.jdt.core.codeComplete.argumentSuffixes= -org.eclipse.jdt.core.codeComplete.fieldPrefixes= -org.eclipse.jdt.core.codeComplete.fieldSuffixes= -org.eclipse.jdt.core.codeComplete.localPrefixes= -org.eclipse.jdt.core.codeComplete.localSuffixes= -org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= -org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= -org.eclipse.jdt.core.codeComplete.staticFinalFieldPrefixes= -org.eclipse.jdt.core.codeComplete.staticFinalFieldSuffixes= -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.doc.comment.support=enabled -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=warning -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.invalidJavadoc=warning -org.eclipse.jdt.core.compiler.problem.invalidJavadocTags=enabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=disabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=enabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=default -org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore -org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=disabled -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public -org.eclipse.jdt.core.compiler.problem.missingJavadocTagDescription=return_tag -org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsMethodTypeParameters=disabled -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=disabled -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=private -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nullReference=ignore -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedImport=warning -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.6 -org.eclipse.jdt.core.formatter.align_type_members_on_columns=false -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_assignment=0 -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 -org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 -org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 -org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 -org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 -org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 -org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 -org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_after_package=1 -org.eclipse.jdt.core.formatter.blank_lines_before_field=0 -org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 -org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 -org.eclipse.jdt.core.formatter.blank_lines_before_method=1 -org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 -org.eclipse.jdt.core.formatter.blank_lines_before_package=0 -org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 -org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 -org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_lambda_body=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false -org.eclipse.jdt.core.formatter.comment.format_block_comments=true -org.eclipse.jdt.core.formatter.comment.format_header=false -org.eclipse.jdt.core.formatter.comment.format_html=true -org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true -org.eclipse.jdt.core.formatter.comment.format_line_comments=true -org.eclipse.jdt.core.formatter.comment.format_source_code=false -org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true -org.eclipse.jdt.core.formatter.comment.indent_root_tags=false -org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=do not insert -org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert -org.eclipse.jdt.core.formatter.comment.line_length=90 -org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true -org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true -org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false -org.eclipse.jdt.core.formatter.compact_else_if=true -org.eclipse.jdt.core.formatter.continuation_indentation=2 -org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 -org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off -org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on -org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false -org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true -org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_empty_lines=false -org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true -org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false -org.eclipse.jdt.core.formatter.indentation.size=8 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_after_type_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=insert -org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=insert -org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=insert -org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert -org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert -org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert -org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.join_lines_in_comments=true -org.eclipse.jdt.core.formatter.join_wrapped_lines=true -org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false -org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false -org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false -org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false -org.eclipse.jdt.core.formatter.lineSplit=90 -org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false -org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false -org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 -org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 -org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true -org.eclipse.jdt.core.formatter.tabulation.char=tab -org.eclipse.jdt.core.formatter.tabulation.size=4 -org.eclipse.jdt.core.formatter.use_on_off_tags=false -org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false -org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true -org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true -org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true diff --git a/eclipse/org.eclipse.jdt.ui.prefs b/eclipse/org.eclipse.jdt.ui.prefs deleted file mode 100644 index fb4753fe..00000000 --- a/eclipse/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,125 +0,0 @@ -cleanup.add_default_serial_version_id=true -cleanup.add_generated_serial_version_id=false -cleanup.add_missing_annotations=true -cleanup.add_missing_deprecated_annotations=true -cleanup.add_missing_methods=false -cleanup.add_missing_nls_tags=false -cleanup.add_missing_override_annotations=true -cleanup.add_missing_override_annotations_interface_methods=true -cleanup.add_serial_version_id=false -cleanup.always_use_blocks=true -cleanup.always_use_parentheses_in_expressions=false -cleanup.always_use_this_for_non_static_field_access=true -cleanup.always_use_this_for_non_static_method_access=false -cleanup.convert_functional_interfaces=false -cleanup.convert_to_enhanced_for_loop=false -cleanup.correct_indentation=false -cleanup.format_source_code=true -cleanup.format_source_code_changes_only=false -cleanup.insert_inferred_type_arguments=false -cleanup.make_local_variable_final=false -cleanup.make_parameters_final=false -cleanup.make_private_fields_final=false -cleanup.make_type_abstract_if_missing_method=false -cleanup.make_variable_declarations_final=false -cleanup.never_use_blocks=false -cleanup.never_use_parentheses_in_expressions=true -cleanup.organize_imports=true -cleanup.qualify_static_field_accesses_with_declaring_class=false -cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -cleanup.qualify_static_member_accesses_with_declaring_class=true -cleanup.qualify_static_method_accesses_with_declaring_class=false -cleanup.remove_private_constructors=true -cleanup.remove_redundant_type_arguments=true -cleanup.remove_trailing_whitespaces=true -cleanup.remove_trailing_whitespaces_all=true -cleanup.remove_trailing_whitespaces_ignore_empty=false -cleanup.remove_unnecessary_casts=true -cleanup.remove_unnecessary_nls_tags=false -cleanup.remove_unused_imports=true -cleanup.remove_unused_local_variables=false -cleanup.remove_unused_private_fields=true -cleanup.remove_unused_private_members=false -cleanup.remove_unused_private_methods=true -cleanup.remove_unused_private_types=true -cleanup.sort_members=false -cleanup.sort_members_all=false -cleanup.use_anonymous_class_creation=false -cleanup.use_blocks=true -cleanup.use_blocks_only_for_return_and_throw=false -cleanup.use_lambda=true -cleanup.use_parentheses_in_expressions=false -cleanup.use_this_for_non_static_field_access=true -cleanup.use_this_for_non_static_field_access_only_if_necessary=false -cleanup.use_this_for_non_static_method_access=false -cleanup.use_this_for_non_static_method_access_only_if_necessary=true -cleanup.use_type_arguments=false -cleanup_profile=_Spring Cloud Cleanup Conventions -cleanup_settings_version=2 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -formatter_profile=_Spring Cloud Java Conventions -formatter_settings_version=12 -org.eclipse.jdt.ui.exception.name=e -org.eclipse.jdt.ui.gettersetter.use.is=false -org.eclipse.jdt.ui.ignorelowercasenames=true -org.eclipse.jdt.ui.importorder=java;javax;org;com;\#; -org.eclipse.jdt.ui.javadoc=true -org.eclipse.jdt.ui.keywordthis=false -org.eclipse.jdt.ui.ondemandthreshold=9999 -org.eclipse.jdt.ui.overrideannotation=true -org.eclipse.jdt.ui.staticondemandthreshold=9999 -org.eclipse.jdt.ui.text.custom_code_templates= -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_missing_override_annotations_interface_methods=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=true -sp_cleanup.always_use_this_for_non_static_field_access=true -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=false -sp_cleanup.correct_indentation=false -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=false -sp_cleanup.make_local_variable_final=false -sp_cleanup.make_parameters_final=false -sp_cleanup.make_private_fields_final=false -sp_cleanup.make_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=false -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=false -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=true -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=false -sp_cleanup.remove_unused_imports=true -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_blocks=true -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=true -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=false -sp_cleanup.use_this_for_non_static_method_access=false -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/pom.xml b/pom.xml index e95e37b6..c69a9cc9 100644 --- a/pom.xml +++ b/pom.xml @@ -2,11 +2,11 @@ 4.0.0 - spring-cloud-netflix + spring-cloud-openfeign 2.0.0.BUILD-SNAPSHOT pom - Spring Cloud Netflix - Spring Cloud Netflix + Spring Cloud OpenFeign + Spring Cloud OpenFeign org.springframework.cloud spring-cloud-build @@ -14,20 +14,16 @@ - https://github.com/spring-cloud/spring-cloud-netflix - scm:git:git://github.com/spring-cloud/spring-cloud-netflix.git - scm:git:ssh://git@github.com/spring-cloud/spring-cloud-netflix.git + https://github.com/spring-cloud/spring-cloud-openfeign + scm:git:git://github.com/spring-cloud/spring-cloud-openfeign.git + scm:git:ssh://git@github.com/spring-cloud/spring-cloud-openfeign.git HEAD - netflix ${basedir} 2.7.3 2.0.0.BUILD-SNAPSHOT - 2.0.0.BUILD-SNAPSHOT - Elmhurst.BUILD-SNAPSHOT - - 1.2.0.RELEASE + 2.0.0.BUILD-SNAPSHOT 3.6.1 @@ -71,12 +67,6 @@ - - org.springframework.cloud - spring-cloud-netflix-hystrix-contract - ${project.version} - test - org.springframework.cloud spring-cloud-netflix-dependencies @@ -97,27 +87,6 @@ test ${spring-cloud-commons.version} - - org.springframework.cloud - spring-cloud-config-dependencies - ${spring-cloud-config.version} - pom - import - - - org.springframework.cloud - spring-cloud-stream-dependencies - ${spring-cloud-stream.version} - pom - import - - - org.springframework.cloud - spring-cloud-contract-dependencies - ${donotreplacespring-cloud-contract.version} - pom - import - com.fasterxml.jackson.dataformat jackson-dataformat-smile @@ -126,21 +95,9 @@ - spring-cloud-netflix-dependencies - spring-cloud-netflix-archaius - - - spring-cloud-netflix-core - spring-cloud-netflix-hystrix-dashboard - spring-cloud-netflix-hystrix-stream - spring-cloud-netflix-eureka-client - spring-cloud-netflix-eureka-server - spring-cloud-netflix-turbine - spring-cloud-netflix-turbine-stream - spring-cloud-netflix-sidecar - spring-cloud-netflix-zuul - spring-cloud-netflix-ribbon - spring-cloud-starter-netflix + spring-cloud-openfeign-dependencies + spring-cloud-openfeign-core + spring-cloud-starter-openfeign docs diff --git a/scripts/build.sh b/scripts/build.sh deleted file mode 100755 index fe43ccda..00000000 --- a/scripts/build.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash - -(cd spring-cloud-netflix-hystrix-contract && ../mvnw clean install -B -Pdocs ${@}) -./mvnw clean install -B -Pdocs ${@} diff --git a/scripts/runAcceptanceTests.sh b/scripts/runAcceptanceTests.sh deleted file mode 100755 index 97a9d6bf..00000000 --- a/scripts/runAcceptanceTests.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash - -set -o errexit - -mkdir -p target - -SCRIPT_URL="https://raw.githubusercontent.com/spring-cloud-samples/brewery/master/runAcceptanceTests.sh" -AT_WHAT_TO_TEST="EUREKA" - -cd target - -curl "${SCRIPT_URL}" --output runAcceptanceTests.sh - -chmod +x runAcceptanceTests.sh - -echo "Killing all running apps" -./runAcceptanceTests.sh -t "${AT_WHAT_TO_TEST}" --killnow - -./runAcceptanceTests.sh -t "${AT_WHAT_TO_TEST}" --killattheend - -SCRIPT_URL="https://raw.githubusercontent.com/spring-cloud-samples/tests/master/scripts/runTests.sh" - -curl "${SCRIPT_URL}" --output runIntegrationTests.sh - -chmod +x runIntegrationTests.sh - -./runIntegrationTests.sh diff --git a/spring-cloud-netflix-archaius/pom.xml b/spring-cloud-netflix-archaius/pom.xml deleted file mode 100644 index bfef5c55..00000000 --- a/spring-cloud-netflix-archaius/pom.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - 4.0.0 - - spring-cloud-netflix - org.springframework.cloud - 2.0.0.BUILD-SNAPSHOT - .. - - - - spring-cloud-netflix-archaius - jar - Spring Cloud Netflix Archaius - Spring Cloud Netflix Archaius - - ${basedir}/.. - - - - - org.springframework.boot - spring-boot-starter-actuator - true - - - org.springframework.cloud - spring-cloud-context - true - - - com.netflix.archaius - archaius-core - true - - - commons-configuration - commons-configuration - true - - - - org.springframework.boot - spring-boot-starter-test - test - - - - diff --git a/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusAutoConfiguration.java b/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusAutoConfiguration.java deleted file mode 100644 index b04a7231..00000000 --- a/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusAutoConfiguration.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.archaius; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.annotation.PreDestroy; - -import org.apache.commons.configuration.AbstractConfiguration; -import org.apache.commons.configuration.ConfigurationBuilder; -import org.apache.commons.configuration.EnvironmentConfiguration; -import org.apache.commons.configuration.SystemConfiguration; -import org.apache.commons.configuration.event.ConfigurationEvent; -import org.apache.commons.configuration.event.ConfigurationListener; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; -import org.springframework.boot.actuate.health.Health; -import org.springframework.boot.autoconfigure.AutoConfigureOrder; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.context.environment.EnvironmentChangeEvent; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationListener; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.Ordered; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.Environment; -import org.springframework.util.ReflectionUtils; - -import com.netflix.config.AggregatedConfiguration; -import com.netflix.config.ConcurrentCompositeConfiguration; -import com.netflix.config.ConfigurationManager; -import com.netflix.config.DeploymentContext; -import com.netflix.config.DynamicProperty; -import com.netflix.config.DynamicPropertyFactory; -import com.netflix.config.DynamicURLConfiguration; - -import static com.netflix.config.ConfigurationManager.APPLICATION_PROPERTIES; -import static com.netflix.config.ConfigurationManager.DISABLE_DEFAULT_ENV_CONFIG; -import static com.netflix.config.ConfigurationManager.DISABLE_DEFAULT_SYS_CONFIG; -import static com.netflix.config.ConfigurationManager.ENV_CONFIG_NAME; -import static com.netflix.config.ConfigurationManager.SYS_CONFIG_NAME; -import static com.netflix.config.ConfigurationManager.URL_CONFIG_NAME; - -/** - * @author Spencer Gibb - */ -@Configuration -@ConditionalOnClass({ ConcurrentCompositeConfiguration.class, - ConfigurationBuilder.class }) -@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) -public class ArchaiusAutoConfiguration { - - private static final Log log = LogFactory.getLog(ArchaiusAutoConfiguration.class); - - private static final AtomicBoolean initialized = new AtomicBoolean(false); - - @Autowired - private ConfigurableEnvironment env; - - @Autowired(required = false) - private List externalConfigurations = new ArrayList<>(); - - private static DynamicURLConfiguration defaultURLConfig; - - @PreDestroy - public void close() { - if (defaultURLConfig != null) { - defaultURLConfig.stopLoading(); - } - setStatic(ConfigurationManager.class, "instance", null); - setStatic(ConfigurationManager.class, "customConfigurationInstalled", false); - setStatic(DynamicPropertyFactory.class, "config", null); - setStatic(DynamicPropertyFactory.class, "initializedWithDefaultConfig", false); - setStatic(DynamicProperty.class, "dynamicPropertySupportImpl", null); - initialized.compareAndSet(true, false); - } - - @Bean - public static ConfigurableEnvironmentConfiguration configurableEnvironmentConfiguration(ConfigurableEnvironment env, - ApplicationContext context) { - Map abstractConfigurationMap = context.getBeansOfType(AbstractConfiguration.class); - List externalConfigurations = new ArrayList<>(abstractConfigurationMap.values()); - ConfigurableEnvironmentConfiguration envConfig = new ConfigurableEnvironmentConfiguration(env); - configureArchaius(envConfig, env, externalConfigurations); - return envConfig; - } - - @Configuration - @ConditionalOnClass(Health.class) - protected static class ArchaiusEndpointConfiguration { - @Bean - @ConditionalOnEnabledEndpoint - protected ArchaiusEndpoint archaiusEndpoint() { - return new ArchaiusEndpoint(); - } - } - - @Configuration - @ConditionalOnProperty(value = "archaius.propagate.environmentChangedEvent", matchIfMissing = true) - @ConditionalOnClass(EnvironmentChangeEvent.class) - protected static class PropagateEventsConfiguration - implements ApplicationListener { - @Autowired - private Environment env; - - @Override - public void onApplicationEvent(EnvironmentChangeEvent event) { - AbstractConfiguration manager = ConfigurationManager.getConfigInstance(); - for (String key : event.getKeys()) { - for (ConfigurationListener listener : manager - .getConfigurationListeners()) { - Object source = event.getSource(); - // TODO: Handle add vs set vs delete? - int type = AbstractConfiguration.EVENT_SET_PROPERTY; - String value = this.env.getProperty(key); - boolean beforeUpdate = false; - listener.configurationChanged(new ConfigurationEvent(source, type, - key, value, beforeUpdate)); - } - } - } - } - - protected static void configureArchaius(ConfigurableEnvironmentConfiguration envConfig, ConfigurableEnvironment env, List externalConfigurations) { - if (initialized.compareAndSet(false, true)) { - String appName = env.getProperty("spring.application.name"); - if (appName == null) { - appName = "application"; - log.warn("No spring.application.name found, defaulting to 'application'"); - } - System.setProperty(DeploymentContext.ContextKey.appId.getKey(), appName); - - ConcurrentCompositeConfiguration config = new ConcurrentCompositeConfiguration(); - - // support to add other Configurations (Jdbc, DynamoDb, Zookeeper, jclouds, - // etc...) - if (externalConfigurations != null) { - for (AbstractConfiguration externalConfig : externalConfigurations) { - config.addConfiguration(externalConfig); - } - } - config.addConfiguration(envConfig, - ConfigurableEnvironmentConfiguration.class.getSimpleName()); - - defaultURLConfig = new DynamicURLConfiguration(); - try { - config.addConfiguration(defaultURLConfig, URL_CONFIG_NAME); - } - catch (Throwable ex) { - log.error("Cannot create config from " + defaultURLConfig, ex); - } - - // TODO: sys/env above urls? - if (!Boolean.getBoolean(DISABLE_DEFAULT_SYS_CONFIG)) { - SystemConfiguration sysConfig = new SystemConfiguration(); - config.addConfiguration(sysConfig, SYS_CONFIG_NAME); - } - if (!Boolean.getBoolean(DISABLE_DEFAULT_ENV_CONFIG)) { - EnvironmentConfiguration environmentConfiguration = new EnvironmentConfiguration(); - config.addConfiguration(environmentConfiguration, ENV_CONFIG_NAME); - } - - ConcurrentCompositeConfiguration appOverrideConfig = new ConcurrentCompositeConfiguration(); - config.addConfiguration(appOverrideConfig, APPLICATION_PROPERTIES); - config.setContainerConfigurationIndex( - config.getIndexOfConfiguration(appOverrideConfig)); - - addArchaiusConfiguration(config); - } - else { - // TODO: reinstall ConfigurationManager - log.warn( - "Netflix ConfigurationManager has already been installed, unable to re-install"); - } - } - - private static void addArchaiusConfiguration(ConcurrentCompositeConfiguration config) { - if (ConfigurationManager.isConfigurationInstalled()) { - AbstractConfiguration installedConfiguration = ConfigurationManager - .getConfigInstance(); - if (installedConfiguration instanceof ConcurrentCompositeConfiguration) { - ConcurrentCompositeConfiguration configInstance = (ConcurrentCompositeConfiguration) installedConfiguration; - configInstance.addConfiguration(config); - } - else { - installedConfiguration.append(config); - if (!(installedConfiguration instanceof AggregatedConfiguration)) { - log.warn( - "Appending a configuration to an existing non-aggregated installed configuration will have no effect"); - } - } - } - else { - ConfigurationManager.install(config); - } - } - - private static void setStatic(Class type, String name, Object value) { - // Hack a private static field - Field field = ReflectionUtils.findField(type, name); - ReflectionUtils.makeAccessible(field); - ReflectionUtils.setField(field, null, value); - } - -} diff --git a/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusDelegatingProxyUtils.java b/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusDelegatingProxyUtils.java deleted file mode 100644 index a28507b9..00000000 --- a/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusDelegatingProxyUtils.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.archaius; - -import org.apache.commons.configuration.AbstractConfiguration; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; - -import com.netflix.config.ConfigurationManager; - -/** - * @author Dave Syer - */ -public class ArchaiusDelegatingProxyUtils { - - public static String APPLICATION_CONTEXT = ApplicationContext.class.getName(); - - public static T getNamedInstance(Class type, String name) { - ApplicationContext context = (ApplicationContext) ConfigurationManager - .getConfigInstance().getProperty(APPLICATION_CONTEXT); - return context != null && context.containsBean(name) ? context - .getBean(name, type) : null; - } - - public static T getInstanceWithPrefix(Class type, String prefix) { - String name = prefix + type.getSimpleName(); - return getNamedInstance(type, name); - } - - public static void addApplicationContext(ConfigurableApplicationContext context) { - AbstractConfiguration config = ConfigurationManager.getConfigInstance(); - config.clearProperty(APPLICATION_CONTEXT); - config.setProperty(APPLICATION_CONTEXT, context); - } - -} diff --git a/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusEndpoint.java b/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusEndpoint.java deleted file mode 100644 index e77114da..00000000 --- a/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusEndpoint.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.archaius; - -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.commons.configuration.AbstractConfiguration; -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.EnvironmentConfiguration; -import org.apache.commons.configuration.SystemConfiguration; -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; - -import com.netflix.config.ConcurrentCompositeConfiguration; -import com.netflix.config.ConfigurationManager; - -/** - * @author Dave Syer - */ -@Endpoint(id = "archaius") -public class ArchaiusEndpoint { - - @ReadOperation - public Map invoke() { - Map map = new LinkedHashMap<>(); - AbstractConfiguration config = ConfigurationManager.getConfigInstance(); - if (config instanceof ConcurrentCompositeConfiguration) { - ConcurrentCompositeConfiguration composite = (ConcurrentCompositeConfiguration) config; - for (Configuration item : composite.getConfigurations()) { - append(map, item); - } - } - else { - append(map, config); - } - return map; - } - - private void append(Map map, Configuration config) { - if (config instanceof ConfigurableEnvironmentConfiguration) { - return; - } - if (config instanceof SystemConfiguration) { - return; - } - if (config instanceof EnvironmentConfiguration) { - return; - } - for (Iterator iter = config.getKeys(); iter.hasNext();) { - String key = iter.next(); - map.put(key, config.getProperty(key)); - } - } - -} diff --git a/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ConfigurableEnvironmentConfiguration.java b/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ConfigurableEnvironmentConfiguration.java deleted file mode 100644 index a2419d78..00000000 --- a/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ConfigurableEnvironmentConfiguration.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.archaius; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.configuration.AbstractConfiguration; -import org.springframework.core.env.CompositePropertySource; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.EnumerablePropertySource; -import org.springframework.core.env.MutablePropertySources; -import org.springframework.core.env.PropertySource; -import org.springframework.core.env.StandardEnvironment; - -/** - * @author Spencer Gibb - */ -public class ConfigurableEnvironmentConfiguration extends AbstractConfiguration { - - private final ConfigurableEnvironment environment; - - public ConfigurableEnvironmentConfiguration(ConfigurableEnvironment environment) { - this.environment = environment; - } - - @Override - protected void addPropertyDirect(String key, Object value) { - - } - - @Override - public boolean isEmpty() { - return !getKeys().hasNext(); // TODO: find a better way to do this - } - - @Override - public boolean containsKey(String key) { - return this.environment.containsProperty(key); - } - - @Override - public Object getProperty(String key) { - return this.environment.getProperty(key); - } - - @Override - public Iterator getKeys() { - List result = new ArrayList<>(); - for (Map.Entry> entry : getPropertySources().entrySet()) { - PropertySource source = entry.getValue(); - if (source instanceof EnumerablePropertySource) { - EnumerablePropertySource enumerable = (EnumerablePropertySource) source; - for (String name : enumerable.getPropertyNames()) { - result.add(name); - } - } - } - return result.iterator(); - } - - private Map> getPropertySources() { - Map> map = new LinkedHashMap<>(); - MutablePropertySources sources = (this.environment != null ? this.environment - .getPropertySources() : new StandardEnvironment().getPropertySources()); - for (PropertySource source : sources) { - extract("", map, source); - } - return map; - } - - private void extract(String root, Map> map, - PropertySource source) { - if (source instanceof CompositePropertySource) { - for (PropertySource nest : ((CompositePropertySource) source) - .getPropertySources()) { - extract(source.getName() + ":", map, nest); - } - } - else { - map.put(root + source.getName(), source); - } - } - -} diff --git a/spring-cloud-netflix-archaius/src/main/resources/META-INF/spring.factories b/spring-cloud-netflix-archaius/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 834129cc..00000000 --- a/spring-cloud-netflix-archaius/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration \ No newline at end of file diff --git a/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/ArchaiusAutoConfigurationTests.java b/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/ArchaiusAutoConfigurationTests.java deleted file mode 100644 index 0a42ec6a..00000000 --- a/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/ArchaiusAutoConfigurationTests.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.archaius; - -import java.util.Collections; - -import org.apache.commons.configuration.AbstractConfiguration; -import org.apache.commons.configuration.event.ConfigurationEvent; -import org.apache.commons.configuration.event.ConfigurationListener; -import org.junit.After; -import org.junit.Test; -import org.springframework.boot.test.util.EnvironmentTestUtils; -import org.springframework.cloud.context.environment.EnvironmentChangeEvent; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; - -import com.netflix.config.ConfigurationManager; -import com.netflix.config.DynamicPropertyFactory; -import com.netflix.config.DynamicStringProperty; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -/** - * @author Dave Syer - */ -public class ArchaiusAutoConfigurationTests { - - private AnnotationConfigApplicationContext context; - private Object propertyValue; - - @After - public void close() { - if (this.context != null) { - this.context.close(); - } - } - - @Test - public void configurationCreated() { - this.context = new AnnotationConfigApplicationContext( - ArchaiusAutoConfiguration.class); - AbstractConfiguration config = this.context - .getBean(ConfigurableEnvironmentConfiguration.class); - assertNotNull(config.getString("java.io.tmpdir")); - } - - @Test - public void environmentChangeEventPropagated() { - this.context = new AnnotationConfigApplicationContext( - ArchaiusAutoConfiguration.class); - ConfigurationManager.getConfigInstance().addConfigurationListener( - new ConfigurationListener() { - @Override - public void configurationChanged(ConfigurationEvent event) { - if (event.getPropertyName().equals("my.prop")) { - ArchaiusAutoConfigurationTests.this.propertyValue = event - .getPropertyValue(); - } - } - }); - EnvironmentTestUtils.addEnvironment(this.context, "my.prop=my.newval"); - this.context.publishEvent(new EnvironmentChangeEvent(Collections - .singleton("my.prop"))); - assertEquals("my.newval", this.propertyValue); - } - - @Test - public void configurationWithoutExternalConfigurations() throws Exception { - this.context = new AnnotationConfigApplicationContext( - ArchaiusAutoConfiguration.class); - DynamicStringProperty dbProperty = DynamicPropertyFactory.getInstance() - .getStringProperty("db.property", null); - DynamicStringProperty staticProperty = DynamicPropertyFactory.getInstance() - .getStringProperty("archaius.file.property", null); - - assertNull(dbProperty.getValue()); - assertNotNull(staticProperty.getValue()); - assertEquals("Static config file property", staticProperty.getValue()); - } - - @Test - public void configurationWithInjectedConfiguration() throws Exception { - this.context = new AnnotationConfigApplicationContext( - ArchaiusAutoConfiguration.class, TestArchaiusExternalConfiguration.class); - DynamicStringProperty dbProperty = DynamicPropertyFactory.getInstance() - .getStringProperty("db.property", null); - DynamicStringProperty secondDbProperty = DynamicPropertyFactory.getInstance() - .getStringProperty("db.second.property", null); - DynamicStringProperty staticProperty = DynamicPropertyFactory.getInstance() - .getStringProperty("archaius.file.property", null); - - assertNotNull(dbProperty.getValue()); - assertNotNull(secondDbProperty.getValue()); - assertNotNull(staticProperty.getValue()); - assertEquals("this is a db property", dbProperty.getValue()); - assertEquals("this is another db property", secondDbProperty.getValue()); - assertEquals("Static config file property", staticProperty.getValue()); - } - -} diff --git a/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/ArchaiusEndpointTests.java b/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/ArchaiusEndpointTests.java deleted file mode 100644 index 50b883d2..00000000 --- a/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/ArchaiusEndpointTests.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.archaius; - -import java.util.Map; - -import org.junit.Test; -import org.springframework.core.env.StandardEnvironment; - -import com.netflix.config.ConcurrentCompositeConfiguration; -import com.netflix.config.ConfigurationManager; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - * @author Dave Syer - */ -public class ArchaiusEndpointTests { - - private ArchaiusEndpoint endpoint = new ArchaiusEndpoint(); - - @Test - public void detectsPropertiesWhenSet() { - ConfigurationManager.getConfigInstance().setProperty("foo", "bar"); - assertTrue(this.endpoint.invoke().containsKey("foo")); - } - - @Test - public void doesNotIncludeSpringEnvironment() { - ConcurrentCompositeConfiguration composite = new ConcurrentCompositeConfiguration( - ConfigurationManager.getConfigInstance()); - ConfigurableEnvironmentConfiguration config = new ConfigurableEnvironmentConfiguration( - new StandardEnvironment()); - assertTrue(config.containsKey("user.dir")); - composite.addConfiguration(config); - ConfigurationManager.getConfigInstance().setProperty("foo", "bar"); - Map map = this.endpoint.invoke(); - assertTrue(map.containsKey("foo")); - assertFalse(map.containsKey("user.dir")); - } - -} diff --git a/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/TestArchaiusExternalConfiguration.java b/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/TestArchaiusExternalConfiguration.java deleted file mode 100644 index fa871eca..00000000 --- a/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/TestArchaiusExternalConfiguration.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.archaius; - -import org.apache.commons.configuration.AbstractConfiguration; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.netflix.config.ConcurrentMapConfiguration; - -/** - * @author Alexandru-George Burghelea - */ -@Configuration -public class TestArchaiusExternalConfiguration { - - @Bean - @Qualifier("dynamicConfiguration") - public AbstractConfiguration createDynamicConfiguration() { - ConcurrentMapConfiguration config = new ConcurrentMapConfiguration(); - config.addProperty("db.property","this is a db property"); - config.addProperty("db.second.property","this is another db property"); - return config; - } - -} diff --git a/spring-cloud-netflix-archaius/src/test/resources/config.properties b/spring-cloud-netflix-archaius/src/test/resources/config.properties deleted file mode 100644 index 1e9c021f..00000000 --- a/spring-cloud-netflix-archaius/src/test/resources/config.properties +++ /dev/null @@ -1,2 +0,0 @@ -archaius.file.property=Static config file property -db.second.property=It should be overridden diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/EnableHystrix.java b/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/EnableHystrix.java deleted file mode 100644 index eecebe16..00000000 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/EnableHystrix.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; - -/** - * Convenience annotation for clients to enable Hystrix circuit breakers (specifically). - * Use this (optionally) in case you want discovery and know for sure that it is Hystrix - * you want. All it does is turn on circuit breakers and let the autoconfiguration find - * the Hystrix classes if they are available (i.e. you need Hystrix on the classpath as - * well). - * - * @author Dave Syer - * @author Spencer Gibb - */ -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Inherited -@EnableCircuitBreaker -public @interface EnableHystrix { - -} diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixAutoConfiguration.java b/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixAutoConfiguration.java deleted file mode 100644 index efc05d96..00000000 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixAutoConfiguration.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.hystrix; - -import org.reactivestreams.Publisher; -import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; -import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator; -import org.springframework.boot.actuate.autoconfigure.health.HealthIndicatorAutoConfiguration; -import org.springframework.boot.actuate.health.Health; -import org.springframework.boot.actuate.health.HealthIndicator; -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.client.actuator.HasFeatures; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.reactive.DispatcherHandler; - -import com.netflix.hystrix.Hystrix; -import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect; -import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet; -import com.netflix.hystrix.metric.consumer.HystrixDashboardStream; -import com.netflix.hystrix.serial.SerialHystrixDashboardData; - -import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type.REACTIVE; -import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type.SERVLET; - -import rx.Observable; -import rx.RxReactiveStreams; - -/** - * Auto configuration for Hystrix. - * - * @author Christian Dupuis - * @author Dave Syer - */ -@Configuration -@ConditionalOnClass({ Hystrix.class, HealthIndicator.class }) -@AutoConfigureAfter({ HealthIndicatorAutoConfiguration.class }) -public class HystrixAutoConfiguration { - - @Bean - @ConditionalOnEnabledHealthIndicator("hystrix") - public HystrixHealthIndicator hystrixHealthIndicator() { - return new HystrixHealthIndicator(); - } - - /** - * See original {@link org.springframework.boot.actuate.autoconfigure.jolokia.JolokiaEndpointAutoConfiguration} - */ - @Configuration - @ConditionalOnWebApplication(type = SERVLET) - @ConditionalOnBean(HystrixCommandAspect.class) // only install the stream if enabled - @ConditionalOnClass({ Health.class, HystrixMetricsStreamServlet.class }) - @EnableConfigurationProperties(HystrixProperties.class) - protected static class HystrixServletAutoConfiguration { - - @Bean - @ConditionalOnEnabledEndpoint - public HystrixStreamEndpoint hystrixStreamEndpoint(HystrixProperties properties) { - return new HystrixStreamEndpoint(properties.getConfig()); - } - - @Bean - public HasFeatures hystrixStreamFeature() { - return HasFeatures.namedFeature("Hystrix Stream Servlet", HystrixMetricsStreamServlet.class); - } - } - - @Configuration - @ConditionalOnWebApplication(type = REACTIVE) - @ConditionalOnBean(HystrixCommandAspect.class) // only install the stream if enabled - @ConditionalOnClass({ Health.class, DispatcherHandler.class }) - @EnableConfigurationProperties(HystrixProperties.class) - protected static class HystrixWebfluxManagementContextConfiguration { - - @Bean - @ConditionalOnEnabledEndpoint - public HystrixWebfluxEndpoint hystrixWebfluxController() { - Observable serializedDashboardData = HystrixDashboardStream.getInstance().observe() - .concatMap(dashboardData -> Observable.from(SerialHystrixDashboardData.toMultipleJsonStrings(dashboardData))); - Publisher publisher = RxReactiveStreams.toPublisher(serializedDashboardData); - return new HystrixWebfluxEndpoint(publisher); - } - - @Bean - public HasFeatures hystrixStreamFeature() { - return HasFeatures.namedFeature("Hystrix Stream Webflux", HystrixMetricsStreamServlet.class); - } - } -} diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCircuitBreakerConfiguration.java b/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCircuitBreakerConfiguration.java deleted file mode 100644 index 20e6a611..00000000 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCircuitBreakerConfiguration.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix; - -import org.apache.catalina.core.ApplicationContext; -import org.springframework.beans.factory.DisposableBean; -import org.springframework.cloud.client.actuator.HasFeatures; -import org.springframework.cloud.client.actuator.NamedFeature; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.netflix.hystrix.Hystrix; -import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect; - -/** - * @author Spencer Gibb - * @author Christian Dupuis - * @author Venil Noronha - */ -@Configuration -public class HystrixCircuitBreakerConfiguration { - - @Bean - public HystrixCommandAspect hystrixCommandAspect() { - return new HystrixCommandAspect(); - } - - @Bean - public HystrixShutdownHook hystrixShutdownHook() { - return new HystrixShutdownHook(); - } - - @Bean - public HasFeatures hystrixFeature() { - return HasFeatures.namedFeatures(new NamedFeature("Hystrix", HystrixCommandAspect.class)); - } - - //FIXME: 2.0.0 - /*@Configuration - @ConditionalOnProperty(value = "hystrix.metrics.enabled", matchIfMissing = true) - @ConditionalOnClass({ HystrixMetricsPoller.class, GaugeService.class }) - @EnableConfigurationProperties(HystrixMetricsProperties.class) - protected static class HystrixMetricsPollerConfiguration implements SmartLifecycle { - - private static Log logger = LogFactory - .getLog(HystrixMetricsPollerConfiguration.class); - - @Autowired(required = false) - private GaugeService gauges; - - @Autowired - private HystrixMetricsProperties metricsProperties; - - private ObjectMapper mapper = new ObjectMapper(); - - private HystrixMetricsPoller poller; - - private Set reserved = new HashSet(Arrays.asList("group", "name", - "type", "currentTime")); - - @Override - public void start() { - if (this.gauges == null) { - return; - } - MetricsAsJsonPollerListener listener = new MetricsAsJsonPollerListener() { - @Override - public void handleJsonMetric(String json) { - try { - @SuppressWarnings("unchecked") - Map map = HystrixMetricsPollerConfiguration.this.mapper - .readValue(json, Map.class); - if (map != null && map.containsKey("type")) { - addMetrics(map, "hystrix."); - } - } - catch (IOException ex) { - // ignore - } - } - - }; - this.poller = new HystrixMetricsPoller(listener, - metricsProperties.getPollingIntervalMs()); - // start polling and it will write directly to the listener - this.poller.start(); - logger.info("Starting poller"); - } - - private void addMetrics(Map map, String root) { - StringBuilder prefixBuilder = new StringBuilder(root); - if (map.containsKey("type")) { - prefixBuilder.append((String) map.get("type")); - if (map.containsKey("group")) { - prefixBuilder.append(".").append(map.get("group")); - } - prefixBuilder.append(".").append(map.get("name")); - } - String prefix = prefixBuilder.toString(); - for (String key : map.keySet()) { - Object value = map.get(key); - if (!this.reserved.contains(key)) { - if (value instanceof Number) { - String name = prefix + "." + key; - this.gauges.submit(name, ((Number) value).doubleValue()); - } - else if (value instanceof Map) { - @SuppressWarnings("unchecked") - Map sub = (Map) value; - addMetrics(sub, prefix); - } - } - } - } - - @Override - public void stop() { - if (this.poller != null) { - this.poller.shutdown(); - } - } - - @Override - public boolean isRunning() { - return this.poller != null ? this.poller.isRunning() : false; - } - - @Override - public int getPhase() { - return Ordered.LOWEST_PRECEDENCE; - } - - @Override - public boolean isAutoStartup() { - return true; - } - - @Override - public void stop(Runnable callback) { - if (this.poller != null) { - this.poller.shutdown(); - } - callback.run(); - } - - }*/ - - /** - * {@link DisposableBean} that makes sure that Hystrix internal state is cleared when - * {@link ApplicationContext} shuts down. - */ - private class HystrixShutdownHook implements DisposableBean { - - @Override - public void destroy() throws Exception { - // Just call Hystrix to reset thread pool etc. - Hystrix.reset(); - } - - } - -} diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCommands.java b/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCommands.java deleted file mode 100644 index 763442dd..00000000 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCommands.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix; - -import java.util.function.Function; - -import org.reactivestreams.Publisher; -import org.springframework.util.StringUtils; - -import com.netflix.hystrix.HystrixCommandGroupKey; -import com.netflix.hystrix.HystrixCommandKey; -import com.netflix.hystrix.HystrixCommandProperties; -import com.netflix.hystrix.HystrixObservableCommand; -import com.netflix.hystrix.HystrixObservableCommand.Setter; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import rx.Observable; -import rx.RxReactiveStreams; - -/** - * Utility class to wrap a {@see Publisher} in a {@see HystrixObservableCommand}. Good for - * use in a Spring WebFlux application. Allows more flexibility than the @HystrixCommand - * annotation. - * @author Spencer Gibb - */ -public class HystrixCommands { - - public static PublisherBuilder from(Publisher publisher) { - return new PublisherBuilder<>(publisher); - } - - public static class PublisherBuilder { - private final Publisher publisher; - private String commandName; - private String groupName; - private Publisher fallback; - private Setter setter; - private HystrixCommandProperties.Setter commandProperties; - private boolean eager = false; - private Function, Observable> toObservable; - - public PublisherBuilder(Publisher publisher) { - this.publisher = publisher; - } - - public PublisherBuilder commandName(String commandName) { - this.commandName = commandName; - return this; - } - - public PublisherBuilder groupName(String groupName) { - this.groupName = groupName; - return this; - } - - public PublisherBuilder fallback(Publisher fallback) { - this.fallback = fallback; - return this; - } - - public PublisherBuilder setter(Setter setter) { - this.setter = setter; - return this; - } - - public PublisherBuilder commandProperties( - HystrixCommandProperties.Setter commandProperties) { - this.commandProperties = commandProperties; - return this; - } - - public PublisherBuilder commandProperties( - Function commandProperties) { - if (commandProperties == null) { - throw new IllegalArgumentException( - "commandProperties must not both be null"); - } - return this.commandProperties( - commandProperties.apply(HystrixCommandProperties.Setter())); - } - - public PublisherBuilder eager() { - this.eager = true; - return this; - } - - public PublisherBuilder toObservable(Function, Observable> toObservable) { - this.toObservable = toObservable; - return this; - } - - public Publisher build() { - if (!StringUtils.hasText(commandName) && setter == null) { - throw new IllegalStateException("commandName and setter can not both be empty"); - } - Setter setterToUse = getSetter(); - - PublisherHystrixCommand command = new PublisherHystrixCommand<>(setterToUse, this.publisher, this.fallback); - - Observable observable = getObservableFunction().apply(command); - - return RxReactiveStreams.toPublisher(observable); - } - - public Function, Observable> getObservableFunction() { - Function, Observable> observableFunc; - - if (this.toObservable != null) { - observableFunc = this.toObservable; - } else if (this.eager) { - observableFunc = cmd -> cmd.observe(); - } else { // apply a default onBackpressureBuffer if not eager - observableFunc = cmd -> cmd.toObservable().onBackpressureBuffer(); - } - return observableFunc; - } - - public Setter getSetter() { - Setter setterToUse; - if (this.setter != null) { - setterToUse = this.setter; - } else { - String groupNameToUse; - if (StringUtils.hasText(this.groupName)) { - groupNameToUse = this.groupName; - } else { - groupNameToUse = commandName + "group"; - } - - HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey(groupNameToUse); - HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey(this.commandName); - HystrixCommandProperties.Setter commandProperties = this.commandProperties != null - ? this.commandProperties - : HystrixCommandProperties.Setter(); - setterToUse = Setter.withGroupKey(groupKey).andCommandKey(commandKey) - .andCommandPropertiesDefaults(commandProperties); - } - return setterToUse; - } - - public Flux toFlux() { - return Flux.from(build()); - } - - public Mono toMono() { - return Mono.from(build()); - } - - } - - private static class PublisherHystrixCommand extends HystrixObservableCommand { - - private Publisher publisher; - private Publisher fallback; - - protected PublisherHystrixCommand(Setter setter, Publisher publisher, - Publisher fallback) { - super(setter); - this.publisher = publisher; - this.fallback = fallback; - } - - @Override - protected Observable construct() { - return RxReactiveStreams.toObservable(publisher); - } - - @Override - protected Observable resumeWithFallback() { - if (this.fallback != null) { - return RxReactiveStreams.toObservable(this.fallback); - } - return super.resumeWithFallback(); - } - } -} diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixConstants.java b/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixConstants.java deleted file mode 100644 index 073eec02..00000000 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixConstants.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix; - -/** - * @author Spencer Gibb - */ -public class HystrixConstants { - - public static final String HYSTRIX_STREAM_DESTINATION = "springCloudHystrixStream"; - - private HystrixConstants() { - throw new AssertionError("Must not instantiate constant utility class"); - } - -} diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixHealthIndicator.java b/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixHealthIndicator.java deleted file mode 100644 index fb1a8bfe..00000000 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixHealthIndicator.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix; - -import java.util.ArrayList; -import java.util.List; - -import org.springframework.boot.actuate.health.AbstractHealthIndicator; -import org.springframework.boot.actuate.health.Health.Builder; -import org.springframework.boot.actuate.health.HealthIndicator; -import org.springframework.boot.actuate.health.Status; - -import com.netflix.hystrix.HystrixCircuitBreaker; -import com.netflix.hystrix.HystrixCommandMetrics; - -/** - * A {@link HealthIndicator} implementation for Hystrix circuit breakers. - *

- * This default implementation will not change the system state (e.g. OK) but - * includes all open circuits by name. - * - * @author Christian Dupuis - */ -public class HystrixHealthIndicator extends AbstractHealthIndicator { - - private static final Status CIRCUIT_OPEN = new Status("CIRCUIT_OPEN"); - - @Override - protected void doHealthCheck(Builder builder) throws Exception { - List openCircuitBreakers = new ArrayList<>(); - - // Collect all open circuit breakers from Hystrix - for (HystrixCommandMetrics metrics : HystrixCommandMetrics.getInstances()) { - HystrixCircuitBreaker circuitBreaker = HystrixCircuitBreaker.Factory - .getInstance(metrics.getCommandKey()); - if (circuitBreaker != null && circuitBreaker.isOpen()) { - openCircuitBreakers.add(metrics.getCommandGroup().name() + "::" - + metrics.getCommandKey().name()); - } - } - - // If there is at least one open circuit report OUT_OF_SERVICE adding the command - // group - // and key name - if (!openCircuitBreakers.isEmpty()) { - builder.status(CIRCUIT_OPEN).withDetail("openCircuitBreakers", - openCircuitBreakers); - } - else { - builder.up(); - } - } - -} diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixMetricsProperties.java b/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixMetricsProperties.java deleted file mode 100644 index 5501efd6..00000000 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixMetricsProperties.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -import java.util.Objects; - -/** - * @author Venil Noronha - * @author Gregor Zurowski - */ -@ConfigurationProperties("hystrix.metrics") -public class HystrixMetricsProperties { - - /** Enable Hystrix metrics polling. Defaults to true. */ - private boolean enabled = true; - - /** Interval between subsequent polling of metrics. Defaults to 2000 ms. */ - private Integer pollingIntervalMs = 2000; - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public Integer getPollingIntervalMs() { - return pollingIntervalMs; - } - - public void setPollingIntervalMs(Integer pollingIntervalMs) { - this.pollingIntervalMs = pollingIntervalMs; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - HystrixMetricsProperties that = (HystrixMetricsProperties) o; - return enabled == that.enabled && - Objects.equals(pollingIntervalMs, that.pollingIntervalMs); - } - - @Override - public int hashCode() { - return Objects.hash(enabled, pollingIntervalMs); - } - - @Override - public String toString() { - return new StringBuilder("HystrixMetricsProperties{") - .append("enabled=").append(enabled).append(", ") - .append("pollingIntervalMs=").append(pollingIntervalMs) - .append("}").toString(); - } -} diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixProperties.java b/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixProperties.java deleted file mode 100644 index 2039c62c..00000000 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixProperties.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.hystrix; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * Configuration properties for Hystrix Servlet. - * - * @author Spencer Gibb - * @since 2.0.0 - */ -@ConfigurationProperties(prefix = "management.endpoint.hystrix") -public class HystrixProperties { - - /** - * Hystrix settings. These are traditionally set using servlet parameters. Refer to - * the documentation of Hystrix for more details. - */ - private final Map config = new HashMap<>(); - - public Map getConfig() { - return this.config; - } - -} - diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpoint.java b/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpoint.java deleted file mode 100644 index af2d870b..00000000 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpoint.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.hystrix; - -import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet; -import org.springframework.boot.actuate.endpoint.web.EndpointServlet; -import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpoint; - -import java.util.Map; -import java.util.function.Supplier; - -/** - * {@link org.springframework.boot.actuate.endpoint.annotation.Endpoint} to expose a Jolokia {@link HystrixMetricsStreamServlet}. - * - * @author Phillip Webb - * @since 2.0.0 - */ -@ServletEndpoint(id = "hystrix.stream") -public class HystrixStreamEndpoint implements Supplier { - - private final Map initParameters; - - public HystrixStreamEndpoint(Map initParameters) { - this.initParameters = initParameters; - } - - @Override - public EndpointServlet get() { - return new EndpointServlet(HystrixMetricsStreamServlet.class) - .withInitParameters(this.initParameters); - } -} diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpoint.java b/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpoint.java deleted file mode 100644 index a9f4f220..00000000 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpoint.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.hystrix; - -import java.time.Duration; - -import org.reactivestreams.Publisher; -import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint; -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.GetMapping; - -import reactor.core.publisher.Flux; - -/** - * @author Spencer Gibb - */ -@RestControllerEndpoint(id = "hystrix.stream") -public class HystrixWebfluxEndpoint { - - private final Flux stream; - - public HystrixWebfluxEndpoint(Publisher dashboardData) { - stream = Flux.interval(Duration.ofMillis(500)).map(aLong -> "{\"type\":\"ping\"}") - .mergeWith(dashboardData).share(); - } - - // path needs to be empty, so it registers correct as /actuator/hystrix.stream - @GetMapping(path = "", produces = MediaType.TEXT_EVENT_STREAM_VALUE) - public Flux hystrixStream() { - return stream; - } -} diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfiguration.java b/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfiguration.java deleted file mode 100644 index 272f234e..00000000 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfiguration.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.security; - -import javax.annotation.PostConstruct; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.AllNestedConditions; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.netflix.hystrix.security.HystrixSecurityAutoConfiguration.HystrixSecurityCondition; -import org.springframework.context.annotation.Conditional; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.core.context.SecurityContext; - -import com.netflix.hystrix.Hystrix; -import com.netflix.hystrix.strategy.HystrixPlugins; -import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; -import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier; -import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook; -import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher; -import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; - -/** - * @author Daniel Lavoie - */ -@Configuration -@Conditional(HystrixSecurityCondition.class) -@ConditionalOnClass({ Hystrix.class, SecurityContext.class }) -public class HystrixSecurityAutoConfiguration { - @Autowired(required = false) - private HystrixConcurrencyStrategy existingConcurrencyStrategy; - - @PostConstruct - public void init() { - // Keeps references of existing Hystrix plugins. - HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance() - .getEventNotifier(); - HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance() - .getMetricsPublisher(); - HystrixPropertiesStrategy propertiesStrategy = HystrixPlugins.getInstance() - .getPropertiesStrategy(); - HystrixCommandExecutionHook commandExecutionHook = HystrixPlugins.getInstance() - .getCommandExecutionHook(); - - HystrixPlugins.reset(); - - // Registers existing plugins excepts the Concurrent Strategy plugin. - HystrixPlugins.getInstance().registerConcurrencyStrategy( - new SecurityContextConcurrencyStrategy(existingConcurrencyStrategy)); - HystrixPlugins.getInstance().registerEventNotifier(eventNotifier); - HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher); - HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy); - HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook); - } - - static class HystrixSecurityCondition extends AllNestedConditions { - - public HystrixSecurityCondition() { - super(ConfigurationPhase.REGISTER_BEAN); - } - - @ConditionalOnProperty(name = "hystrix.shareSecurityContext") - static class ShareSecurityContext { - - } - } -} diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/security/SecurityContextConcurrencyStrategy.java b/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/security/SecurityContextConcurrencyStrategy.java deleted file mode 100644 index a438882c..00000000 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/security/SecurityContextConcurrencyStrategy.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.security; - -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Callable; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import com.netflix.hystrix.HystrixThreadPoolProperties; -import org.springframework.security.concurrent.DelegatingSecurityContextCallable; - -import com.netflix.hystrix.HystrixThreadPoolKey; -import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; -import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariable; -import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableLifecycle; -import com.netflix.hystrix.strategy.properties.HystrixProperty; - -/** - * @author daniellavoie - */ -public class SecurityContextConcurrencyStrategy extends HystrixConcurrencyStrategy { - private HystrixConcurrencyStrategy existingConcurrencyStrategy; - - public SecurityContextConcurrencyStrategy( - HystrixConcurrencyStrategy existingConcurrencyStrategy) { - this.existingConcurrencyStrategy = existingConcurrencyStrategy; - } - - @Override - public BlockingQueue getBlockingQueue(int maxQueueSize) { - return existingConcurrencyStrategy != null - ? existingConcurrencyStrategy.getBlockingQueue(maxQueueSize) - : super.getBlockingQueue(maxQueueSize); - } - - @Override - public HystrixRequestVariable getRequestVariable( - HystrixRequestVariableLifecycle rv) { - return existingConcurrencyStrategy != null - ? existingConcurrencyStrategy.getRequestVariable(rv) - : super.getRequestVariable(rv); - } - - @Override - public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey, - HystrixProperty corePoolSize, - HystrixProperty maximumPoolSize, - HystrixProperty keepAliveTime, TimeUnit unit, - BlockingQueue workQueue) { - return existingConcurrencyStrategy != null - ? existingConcurrencyStrategy.getThreadPool(threadPoolKey, corePoolSize, - maximumPoolSize, keepAliveTime, unit, workQueue) - : super.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize, - keepAliveTime, unit, workQueue); - } - - @Override - public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties threadPoolProperties) { - return existingConcurrencyStrategy != null - ? existingConcurrencyStrategy.getThreadPool(threadPoolKey, threadPoolProperties) - : super.getThreadPool(threadPoolKey, threadPoolProperties); - } - - @Override - public Callable wrapCallable(Callable callable) { - return existingConcurrencyStrategy != null - ? existingConcurrencyStrategy - .wrapCallable(new DelegatingSecurityContextCallable(callable)) - : super.wrapCallable(new DelegatingSecurityContextCallable(callable)); - } -} diff --git a/spring-cloud-netflix-core/src/main/resources/META-INF/spring.factories b/spring-cloud-netflix-core/src/main/resources/META-INF/spring.factories deleted file mode 100644 index d14e8902..00000000 --- a/spring-cloud-netflix-core/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,11 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -org.springframework.cloud.netflix.feign.ribbon.FeignRibbonClientAutoConfiguration,\ -org.springframework.cloud.netflix.feign.FeignAutoConfiguration,\ -org.springframework.cloud.netflix.feign.encoding.FeignAcceptGzipEncodingAutoConfiguration,\ -org.springframework.cloud.netflix.feign.encoding.FeignContentGzipEncodingAutoConfiguration,\ -org.springframework.cloud.netflix.hystrix.HystrixAutoConfiguration,\ -org.springframework.cloud.netflix.hystrix.security.HystrixSecurityAutoConfiguration,\ -org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration - -org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker=\ -org.springframework.cloud.netflix.hystrix.HystrixCircuitBreakerConfiguration diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/AdhocTestSuite.java b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/AdhocTestSuite.java deleted file mode 100644 index f57abb17..00000000 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/AdhocTestSuite.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2012-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix; - -import org.junit.Ignore; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -/** - * A test suite for probing weird ordering problems in the tests. - * - * @author Dave Syer - */ -@RunWith(Suite.class) -@SuiteClasses({ - // org.springframework.cloud.netflix.test.OkHttpClientConfigurationTests.class, - // org.springframework.cloud.netflix.test.ApacheHttpClientConfigurationTests.class, - // org.springframework.cloud.netflix.hystrix.HystrixCommandsTests.class, - // org.springframework.cloud.netflix.hystrix.HystrixOnlyTests.class, - // org.springframework.cloud.netflix.hystrix.security.HystrixSecurityTests.class, - // org.springframework.cloud.netflix.hystrix.security.HystrixSecurityNoFeignTests.class, - // org.springframework.cloud.netflix.hystrix.HystrixStreamEndpointTests.class, - // org.springframework.cloud.netflix.hystrix.HystrixConfigurationTests.class, - // org.springframework.cloud.netflix.resttemplate.RestTemplateRetryTests.class, - // org.springframework.cloud.netflix.ribbon.RibbonClientPreprocessorOverridesRetryTests.class, - // org.springframework.cloud.netflix.ribbon.RibbonUtilsTests.class, - // org.springframework.cloud.netflix.ribbon.test.RibbonClientDefaultConfigurationTests.class, - // org.springframework.cloud.netflix.ribbon.RibbonClientConfigurationTests.class, - // org.springframework.cloud.netflix.ribbon.RibbonClientHttpRequestFactoryTests.class, - // org.springframework.cloud.netflix.ribbon.SpringRetryEnabledTests.class, - // org.springframework.cloud.netflix.ribbon.PlainRibbonClientPreprocessorIntegrationTests.class, - // org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClientTests.class, - // org.springframework.cloud.netflix.ribbon.apache.RibbonApacheHttpRequestTests.class, - // org.springframework.cloud.netflix.ribbon.apache.RibbonApacheHttpResponseTests.class, - // org.springframework.cloud.netflix.ribbon.RibbonClientPreprocessorIntegrationTests.class, - // org.springframework.cloud.netflix.ribbon.RibbonClientsPreprocessorIntegrationTests.class, - // org.springframework.cloud.netflix.ribbon.RibbonClientsEagerInitializationTests.class, - // org.springframework.cloud.netflix.ribbon.RibbonInterceptorTests.class, - // org.springframework.cloud.netflix.ribbon.support.ContextAwareRequestTests.class, - // org.springframework.cloud.netflix.ribbon.support.RibbonCommandContextTest.class, - // org.springframework.cloud.netflix.ribbon.support.RetryableStatusCodeExceptionTests.class, - // org.springframework.cloud.netflix.ribbon.ZonePreferenceServerListFilterTests.class, - // org.springframework.cloud.netflix.ribbon.DefaultServerIntrospectorDefaultTests.class, - // org.springframework.cloud.netflix.ribbon.RibbonClientPreprocessorPropertiesOverridesIntegrationTests.class, - // org.springframework.cloud.netflix.ribbon.RibbonLoadBalancedRetryPolicyFactoryTests.class, - // org.springframework.cloud.netflix.ribbon.SpringClientFactoryTests.class, - // org.springframework.cloud.netflix.ribbon.RibbonAutoConfigurationIntegrationTests.class, - // org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClientTests.class, - // org.springframework.cloud.netflix.ribbon.RibbonClientPreprocessorOverridesIntegrationTests.class, - // org.springframework.cloud.netflix.ribbon.RibbonApplicationContextInitializerTests.class, - // org.springframework.cloud.netflix.ribbon.okhttp.SpringRetryDisableOkHttpClientTests.class, - // org.springframework.cloud.netflix.ribbon.okhttp.OkHttpRibbonResponseTests.class, - // org.springframework.cloud.netflix.ribbon.okhttp.OkHttpLoadBalancingClientTests.class, - // org.springframework.cloud.netflix.ribbon.okhttp.OkHttpRibbonRequestTests.class, - // org.springframework.cloud.netflix.ribbon.okhttp.SpringRetryEnabledOkHttpClientTests.class, - // org.springframework.cloud.netflix.ribbon.RibbonClientConfigurationIntegrationTests.class, - // org.springframework.cloud.netflix.ribbon.RibbonDisabledTests.class, - // org.springframework.cloud.netflix.ribbon.DefaultServerIntrospectorTests.class, - // org.springframework.cloud.netflix.ribbon.SpringRetryDisabledTests.class, - // org.springframework.cloud.netflix.feign.beans.FeignClientTests.class, - // org.springframework.cloud.netflix.feign.FeignClientsRegistrarTests.class, - // org.springframework.cloud.netflix.feign.encoding.FeignAcceptEncodingTests.class, - // org.springframework.cloud.netflix.feign.encoding.FeignContentEncodingTests.class, - // org.springframework.cloud.netflix.feign.FeignLoggerFactoryTests.class, - // org.springframework.cloud.netflix.feign.FeignCompressionTests.class, - // org.springframework.cloud.netflix.feign.EnableFeignClientsTests.class, - // org.springframework.cloud.netflix.feign.SpringDecoderTests.class, - // org.springframework.cloud.netflix.feign.FeignClientUsingPropertiesTests.class, - // org.springframework.cloud.netflix.feign.FeignHttpClientUrlTests.class, - // org.springframework.cloud.netflix.feign.invalid.FeignClientValidationTests.class, - // org.springframework.cloud.netflix.feign.support.FeignHttpClientPropertiesTests.class, - // org.springframework.cloud.netflix.feign.support.SpringMvcContractTests.class, - // org.springframework.cloud.netflix.feign.support.SpringEncoderTests.class, - // org.springframework.cloud.netflix.feign.FeignClientOverrideDefaultsTests.class, - // org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClientOverrideTests.class, - // org.springframework.cloud.netflix.feign.ribbon.FeignRibbonClientPathTests.class, - // org.springframework.cloud.netflix.feign.ribbon.RetryableFeignLoadBalancerTests.class, - // org.springframework.cloud.netflix.feign.ribbon.FeignRibbonClientRetryTests.class, - // org.springframework.cloud.netflix.feign.ribbon.FeignLoadBalancerTests.class, - // org.springframework.cloud.netflix.feign.ribbon.FeignRibbonClientTests.class, - // org.springframework.cloud.netflix.feign.ribbon.CachingSpringLoadBalancerFactoryTests.class, - // org.springframework.cloud.netflix.feign.valid.scanning.FeignClientEnvVarTests.class, - // org.springframework.cloud.netflix.feign.valid.scanning.FeignClientScanningTests.class, - // org.springframework.cloud.netflix.feign.valid.FeignOkHttpTests.class, - // org.springframework.cloud.netflix.feign.valid.FeignClientValidationTests.class, - // org.springframework.cloud.netflix.feign.valid.FeignClientTests.class, - // org.springframework.cloud.netflix.feign.valid.FeignHttpClientTests.class, - // org.springframework.cloud.netflix.feign.valid.FeignClientNotPrimaryTests.class, - // org.springframework.cloud.netflix.feign.FeignClientFactoryTests.class, - -}) -@Ignore -public class AdhocTestSuite { - -} diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixCommandsTests.java b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixCommandsTests.java deleted file mode 100644 index 698ee8a2..00000000 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixCommandsTests.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix; - -import java.time.Duration; - -import org.junit.Test; - -import com.netflix.hystrix.exception.HystrixRuntimeException; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -public class HystrixCommandsTests { - - @Test - public void monoWorks() { - StepVerifier.create(HystrixCommands.from(Flux.just("works")) - .commandName("testworks") - .toMono()) - .expectNext("works") - .verifyComplete(); - } - - @Test - public void eagerMonoWorks() { - StepVerifier.create(HystrixCommands.from(Mono.just("works")) - .eager() - .commandName("testworks") - .toMono()) - .expectNext("works") - .verifyComplete(); - } - - @Test - public void monoTimesOut() { - StepVerifier.create(HystrixCommands.from(Mono.fromCallable(() -> { - Thread.sleep(1500); - return "timeout"; - })).commandName("failcmd").toMono()) - .verifyError(HystrixRuntimeException.class); - } - - @Test - public void monoFallbackWorks() { - StepVerifier.create(HystrixCommands.from(Mono.error(new Exception())) - .commandName("failcmd") - .fallback(Mono.just("fallback")) - .toMono()) - .expectNext("fallback") - .verifyComplete(); - } - - @Test - public void fluxWorks() { - StepVerifier.create(HystrixCommands.from( Flux.just("1", "2")) - .commandName("multiflux") - .toFlux()) - .expectNext("1") - .expectNext("2") - .verifyComplete(); - } - - @Test - public void fluxWorksDeferredRequest() { - StepVerifier.create(HystrixCommands.from(Flux.just("1", "2")) - .commandName("multiflux") - .build(), 1) - .expectNext("1") - .thenAwait(Duration.ofSeconds(1)) - .thenRequest(1) - .expectNext("2") - .verifyComplete(); - } - - @Test - public void toObservableFunctionWorks() { - StepVerifier.create(HystrixCommands.from(Flux.just("1", "2")) - .commandName("multiflux") - .toObservable(cmd -> cmd.toObservable()) - .build(), 1) - .expectNext("1") - .thenAwait(Duration.ofSeconds(1)) - .thenRequest(1) - .verifyError(); - } - - @Test - public void eagerFluxWorks() { - StepVerifier.create(HystrixCommands.from( Flux.just("1", "2")) - .commandName("multiflux") - .eager() - .toFlux()) - .expectNext("1") - .expectNext("2") - .verifyComplete(); - } - - @Test - public void fluxTimesOut() { - StepVerifier.create(HystrixCommands.from( Flux.from(s -> { - try { - Thread.sleep(1500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - })).commandName("failcmd").toFlux()) - .verifyError(HystrixRuntimeException.class); - } - - @Test - public void fluxFallbackWorks() { - StepVerifier.create(HystrixCommands.from(Flux.error(new Exception())) - .commandName("multiflux") - .fallback(Flux.just("a", "b")) - .toFlux()) - .expectNext("a") - .expectNext("b") - .verifyComplete(); - } - - @Test - public void extendTimeout() { - StepVerifier.create(HystrixCommands.from(Mono.fromCallable(() -> { - Thread.sleep(1500); - return "works"; - })).commandName("extendTimeout") - .commandProperties( - setter -> setter.withExecutionTimeoutInMilliseconds(2000)) - .toMono()) - .expectNext("works") - .verifyComplete(); - } - -} diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixConfigurationTests.java b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixConfigurationTests.java deleted file mode 100644 index 39628434..00000000 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixConfigurationTests.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix; - -import org.junit.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Dave Syer - * @author Biju Kunjummen - */ -public class HystrixConfigurationTests { - - @Test - public void nonWebAppStartsUp() { - new ApplicationContextRunner() - .withUserConfiguration(HystrixCircuitBreakerConfiguration.class) - .run(c -> { - assertThat(c).hasSingleBean(HystrixCommandAspect.class); - }); - } - -} \ No newline at end of file diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixOnlyTests.java b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixOnlyTests.java deleted file mode 100644 index d11dae59..00000000 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixOnlyTests.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix; - -import java.util.Base64; -import java.util.Map; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; -import static org.springframework.cloud.netflix.test.TestAutoConfiguration.PASSWORD; -import static org.springframework.cloud.netflix.test.TestAutoConfiguration.USER; - -/** - * @author Spencer Gibb - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = HystrixOnlyApplication.class, webEnvironment = RANDOM_PORT, - properties = "management.endpoint.health.show-details=true") -@DirtiesContext -@ActiveProfiles("proxysecurity") -public class HystrixOnlyTests { - private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); - - @LocalServerPort - private int port; - - @Test - public void testNormalExecution() { - ResponseEntity res = new TestRestTemplate() - .getForEntity("http://localhost:" + this.port + "/", String.class); - assertEquals("incorrect response", "Hello world", res.getBody()); - } - - @Test - public void testFailureFallback() { - ResponseEntity res = new TestRestTemplate() - .getForEntity("http://localhost:" + this.port + "/fail", String.class); - assertEquals("incorrect fallback", "Fallback Hello world", res.getBody()); - } - - @Test - @SuppressWarnings("unchecked") - public void testHystrixHealth() { - Map map = getHealth(); - assertThat(map).containsKeys("details"); - Map details = (Map) map.get("details"); - assertThat(details).containsKeys("hystrix"); - Map hystrix = (Map) details.get("hystrix"); - assertThat(hystrix).containsEntry("status", "UP"); - } - - @Test - public void testNoDiscoveryHealth() { - Map map = getHealth(); - // There is explicitly no discovery, so there should be no discovery health key - assertFalse("Incorrect existing discovery health key", - map.containsKey("discovery")); - } - - private Map getHealth() { - return new TestRestTemplate().exchange( - "http://localhost:" + this.port + BASE_PATH + "/health", HttpMethod.GET, - new HttpEntity(createBasicAuthHeader(USER, PASSWORD)), - Map.class).getBody(); - } - - public static HttpHeaders createBasicAuthHeader(final String username, - final String password) { - return new HttpHeaders() { - private static final long serialVersionUID = 1766341693637204893L; - - { - String auth = username + ":" + password; - byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes()); - String authHeader = "Basic " + new String(encodedAuth); - this.set("Authorization", authHeader); - } - }; - } -} - -class Service { - @HystrixCommand - public String hello() { - return "Hello world"; - } - - @HystrixCommand(fallbackMethod = "fallback") - public String fail() { - throw new RuntimeException("Always fail"); - } - - public String fallback() { - return "Fallback Hello world"; - } -} - -// Don't use @SpringBootApplication because we don't want to component scan -@Configuration -@EnableAutoConfiguration -@EnableCircuitBreaker -@RestController -class HystrixOnlyApplication { - - @Bean - public Service service() { - return new Service(); - } - - @Autowired - private Service service; - - @RequestMapping("/") - public String home() { - return this.service.hello(); - } - - @RequestMapping("/fail") - public String fail() { - return this.service.fail(); - } - -} diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpointTests.java b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpointTests.java deleted file mode 100644 index 405cb987..00000000 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpointTests.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.hystrix; - -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * @author Dave Syer - * @author Spencer Gibb - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = HystrixStreamEndpointTests.Application.class, - webEnvironment = WebEnvironment.RANDOM_PORT, value = { - "spring.application.name=hystrixstreamtest" }) -@DirtiesContext -public class HystrixStreamEndpointTests { - private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); - private static final Log log = LogFactory.getLog(HystrixStreamEndpointTests.class); - - @LocalServerPort - private int port = 0; - - @Test - public void hystrixStreamWorks() throws Exception { - String url = "http://localhost:" + port; - // you have to hit a Hystrix circuit breaker before the stream sends anything - ResponseEntity response = new TestRestTemplate().getForEntity(url, - String.class); - assertEquals("bad response code", HttpStatus.OK, response.getStatusCode()); - - URL hystrixUrl = new URL(url + BASE_PATH + "/hystrix.stream"); - - List data = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - try (InputStream in = hystrixUrl.openStream()) { - byte[] buffer = new byte[1024]; - in.read(buffer); - data.add(new String(buffer)); - } catch (Exception e) { - log.error("Error getting hystrix stream, try " + i, e); - } - } - - for (String item : data) { - if (item.contains("data:")) { - return; // test passed - } - } - fail("/hystrix.stream didn't contain 'data:' was " + data); - } - - @Configuration - @EnableAutoConfiguration - @RestController - @EnableCircuitBreaker - protected static class Application { - @Autowired - Service service; - - @Bean - Service service() { - return new Service(); - } - - @RequestMapping("/") - public String hello() { - return service.hello(); - } - } - - protected static class Service { - @HystrixCommand - public String hello() { - return "Hello World"; - } - } -} diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpointTests.java b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpointTests.java deleted file mode 100644 index c8a2bd2a..00000000 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpointTests.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.hystrix; - -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; -import org.springframework.cloud.netflix.test.TestAutoConfiguration; -import org.springframework.http.MediaType; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.reactive.server.WebTestClient; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.reactive.function.client.WebClient; - -import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; - -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -import reactor.core.publisher.Flux; -import reactor.test.StepVerifier; - -/** - * @author Dave Syer - * @author Spencer Gibb - */ -@RunWith(SpringRunner.class) -@SpringBootTest( webEnvironment = RANDOM_PORT, properties = { - "spring.main.web-application-type=reactive", - "spring.application.name=hystrixstreamwebfluxtest", /*"debug=true"*/ }) -@DirtiesContext -public class HystrixWebfluxEndpointTests { - private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); - private static final Log log = LogFactory.getLog(HystrixWebfluxEndpointTests.class); - - @LocalServerPort - private int port; - - @Test - public void hystrixStreamWorks() { - String url = "http://localhost:" + port; - // you have to hit a Hystrix circuit breaker before the stream sends anything - WebTestClient testClient = WebTestClient.bindToServer().baseUrl(url).build(); - testClient.get().uri("/").exchange().expectStatus().isOk(); - - WebClient client = WebClient.create(url); - - Flux result = client.get().uri(BASE_PATH + "/hystrix.stream") - .accept(MediaType.TEXT_EVENT_STREAM) - .exchange() - .flatMapMany(res -> res.bodyToFlux(Map.class)) - .take(5) - .filter(map -> "HystrixCommand".equals(map.get("type"))) - .map(map -> (String)map.get("type")); - - StepVerifier.create(result) - .expectNext("HystrixCommand") - .thenCancel() - .verify(); - } - - @RestController - @EnableCircuitBreaker - @EnableAutoConfiguration(exclude = TestAutoConfiguration.class, - excludeName = {"org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration", - "org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration"}) - @SpringBootConfiguration - protected static class Config { - @HystrixCommand - @RequestMapping("/") - public String hi() { - return "hi"; - } - } -} diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityApplication.java b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityApplication.java deleted file mode 100644 index 7d146703..00000000 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityApplication.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.security; - -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.hystrix.security.app.UsernameClient; -import org.springframework.context.annotation.Configuration; - -/** - * @author Daniel Lavoie - */ -@Configuration -@SpringBootApplication -@EnableFeignClients(clients = UsernameClient.class) -public class HystrixSecurityApplication { - -} diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityNoFeignTests.java b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityNoFeignTests.java deleted file mode 100644 index e9a36fd3..00000000 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityNoFeignTests.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.hystrix.security; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; - -import com.netflix.hystrix.strategy.HystrixPlugins; -import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringRunner.class) -@DirtiesContext -@SpringBootTest(classes = HystrixSecurityApplication.class) -public class HystrixSecurityNoFeignTests { - - @Test - public void testSecurityConcurrencyStrategyInstalled() { - HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy(); - assertThat(concurrencyStrategy).isInstanceOf(SecurityContextConcurrencyStrategy.class); - } - -} diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityTests.java b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityTests.java deleted file mode 100644 index afba9657..00000000 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityTests.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.security; - -import java.util.Base64; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.netflix.hystrix.security.app.CustomConcurrenyStrategy; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; - -import com.netflix.hystrix.strategy.HystrixPlugins; -import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests that a secured web service returning values using a feign client properly access - * the security context from a hystrix command. - * @author Daniel Lavoie - */ -@RunWith(SpringRunner.class) -@DirtiesContext -@SpringBootTest(classes = HystrixSecurityApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "username.ribbon.listOfServers=localhost:${local.server.port}", - "feign.hystrix.enabled=true"}) -@ActiveProfiles("proxysecurity") -public class HystrixSecurityTests { - @Autowired - private CustomConcurrenyStrategy customConcurrenyStrategy; - - @LocalServerPort - private String serverPort; - - //TODOO: move to constants in TestAutoConfiguration - private String username = "user"; - - private String password = "password"; - - @Test - public void testSecurityConcurrencyStrategyInstalled() { - HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy(); - assertThat(concurrencyStrategy).isInstanceOf(SecurityContextConcurrencyStrategy.class); - } - - @Test - public void testFeignHystrixSecurity() { - HttpHeaders headers = HystrixSecurityTests.createBasicAuthHeader(username, - password); - - String usernameResult = new RestTemplate() - .exchange("http://localhost:" + serverPort + "/proxy-username", - HttpMethod.GET, new HttpEntity(headers), String.class) - .getBody(); - - Assert.assertTrue("Username should have been intercepted by feign interceptor.", - username.equals(usernameResult)); - - Assert.assertTrue("Custom hook should have been called.", - customConcurrenyStrategy.isHookCalled()); - } - - public static HttpHeaders createBasicAuthHeader(final String username, - final String password) { - return new HttpHeaders() { - private static final long serialVersionUID = 1766341693637204893L; - - { - String auth = username + ":" + password; - byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes()); - String authHeader = "Basic " + new String(encodedAuth); - this.set("Authorization", authHeader); - } - }; - } -} diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/CustomConcurrenyStrategy.java b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/CustomConcurrenyStrategy.java deleted file mode 100644 index 674adf67..00000000 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/CustomConcurrenyStrategy.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.springframework.cloud.netflix.hystrix.security.app; - -import java.util.concurrent.Callable; - -import org.springframework.stereotype.Component; - -import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; - -@Component -public class CustomConcurrenyStrategy extends HystrixConcurrencyStrategy { - private boolean hookCalled; - - @Override - public Callable wrapCallable(Callable callable) { - this.hookCalled = true; - - return super.wrapCallable(callable); - } - - public boolean isHookCalled() { - return hookCalled; - } -} diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/ProxyUsernameController.java b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/ProxyUsernameController.java deleted file mode 100644 index 2f30427c..00000000 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/ProxyUsernameController.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.security.app; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - * @author Daniel Lavoie - */ -@RestController -@RequestMapping("/proxy-username") -public class ProxyUsernameController { - @Autowired - private UsernameClient usernameClient; - - @RequestMapping - public String getUsername() { - return usernameClient.getUsername(); - } -} diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/TestInterceptor.java b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/TestInterceptor.java deleted file mode 100644 index c904de7e..00000000 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/TestInterceptor.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.security.app; - -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Component; - -import feign.RequestInterceptor; -import feign.RequestTemplate; - -/** - * This interceptor should be called from an Hyxtrix command execution thread. It is - * access the SecurityContext and settings an http header from the authentication details. - * - * @author Daniel Lavoie - */ -@Component -public class TestInterceptor implements RequestInterceptor { - - @Override - public void apply(RequestTemplate template) { - if (SecurityContextHolder.getContext().getAuthentication() != null) - template.header("username", - SecurityContextHolder.getContext().getAuthentication().getName()); - } -} diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/UsernameClient.java b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/UsernameClient.java deleted file mode 100644 index b630f839..00000000 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/UsernameClient.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.security.app; - -import org.springframework.cloud.netflix.feign.FeignClient; -import org.springframework.web.bind.annotation.RequestMapping; - -/** - * @author Daniel Lavoie - */ -@FeignClient("username") -public interface UsernameClient { - - @RequestMapping("/username") - public String getUsername(); -} diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/UsernameController.java b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/UsernameController.java deleted file mode 100644 index 54605b8e..00000000 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/UsernameController.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.security.app; - -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - * @author Daniel Lavoie - */ -@RestController -@RequestMapping("/username") -public class UsernameController { - @RequestMapping - public String getUsername(@RequestHeader String username){ - return username; - } -} diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/resttemplate/RestTemplateRetryTests.java b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/resttemplate/RestTemplateRetryTests.java deleted file mode 100644 index 1458353f..00000000 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/resttemplate/RestTemplateRetryTests.java +++ /dev/null @@ -1,287 +0,0 @@ -package org.springframework.cloud.netflix.resttemplate; - -import java.net.UnknownHostException; -import java.util.Arrays; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.loadbalancer.LoadBalanced; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.util.SocketUtils; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; - -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.AvailabilityFilteringRule; -import com.netflix.loadbalancer.BaseLoadBalancer; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.IPing; -import com.netflix.loadbalancer.IRule; -import com.netflix.loadbalancer.LoadBalancerBuilder; -import com.netflix.loadbalancer.LoadBalancerStats; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.loadbalancer.ServerStats; -import com.netflix.niws.client.http.HttpClientLoadBalancerErrorHandler; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = RestTemplateRetryTests.Application.class, webEnvironment = RANDOM_PORT, - properties = { "spring.application.name=resttemplatetest", "logging.level.com.netflix=DEBUG", - "logging.level.org.springframework.cloud.netflix.resttemplate=DEBUG", - "logging.level.com.netflix=DEBUG", "badClients.ribbon.MaxAutoRetries=25", - "badClients.ribbon.OkToRetryOnAllOperations=true", "ribbon.http.client.enabled" }) -@DirtiesContext -public class RestTemplateRetryTests { - - private static final Log logger = LogFactory.getLog(RestTemplateRetryTests.class); - - @Autowired - private RestTemplate testClient; - - @Before - public void setup() throws Exception { - // Force Ribbon configuration by making one call. - this.testClient.getForObject("http://badClients/ping", Integer.class); - } - - @Test - public void testNullPointer() throws Exception { - - LoadBalancerStats stats = LocalBadClientConfiguration.balancer - .getLoadBalancerStats(); - ServerStats badServer1Stats = stats - .getSingleServerStat(LocalBadClientConfiguration.badServer); - ServerStats badServer2Stats = stats - .getSingleServerStat(LocalBadClientConfiguration.badServer2); - ServerStats goodServerStats = stats - .getSingleServerStat(LocalBadClientConfiguration.goodServer); - - badServer1Stats.clearSuccessiveConnectionFailureCount(); - badServer2Stats.clearSuccessiveConnectionFailureCount(); - int numCalls = 10; - long targetConnectionCount = goodServerStats.getTotalRequestsCount() + numCalls; - - // A null pointer should NOT trigger a circuit breaker. - for (int index = 0; index < numCalls; index++) { - try { - this.testClient.getForObject("http://badClients/null", Integer.class); - } - catch (Exception exception) { - } - } - logServerStats(LocalBadClientConfiguration.badServer); - logServerStats(LocalBadClientConfiguration.badServer2); - logServerStats(LocalBadClientConfiguration.goodServer); - - assertTrue(badServer1Stats.isCircuitBreakerTripped()); - assertTrue(badServer2Stats.isCircuitBreakerTripped()); - assertThat(targetConnectionCount).isLessThanOrEqualTo(goodServerStats.getTotalRequestsCount()); - - // Wait for any timeout thread to finish. - - } - - private void logServerStats(Server server) { - LoadBalancerStats stats = LocalBadClientConfiguration.balancer - .getLoadBalancerStats(); - ServerStats serverStats = stats.getSingleServerStat(server); - logger.debug("Server : " + server.toString() + " : Total Count == " - + serverStats.getTotalRequestsCount() + ", Failure Count == " - + serverStats.getFailureCount() + ", Successive Connection Failure == " - + serverStats.getSuccessiveConnectionFailureCount() - + ", Circuit Breaker ? == " + serverStats.isCircuitBreakerTripped()); - } - - @Test - public void testRestRetries() { - - LoadBalancerStats stats = LocalBadClientConfiguration.balancer - .getLoadBalancerStats(); - ServerStats badServer1Stats = stats - .getSingleServerStat(LocalBadClientConfiguration.badServer); - ServerStats badServer2Stats = stats - .getSingleServerStat(LocalBadClientConfiguration.badServer2); - ServerStats goodServerStats = stats - .getSingleServerStat(LocalBadClientConfiguration.goodServer); - - badServer1Stats.clearSuccessiveConnectionFailureCount(); - badServer2Stats.clearSuccessiveConnectionFailureCount(); - int numCalls = 20; - long targetConnectionCount = goodServerStats.getTotalRequestsCount() + numCalls; - - int hits = 0; - - for (int index = 0; index < numCalls; index++) { - hits = this.testClient.getForObject("http://badClients/good", Integer.class); - } - - logServerStats(LocalBadClientConfiguration.badServer); - logServerStats(LocalBadClientConfiguration.badServer2); - logServerStats(LocalBadClientConfiguration.goodServer); - - assertTrue(badServer1Stats.isCircuitBreakerTripped()); - assertTrue(badServer2Stats.isCircuitBreakerTripped()); - assertThat(targetConnectionCount).isLessThanOrEqualTo(goodServerStats.getTotalRequestsCount()); - assertThat(hits).isGreaterThanOrEqualTo(numCalls); - logger.debug("Retry Hits: " + hits); - } - - @Test - public void testRestRetriesWithReadTimeout() throws Exception { - - LoadBalancerStats stats = LocalBadClientConfiguration.balancer - .getLoadBalancerStats(); - ServerStats badServer1Stats = stats - .getSingleServerStat(LocalBadClientConfiguration.badServer); - ServerStats badServer2Stats = stats - .getSingleServerStat(LocalBadClientConfiguration.badServer2); - ServerStats goodServerStats = stats - .getSingleServerStat(LocalBadClientConfiguration.goodServer); - - badServer1Stats.clearSuccessiveConnectionFailureCount(); - badServer2Stats.clearSuccessiveConnectionFailureCount(); - assertTrue(!badServer1Stats.isCircuitBreakerTripped()); - assertTrue(!badServer2Stats.isCircuitBreakerTripped()); - - int hits = 0; - - int numCalls = 15; - for (int index = 0; index < numCalls; index++) { - hits = this.testClient.getForObject("http://badClients/timeout", - Integer.class); - } - logServerStats(LocalBadClientConfiguration.badServer); - logServerStats(LocalBadClientConfiguration.badServer2); - logServerStats(LocalBadClientConfiguration.goodServer); - - assertTrue(badServer1Stats.isCircuitBreakerTripped()); - assertTrue(badServer2Stats.isCircuitBreakerTripped()); - assertTrue(!goodServerStats.isCircuitBreakerTripped()); - - // 15 + 4 timeouts. See the endpoint for timeout conditions. - assertThat(hits).isGreaterThanOrEqualTo(numCalls + 4); - - // Wait for any timeout thread to finish. - Thread.sleep(600); - - } - - @Configuration - @EnableAutoConfiguration - @RestController - @RibbonClient(name = "badClients", configuration = LocalBadClientConfiguration.class) - public static class Application { - - private AtomicInteger hits = new AtomicInteger(1); - private AtomicInteger retryHits = new AtomicInteger(1); - - @RequestMapping(method = RequestMethod.GET, value = "/ping") - public int ping() { - return 0; - } - - @RequestMapping(method = RequestMethod.GET, value = "/good") - public int good() { - int lValue = this.hits.getAndIncrement(); - return lValue; - } - - @RequestMapping(method = RequestMethod.GET, value = "/timeout") - public int timeout() throws Exception { - int lValue = this.retryHits.getAndIncrement(); - - // Force the good server to have 2 consecutive errors a couple of times. - if (lValue == 2 || lValue == 3 || lValue == 5 || lValue == 6) { - Thread.sleep(500); - } - return lValue; - } - - @RequestMapping(method = RequestMethod.GET, value = "/null") - public int isNull() throws Exception { - throw new NullPointerException("Null"); - } - - @LoadBalanced - @Bean - RestTemplate restTemplate() { - return new RestTemplate(); - } - } - - - // Load balancer with fixed server list for "local" pointing to localhost - // and some bogus servers are thrown in to test retry - @Configuration - static class LocalBadClientConfiguration { - - static BaseLoadBalancer balancer; - static Server goodServer; - static Server badServer; - static Server badServer2; - - public LocalBadClientConfiguration() { - } - - @Value("${local.server.port}") - private int port = 0; - - @Bean - public IRule loadBalancerRule() { - // This is a good place to try different load balancing rules and how those rules - // behave in failure states: BestAvailableRule, WeightedResponseTimeRule, etc - - // This rule just uses a round robin and will skip servers that are in circuit - // breaker state. - return new AvailabilityFilteringRule(); - - } - - @Bean - public ILoadBalancer ribbonLoadBalancer(IClientConfig config, - ServerList serverList, IRule rule, IPing ping) { - - goodServer = new Server("localhost", this.port); - badServer = new Server("mybadhost", 10001); - badServer2 = new Server("localhost", SocketUtils.findAvailableTcpPort()); - - balancer = LoadBalancerBuilder.newBuilder().withClientConfig(config) - .withRule(rule).withPing(ping).buildFixedServerListLoadBalancer( - Arrays.asList(badServer, badServer2, goodServer)); - return balancer; - } - - @Bean - public RetryHandler retryHandler() { - return new OverrideRetryHandler(); - } - - static class OverrideRetryHandler extends HttpClientLoadBalancerErrorHandler { - public OverrideRetryHandler() { - this.circuitRelated.add(UnknownHostException.class); - this.retriable.add(UnknownHostException.class); - } - } - - } -} diff --git a/spring-cloud-netflix-core/src/test/resources/archaius_db_store.sql b/spring-cloud-netflix-core/src/test/resources/archaius_db_store.sql deleted file mode 100644 index 6b914cb5..00000000 --- a/spring-cloud-netflix-core/src/test/resources/archaius_db_store.sql +++ /dev/null @@ -1,8 +0,0 @@ -create table if not exists properties ( - property_key VARCHAR(40) NOT NULL PRIMARY KEY, - property_value VARCHAR(255) NOT NULL, -); - -insert into properties(property_key, property_value) values ('db.property','this is a db property'); -insert into properties(property_key, property_value) values ('db.second.property','this is another db property'); - diff --git a/spring-cloud-netflix-core/src/test/resources/config.properties.bak b/spring-cloud-netflix-core/src/test/resources/config.properties.bak deleted file mode 100644 index 1e9c021f..00000000 --- a/spring-cloud-netflix-core/src/test/resources/config.properties.bak +++ /dev/null @@ -1,2 +0,0 @@ -archaius.file.property=Static config file property -db.second.property=It should be overridden diff --git a/spring-cloud-netflix-core/src/test/resources/static/index.html b/spring-cloud-netflix-core/src/test/resources/static/index.html deleted file mode 100644 index 27f58190..00000000 --- a/spring-cloud-netflix-core/src/test/resources/static/index.html +++ /dev/null @@ -1,28 +0,0 @@ - - -

- File to upload:
Name:

Press here to upload the file via ribbon proxy! -
-
- File to upload:
Name:

Press here to upload the file via direct proxy! -
-
- File to upload:
Name:

Press here to upload the file via proxy servlet! -
-
- File to upload:
Name:

Press here to upload the file directly! -
- - \ No newline at end of file diff --git a/spring-cloud-netflix-dependencies/pom.xml b/spring-cloud-netflix-dependencies/pom.xml deleted file mode 100644 index 55891682..00000000 --- a/spring-cloud-netflix-dependencies/pom.xml +++ /dev/null @@ -1,578 +0,0 @@ - - - 4.0.0 - - spring-cloud-dependencies-parent - org.springframework.cloud - 2.0.0.BUILD-SNAPSHOT - - - spring-cloud-netflix-dependencies - 2.0.0.BUILD-SNAPSHOT - pom - spring-cloud-netflix-dependencies - Spring Cloud Netflix Dependencies - - 0.7.5 - 1.8.6 - 9.5.1 - 1.5.12 - 2.2.4 - 0.10.1 - 1.3.1 - 1.2.0 - 1.2.1 - 1.0.0 - 1.19.1 - 1.4.9 - 3.8.1 - - - - - org.springframework.cloud - spring-cloud-netflix-eureka-client - ${project.version} - - - org.springframework.cloud - spring-cloud-netflix-archaius - ${project.version} - - - org.springframework.cloud - spring-cloud-starter-netflix-archaius - ${project.version} - - - org.springframework.cloud - spring-cloud-starter-netflix-eureka-client - ${project.version} - - - org.springframework.cloud - spring-cloud-starter-netflix-eureka-server - ${project.version} - - - org.springframework.cloud - spring-cloud-starter-openfeign - ${project.version} - - - org.springframework.cloud - spring-cloud-starter-netflix-hystrix - ${project.version} - - - org.springframework.cloud - spring-cloud-netflix-hystrix-contract - ${project.version} - - - org.springframework.cloud - spring-cloud-starter-netflix-hystrix-dashboard - ${project.version} - - - org.springframework.cloud - spring-cloud-starter-netflix-ribbon - ${project.version} - - - org.springframework.cloud - spring-cloud-starter-netflix-turbine - ${project.version} - - - org.springframework.cloud - spring-cloud-starter-netflix-turbine-stream - ${project.version} - - - org.springframework.cloud - spring-cloud-starter-netflix-zuul - ${project.version} - - - org.springframework.cloud - spring-cloud-netflix-core - ${project.version} - - - org.springframework.cloud - spring-cloud-netflix-eureka-server - ${project.version} - - - org.springframework.cloud - spring-cloud-netflix-hystrix-dashboard - ${project.version} - - - org.springframework.cloud - spring-cloud-netflix-hystrix-stream - ${project.version} - - - org.springframework.cloud - spring-cloud-netflix-sidecar - ${project.version} - - - org.springframework.cloud - spring-cloud-netflix-turbine - ${project.version} - - - org.springframework.cloud - spring-cloud-netflix-turbine-stream - ${project.version} - - - org.springframework.cloud - spring-cloud-netflix-zuul - ${project.version} - - - org.springframework.cloud - spring-cloud-netflix-ribbon - ${project.version} - - - com.netflix.netflix-commons - netflix-commons-util - 0.1.1 - - - com.netflix.archaius - archaius-core - ${archaius.version} - - - commons-logging - commons-logging - - - com.google.code.findbugs - annotations - - - - - - commons-configuration - commons-configuration - 1.8 - - - commons-logging - commons-logging - - - - - - com.sun.jersey - jersey-servlet - ${eureka-jersey.version} - - - com.sun.jersey - jersey-core - ${eureka-jersey.version} - - - com.sun.jersey - jersey-client - ${eureka-jersey.version} - - - com.sun.jersey - jersey-server - ${eureka-jersey.version} - - - com.sun.jersey.contribs - jersey-apache-client4 - ${eureka-jersey.version} - - - com.netflix.servo - servo-core - ${servo.version} - - - com.google.code.findbugs - annotations - - - - - com.netflix.eureka - eureka-client - ${eureka.version} - - - javax.servlet - servlet-api - - - commons-logging - commons-logging - - - com.google.code.findbugs - jsr305 - - - com.google.code.findbugs - annotations - - - - - com.netflix.eureka - eureka-core - ${eureka.version} - - - javax.servlet - servlet-api - - - commons-logging - commons-logging - - - log4j - log4j - - - com.netflix.blitz4j - blitz4j - - - com.google.code.findbugs - annotations - - - com.google.code.findbugs - jsr305 - - - jackson-dataformat-xml - com.fasterxml.jackson.dataformat - - - * - com.amazonaws - - - - - - com.thoughtworks.xstream - xstream - ${xstream.version} - - - io.github.openfeign - feign-core - ${feign.version} - - - io.github.openfeign - feign-slf4j - ${feign.version} - - - io.github.openfeign - feign-httpclient - ${feign.version} - - - io.github.openfeign - feign-hystrix - ${feign.version} - - - io.github.openfeign - feign-java8 - ${feign.version} - - - io.github.openfeign - feign-okhttp - ${feign.version} - - - io.github.openfeign - feign-gson - ${feign.version} - - - io.github.openfeign - feign-jackson-jaxb - ${feign.version} - - - io.github.openfeign - feign-jackson - ${feign.version} - - - io.github.openfeign - feign-java8 - ${feign.version} - - - io.github.openfeign - feign-jaxb - ${feign.version} - - - io.github.openfeign - feign-jaxrs - ${feign.version} - - - io.github.openfeign - feign-ribbon - ${feign.version} - - - io.github.openfeign - feign-sax - ${feign.version} - - - com.netflix.hystrix - hystrix-core - ${hystrix.version} - - - com.google.code.findbugs - annotations - - - - - com.netflix.hystrix - hystrix-serialization - ${hystrix.version} - - - com.google.code.findbugs - annotations - - - - - com.netflix.hystrix - hystrix-metrics-event-stream - ${hystrix.version} - - - javax.servlet - servlet-api - - - - - com.netflix.hystrix - hystrix-javanica - ${hystrix.version} - - - com.google.code.findbugs - jsr305 - - - com.google.code.findbugs - annotations - - - org.aspectj - aspectjrt - - - - - com.netflix.ribbon - ribbon - ${ribbon.version} - - - commons-logging - commons-logging - - - - - com.netflix.ribbon - ribbon-core - ${ribbon.version} - - - com.google.code.findbugs - annotations - - - - - com.netflix.ribbon - ribbon-httpclient - ${ribbon.version} - - - com.google.code.findbugs - annotations - - - - - com.netflix.ribbon - ribbon-eureka - ${ribbon.version} - - - com.google.code.findbugs - annotations - - - javax.servlet - servlet-api - - - - - com.netflix.ribbon - ribbon-loadbalancer - ${ribbon.version} - - - com.google.code.findbugs - annotations - - - - - io.reactivex - rxjava - ${rxjava.version} - - - io.reactivex - rxjava-reactive-streams - ${rxjava-reactive-streams.version} - - - com.netflix.zuul - zuul-core - ${zuul.version} - - - groovy-all - org.codehaus.groovy - - - mockito-all - org.mockito - - - - - com.squareup.okhttp3 - okhttp - ${okhttp3.version} - - - com.squareup.okhttp3 - logging-interceptor - ${okhttp3.version} - - - com.google.guava - guava - 18.0 - - - org.webjars - d3js - 3.4.11 - - - org.webjars - jquery - 2.1.1 - - - org.webjars - bootstrap - 3.2.0 - - - javax.inject - javax.inject - 1 - - - - - - spring - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/libs-snapshot-local - - true - - - false - - - - spring-milestones - Spring Milestones - https://repo.spring.io/libs-milestone-local - - false - - - - spring-releases - Spring Releases - https://repo.spring.io/release - - false - - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/libs-snapshot-local - - true - - - false - - - - spring-milestones - Spring Milestones - https://repo.spring.io/libs-milestone-local - - false - - - - - - diff --git a/spring-cloud-netflix-eureka-client/pom.xml b/spring-cloud-netflix-eureka-client/pom.xml deleted file mode 100644 index c6891838..00000000 --- a/spring-cloud-netflix-eureka-client/pom.xml +++ /dev/null @@ -1,135 +0,0 @@ - - - 4.0.0 - - org.springframework.cloud - spring-cloud-netflix - 2.0.0.BUILD-SNAPSHOT - .. - - spring-cloud-netflix-eureka-client - jar - Spring Cloud Netflix Eureka Client - Spring Cloud Netflix Eureka Client - - - false - ${basedir}/.. - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework.boot - spring-boot-starter-actuator - true - - - org.springframework.cloud - spring-cloud-netflix-core - - - org.springframework.cloud - spring-cloud-config-client - true - - - org.springframework.cloud - spring-cloud-config-server - true - - - com.netflix.eureka - eureka-client - true - - - javax.inject - javax.inject - true - - - com.netflix.eureka - eureka-core - true - - - - com.thoughtworks.xstream - xstream - true - - - net.java.dev.rome - rome - 1.0.0 - true - - - com.sun.jersey.contribs - jersey-apache-client4 - true - - - com.netflix.archaius - archaius-core - true - - - - commons-configuration - commons-configuration - true - - - - com.netflix.ribbon - ribbon - true - - - com.netflix.ribbon - ribbon-core - true - - - com.netflix.ribbon - ribbon-loadbalancer - true - - - com.netflix.ribbon - ribbon-eureka - true - - - com.netflix.ribbon - ribbon-httpclient - true - - - org.springframework.boot - spring-boot-starter-security - test - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.cloud - spring-cloud-test-support - test - - - org.springframework.retry - spring-retry - test - - - diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaClient.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaClient.java deleted file mode 100644 index d1c8ead7..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaClient.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -import java.lang.reflect.Field; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.client.discovery.event.HeartbeatEvent; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.http.HttpStatus; -import org.springframework.util.ReflectionUtils; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.appinfo.InstanceInfo.InstanceStatus; -import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs; -import com.netflix.discovery.DiscoveryClient; -import com.netflix.discovery.EurekaClientConfig; -import com.netflix.discovery.shared.transport.EurekaHttpClient; -import com.netflix.discovery.shared.transport.EurekaHttpResponse; - -/** - * Subclass of {@link DiscoveryClient} that sends a {@link HeartbeatEvent} when - * {@link CloudEurekaClient#onCacheRefreshed()} is called. - * @author Spencer Gibb - */ -public class CloudEurekaClient extends DiscoveryClient { - private static final Log log = LogFactory.getLog(CloudEurekaClient.class); - - private final AtomicLong cacheRefreshedCount = new AtomicLong(0); - - private ApplicationEventPublisher publisher; - private Field eurekaTransportField; - private ApplicationInfoManager applicationInfoManager; - private AtomicReference eurekaHttpClient = new AtomicReference<>(); - - public CloudEurekaClient(ApplicationInfoManager applicationInfoManager, - EurekaClientConfig config, ApplicationEventPublisher publisher) { - this(applicationInfoManager, config, null, publisher); - } - - public CloudEurekaClient(ApplicationInfoManager applicationInfoManager, - EurekaClientConfig config, - AbstractDiscoveryClientOptionalArgs args, - ApplicationEventPublisher publisher) { - super(applicationInfoManager, config, args); - this.applicationInfoManager = applicationInfoManager; - this.publisher = publisher; - this.eurekaTransportField = ReflectionUtils.findField(DiscoveryClient.class, "eurekaTransport"); - ReflectionUtils.makeAccessible(this.eurekaTransportField); - } - - public ApplicationInfoManager getApplicationInfoManager() { - return applicationInfoManager; - } - - public void cancelOverrideStatus(InstanceInfo info) { - getEurekaHttpClient().deleteStatusOverride(info.getAppName(), info.getId(), info); - } - - public InstanceInfo getInstanceInfo(String appname, String instanceId) { - EurekaHttpResponse response = getEurekaHttpClient().getInstance(appname, instanceId); - HttpStatus httpStatus = HttpStatus.valueOf(response.getStatusCode()); - if (httpStatus.is2xxSuccessful() && response.getEntity() != null) { - return response.getEntity(); - } - return null; - } - - EurekaHttpClient getEurekaHttpClient() { - if (this.eurekaHttpClient.get() == null) { - try { - Object eurekaTransport = this.eurekaTransportField.get(this); - Field registrationClientField = ReflectionUtils.findField(eurekaTransport.getClass(), "registrationClient"); - ReflectionUtils.makeAccessible(registrationClientField); - this.eurekaHttpClient.compareAndSet(null, (EurekaHttpClient) registrationClientField.get(eurekaTransport)); - } catch (IllegalAccessException e) { - log.error("error getting EurekaHttpClient", e); - } - } - return this.eurekaHttpClient.get(); - } - - public void setStatus(InstanceStatus newStatus, InstanceInfo info) { - getEurekaHttpClient().statusUpdate(info.getAppName(), info.getId(), newStatus, info); - } - - @Override - protected void onCacheRefreshed() { - super.onCacheRefreshed(); - - if (this.cacheRefreshedCount != null) { //might be called during construction and will be null - long newCount = this.cacheRefreshedCount.incrementAndGet(); - log.trace("onCacheRefreshed called with count: " + newCount); - this.publisher.publishEvent(new HeartbeatEvent(this, newCount)); - } - } -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaInstanceConfig.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaInstanceConfig.java deleted file mode 100644 index 6ea3e889..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaInstanceConfig.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -import com.netflix.appinfo.EurekaInstanceConfig; -import com.netflix.appinfo.InstanceInfo; - -/** - * @author Spencer Gibb - */ -public interface CloudEurekaInstanceConfig extends EurekaInstanceConfig { - void setNonSecurePort(int port); - void setSecurePort(int securePort); - InstanceInfo.InstanceStatus getInitialStatus(); -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaTransportConfig.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaTransportConfig.java deleted file mode 100644 index 5eb21163..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaTransportConfig.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -import com.netflix.discovery.shared.transport.EurekaTransportConfig; - -import java.util.Objects; - -/** - * @author Spencer Gibb - * @author Gregor Zurowski - */ -public class CloudEurekaTransportConfig implements EurekaTransportConfig { - - private int sessionedClientReconnectIntervalSeconds = 20 * 60; - - private double retryableClientQuarantineRefreshPercentage = 0.66; - - private int bootstrapResolverRefreshIntervalSeconds = 5 * 60; - - private int applicationsResolverDataStalenessThresholdSeconds = 5 * 60; - - private int asyncResolverRefreshIntervalMs = 5 * 60 * 1000; - - private int asyncResolverWarmUpTimeoutMs = 5000; - - private int asyncExecutorThreadPoolSize = 5; - - private String readClusterVip; - - private String writeClusterVip; - - private boolean bootstrapResolverForQuery = true; - - private String bootstrapResolverStrategy; - - private boolean applicationsResolverUseIp = false; - - @Override - public boolean useBootstrapResolverForQuery() { - return this.bootstrapResolverForQuery; - } - - @Override - public boolean applicationsResolverUseIp() { - return this.applicationsResolverUseIp; - } - - public int getSessionedClientReconnectIntervalSeconds() { - return sessionedClientReconnectIntervalSeconds; - } - - public void setSessionedClientReconnectIntervalSeconds( - int sessionedClientReconnectIntervalSeconds) { - this.sessionedClientReconnectIntervalSeconds = sessionedClientReconnectIntervalSeconds; - } - - public double getRetryableClientQuarantineRefreshPercentage() { - return retryableClientQuarantineRefreshPercentage; - } - - public void setRetryableClientQuarantineRefreshPercentage( - double retryableClientQuarantineRefreshPercentage) { - this.retryableClientQuarantineRefreshPercentage = retryableClientQuarantineRefreshPercentage; - } - - public int getBootstrapResolverRefreshIntervalSeconds() { - return bootstrapResolverRefreshIntervalSeconds; - } - - public void setBootstrapResolverRefreshIntervalSeconds( - int bootstrapResolverRefreshIntervalSeconds) { - this.bootstrapResolverRefreshIntervalSeconds = bootstrapResolverRefreshIntervalSeconds; - } - - public int getApplicationsResolverDataStalenessThresholdSeconds() { - return applicationsResolverDataStalenessThresholdSeconds; - } - - public void setApplicationsResolverDataStalenessThresholdSeconds( - int applicationsResolverDataStalenessThresholdSeconds) { - this.applicationsResolverDataStalenessThresholdSeconds = applicationsResolverDataStalenessThresholdSeconds; - } - - public int getAsyncResolverRefreshIntervalMs() { - return asyncResolverRefreshIntervalMs; - } - - public void setAsyncResolverRefreshIntervalMs(int asyncResolverRefreshIntervalMs) { - this.asyncResolverRefreshIntervalMs = asyncResolverRefreshIntervalMs; - } - - public int getAsyncResolverWarmUpTimeoutMs() { - return asyncResolverWarmUpTimeoutMs; - } - - public void setAsyncResolverWarmUpTimeoutMs(int asyncResolverWarmUpTimeoutMs) { - this.asyncResolverWarmUpTimeoutMs = asyncResolverWarmUpTimeoutMs; - } - - public int getAsyncExecutorThreadPoolSize() { - return asyncExecutorThreadPoolSize; - } - - public void setAsyncExecutorThreadPoolSize(int asyncExecutorThreadPoolSize) { - this.asyncExecutorThreadPoolSize = asyncExecutorThreadPoolSize; - } - - public String getReadClusterVip() { - return readClusterVip; - } - - public void setReadClusterVip(String readClusterVip) { - this.readClusterVip = readClusterVip; - } - - public String getWriteClusterVip() { - return writeClusterVip; - } - - public void setWriteClusterVip(String writeClusterVip) { - this.writeClusterVip = writeClusterVip; - } - - public boolean isBootstrapResolverForQuery() { - return bootstrapResolverForQuery; - } - - public void setBootstrapResolverForQuery(boolean bootstrapResolverForQuery) { - this.bootstrapResolverForQuery = bootstrapResolverForQuery; - } - - public String getBootstrapResolverStrategy() { - return bootstrapResolverStrategy; - } - - public void setBootstrapResolverStrategy(String bootstrapResolverStrategy) { - this.bootstrapResolverStrategy = bootstrapResolverStrategy; - } - - public boolean isApplicationsResolverUseIp() { - return applicationsResolverUseIp; - } - - public void setApplicationsResolverUseIp(boolean applicationsResolverUseIp) { - this.applicationsResolverUseIp = applicationsResolverUseIp; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - CloudEurekaTransportConfig that = (CloudEurekaTransportConfig) o; - return sessionedClientReconnectIntervalSeconds == that.sessionedClientReconnectIntervalSeconds && - Double.compare(retryableClientQuarantineRefreshPercentage, that.retryableClientQuarantineRefreshPercentage) == 0 && - bootstrapResolverRefreshIntervalSeconds == that.bootstrapResolverRefreshIntervalSeconds && - applicationsResolverDataStalenessThresholdSeconds == that.applicationsResolverDataStalenessThresholdSeconds && - asyncResolverRefreshIntervalMs == that.asyncResolverRefreshIntervalMs && - asyncResolverWarmUpTimeoutMs == that.asyncResolverWarmUpTimeoutMs && - asyncExecutorThreadPoolSize == that.asyncExecutorThreadPoolSize && - Objects.equals(readClusterVip, that.readClusterVip) && - Objects.equals(writeClusterVip, that.writeClusterVip) && - bootstrapResolverForQuery == that.bootstrapResolverForQuery && - Objects.equals(bootstrapResolverStrategy, that.bootstrapResolverStrategy) && - applicationsResolverUseIp == that.applicationsResolverUseIp; - } - - @Override - public int hashCode() { - return Objects.hash(sessionedClientReconnectIntervalSeconds, - retryableClientQuarantineRefreshPercentage, - bootstrapResolverRefreshIntervalSeconds, - applicationsResolverDataStalenessThresholdSeconds, - asyncResolverRefreshIntervalMs, asyncResolverWarmUpTimeoutMs, - asyncExecutorThreadPoolSize, readClusterVip, writeClusterVip, - bootstrapResolverForQuery, bootstrapResolverStrategy, - applicationsResolverUseIp); - } - - @Override - public String toString() { - return new StringBuilder("CloudEurekaTransportConfig{") - .append("sessionedClientReconnectIntervalSeconds=").append(sessionedClientReconnectIntervalSeconds).append(", ") - .append("retryableClientQuarantineRefreshPercentage=").append(retryableClientQuarantineRefreshPercentage).append(", ") - .append("bootstrapResolverRefreshIntervalSeconds=").append(bootstrapResolverRefreshIntervalSeconds).append(", ") - .append("applicationsResolverDataStalenessThresholdSeconds=").append(applicationsResolverDataStalenessThresholdSeconds).append(", ") - .append("asyncResolverRefreshIntervalMs=").append(asyncResolverRefreshIntervalMs).append(", ") - .append("asyncResolverWarmUpTimeoutMs=").append(asyncResolverWarmUpTimeoutMs).append(", ") - .append("asyncExecutorThreadPoolSize=").append(asyncExecutorThreadPoolSize).append(", ") - .append("readClusterVip='").append(readClusterVip).append("', ") - .append("writeClusterVip='").append(writeClusterVip).append("', ") - .append("bootstrapResolverForQuery=").append(bootstrapResolverForQuery).append(", ") - .append("bootstrapResolverStrategy='").append(bootstrapResolverStrategy).append("', ") - .append("applicationsResolverUseIp=").append(applicationsResolverUseIp).append(", ").append("}") - .toString(); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EnableEurekaClient.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EnableEurekaClient.java deleted file mode 100644 index 0af19d53..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EnableEurekaClient.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Convenience annotation for clients to enable Eureka discovery configuration - * (specifically). Use this (optionally) in case you want discovery and know for sure that - * it is Eureka you want. All it does is turn on discovery and let the autoconfiguration - * find the eureka classes if they are available (i.e. you need Eureka on the classpath as - * well). - * - * @author Dave Syer - * @author Spencer Gibb - */ -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Inherited -public @interface EnableEurekaClient { - -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfiguration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfiguration.java deleted file mode 100644 index afd2b0d0..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfiguration.java +++ /dev/null @@ -1,326 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator; -import org.springframework.boot.actuate.health.Health; -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.condition.AnyNestedCondition; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.condition.SearchStrategy; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; -import org.springframework.cloud.client.CommonsClientAutoConfiguration; -import org.springframework.cloud.client.actuator.HasFeatures; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.client.discovery.noop.NoopDiscoveryClientAutoConfiguration; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; -import org.springframework.cloud.client.serviceregistry.ServiceRegistryAutoConfiguration; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.context.scope.refresh.RefreshScope; -import org.springframework.cloud.netflix.eureka.config.DiscoveryClientOptionalArgsConfiguration; -import org.springframework.cloud.netflix.eureka.metadata.DefaultManagementMetadataProvider; -import org.springframework.cloud.netflix.eureka.metadata.ManagementMetadata; -import org.springframework.cloud.netflix.eureka.metadata.ManagementMetadataProvider; -import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration; -import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration; -import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Conditional; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.context.annotation.Lazy; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.util.StringUtils; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.EurekaInstanceConfig; -import com.netflix.appinfo.HealthCheckHandler; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs; -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.EurekaClientConfig; - -import static org.springframework.cloud.commons.util.IdUtils.getDefaultInstanceId; - -/** - * @author Dave Syer - * @author Spencer Gibb - * @author Jon Schneider - * @author Matt Jenkins - * @author Ryan Baxter - * @author Daniel Lavoie - */ -@Configuration -@EnableConfigurationProperties -@ConditionalOnClass(EurekaClientConfig.class) -@Import(DiscoveryClientOptionalArgsConfiguration.class) -@ConditionalOnBean(EurekaDiscoveryClientConfiguration.Marker.class) -@ConditionalOnProperty(value = "eureka.client.enabled", matchIfMissing = true) -@AutoConfigureBefore({ NoopDiscoveryClientAutoConfiguration.class, - CommonsClientAutoConfiguration.class, ServiceRegistryAutoConfiguration.class }) -@AutoConfigureAfter(name = {"org.springframework.cloud.autoconfigure.RefreshAutoConfiguration", - "org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration", - "org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration"}) -public class EurekaClientAutoConfiguration { - - private static final Log log = LogFactory.getLog(EurekaClientAutoConfiguration.class); - - private ConfigurableEnvironment env; - - public EurekaClientAutoConfiguration(ConfigurableEnvironment env) { - this.env = env; - } - - @Bean - public HasFeatures eurekaFeature() { - return HasFeatures.namedFeature("Eureka Client", EurekaClient.class); - } - - @Bean - @ConditionalOnMissingBean(value = EurekaClientConfig.class, search = SearchStrategy.CURRENT) - public EurekaClientConfigBean eurekaClientConfigBean() { - EurekaClientConfigBean client = new EurekaClientConfigBean(); - if ("bootstrap".equals(this.env.getProperty("spring.config.name"))) { - // We don't register during bootstrap by default, but there will be another - // chance later. - client.setRegisterWithEureka(false); - } - return client; - } - - @Bean - @ConditionalOnMissingBean - public ManagementMetadataProvider serviceManagementMetadataProvider() { - return new DefaultManagementMetadataProvider(); - } - - private String getProperty(String property) { - return this.env.containsProperty(property) ? this.env.getProperty(property) : ""; - } - - @Bean - @ConditionalOnMissingBean(value = EurekaInstanceConfig.class, search = SearchStrategy.CURRENT) - public EurekaInstanceConfigBean eurekaInstanceConfigBean(InetUtils inetUtils, - ManagementMetadataProvider managementMetadataProvider) { - String hostname = getProperty("eureka.instance.hostname"); - boolean preferIpAddress = Boolean.parseBoolean(getProperty("eureka.instance.prefer-ip-address")); - String ipAddress = getProperty("eureka.instance.ipAddress"); - boolean isSecurePortEnabled = Boolean.parseBoolean(getProperty("eureka.instance.secure-port-enabled")); - - String serverContextPath = env.getProperty("server.context-path", "/"); - int serverPort = Integer.valueOf(env.getProperty("server.port", env.getProperty("port", "8080"))); - - Integer managementPort = env.getProperty("management.server.port", Integer.class);// nullable. should be wrapped into optional - String managementContextPath = env.getProperty("management.server.context-path");// nullable. should be wrapped into optional - Integer jmxPort = env.getProperty("com.sun.management.jmxremote.port", Integer.class);//nullable - EurekaInstanceConfigBean instance = new EurekaInstanceConfigBean(inetUtils); - - instance.setNonSecurePort(serverPort); - instance.setInstanceId(getDefaultInstanceId(env)); - instance.setPreferIpAddress(preferIpAddress); - if (StringUtils.hasText(ipAddress)) { - instance.setIpAddress(ipAddress); - } - - if(isSecurePortEnabled) { - instance.setSecurePort(serverPort); - } - - if (StringUtils.hasText(hostname)) { - instance.setHostname(hostname); - } - String statusPageUrlPath = getProperty("eureka.instance.status-page-url-path"); - String healthCheckUrlPath = getProperty("eureka.instance.health-check-url-path"); - - if (StringUtils.hasText(statusPageUrlPath)) { - instance.setStatusPageUrlPath(statusPageUrlPath); - } - if (StringUtils.hasText(healthCheckUrlPath)) { - instance.setHealthCheckUrlPath(healthCheckUrlPath); - } - - ManagementMetadata metadata = managementMetadataProvider.get(instance, serverPort, - serverContextPath, managementContextPath, managementPort); - - if(metadata != null) { - instance.setStatusPageUrl(metadata.getStatusPageUrl()); - instance.setHealthCheckUrl(metadata.getHealthCheckUrl()); - Map metadataMap = instance.getMetadataMap(); - if (metadataMap.get("management.port") == null) { - metadataMap.put("management.port", String.valueOf(metadata.getManagementPort())); - } - } - - setupJmxPort(instance, jmxPort); - return instance; - } - - private void setupJmxPort(EurekaInstanceConfigBean instance, Integer jmxPort) { - Map metadataMap = instance.getMetadataMap(); - if (metadataMap.get("jmx.port") == null && jmxPort != null) { - metadataMap.put("jmx.port", String.valueOf(jmxPort)); - } - } - - @Bean - public DiscoveryClient discoveryClient(EurekaInstanceConfig config, EurekaClient client) { - return new EurekaDiscoveryClient(config, client); - } - - @Bean - public EurekaServiceRegistry eurekaServiceRegistry() { - return new EurekaServiceRegistry(); - } - - @Bean - @ConditionalOnBean(AutoServiceRegistrationProperties.class) - @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) - public EurekaRegistration eurekaRegistration(EurekaClient eurekaClient, CloudEurekaInstanceConfig instanceConfig, ApplicationInfoManager applicationInfoManager, ObjectProvider healthCheckHandler) { - return EurekaRegistration.builder(instanceConfig) - .with(applicationInfoManager) - .with(eurekaClient) - .with(healthCheckHandler) - .build(); - } - - @Bean - @ConditionalOnBean(AutoServiceRegistrationProperties.class) - @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) - public EurekaAutoServiceRegistration eurekaAutoServiceRegistration(ApplicationContext context, EurekaServiceRegistry registry, EurekaRegistration registration) { - return new EurekaAutoServiceRegistration(context, registry, registration); - } - - @Configuration - @ConditionalOnMissingRefreshScope - protected static class EurekaClientConfiguration { - - @Autowired - private ApplicationContext context; - - @Autowired - private AbstractDiscoveryClientOptionalArgs optionalArgs; - - @Bean(destroyMethod = "shutdown") - @ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT) - public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config) { - return new CloudEurekaClient(manager, config, this.optionalArgs, - this.context); - } - - @Bean - @ConditionalOnMissingBean(value = ApplicationInfoManager.class, search = SearchStrategy.CURRENT) - public ApplicationInfoManager eurekaApplicationInfoManager( - EurekaInstanceConfig config) { - InstanceInfo instanceInfo = new InstanceInfoFactory().create(config); - return new ApplicationInfoManager(config, instanceInfo); - } - } - - @Configuration - @ConditionalOnRefreshScope - protected static class RefreshableEurekaClientConfiguration { - - @Autowired - private ApplicationContext context; - - @Autowired - private AbstractDiscoveryClientOptionalArgs optionalArgs; - - @Bean(destroyMethod = "shutdown") - @ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT) - @org.springframework.cloud.context.config.annotation.RefreshScope - @Lazy - public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config, EurekaInstanceConfig instance) { - manager.getInfo(); // force initialization - return new CloudEurekaClient(manager, config, this.optionalArgs, - this.context); - } - - @Bean - @ConditionalOnMissingBean(value = ApplicationInfoManager.class, search = SearchStrategy.CURRENT) - @org.springframework.cloud.context.config.annotation.RefreshScope - @Lazy - public ApplicationInfoManager eurekaApplicationInfoManager(EurekaInstanceConfig config) { - InstanceInfo instanceInfo = new InstanceInfoFactory().create(config); - return new ApplicationInfoManager(config, instanceInfo); - } - - } - - @Target({ ElementType.TYPE, ElementType.METHOD }) - @Retention(RetentionPolicy.RUNTIME) - @Documented - @Conditional(OnMissingRefreshScopeCondition.class) - @interface ConditionalOnMissingRefreshScope { - - } - - @Target({ ElementType.TYPE, ElementType.METHOD }) - @Retention(RetentionPolicy.RUNTIME) - @Documented - @ConditionalOnClass(RefreshScope.class) - @ConditionalOnBean(RefreshAutoConfiguration.class) - @interface ConditionalOnRefreshScope { - - } - - private static class OnMissingRefreshScopeCondition extends AnyNestedCondition { - - public OnMissingRefreshScopeCondition() { - super(ConfigurationPhase.REGISTER_BEAN); - } - - @ConditionalOnMissingClass("org.springframework.cloud.context.scope.refresh.RefreshScope") - static class MissingClass { - } - - @ConditionalOnMissingBean(RefreshAutoConfiguration.class) - static class MissingScope { - } - - } - - @Configuration - @ConditionalOnClass(Health.class) - protected static class EurekaHealthIndicatorConfiguration { - @Bean - @ConditionalOnMissingBean - @ConditionalOnEnabledHealthIndicator("eureka") - public EurekaHealthIndicator eurekaHealthIndicator(EurekaClient eurekaClient, - EurekaInstanceConfig instanceConfig, EurekaClientConfig clientConfig) { - return new EurekaHealthIndicator(eurekaClient, instanceConfig, clientConfig); - } - } -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBean.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBean.java deleted file mode 100644 index 323b607f..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBean.java +++ /dev/null @@ -1,1043 +0,0 @@ -/* -* Copyright 2013-2014 the original author or authors. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -package org.springframework.cloud.netflix.eureka; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.NestedConfigurationProperty; -import org.springframework.core.env.PropertyResolver; -import org.springframework.util.StringUtils; - -import com.netflix.appinfo.EurekaAccept; -import com.netflix.discovery.EurekaClientConfig; -import com.netflix.discovery.shared.transport.EurekaTransportConfig; - -import static org.springframework.cloud.netflix.eureka.EurekaConstants.DEFAULT_PREFIX; - -/** - * @author Dave Syer - * @author Gregor Zurowski - */ -@ConfigurationProperties(EurekaClientConfigBean.PREFIX) -public class EurekaClientConfigBean implements EurekaClientConfig { - - public static final String PREFIX = "eureka.client"; - - public static final String DEFAULT_URL = "http://localhost:8761" + DEFAULT_PREFIX - + "/"; - - public static final String DEFAULT_ZONE = "defaultZone"; - - private static final int MINUTES = 60; - - @Autowired(required = false) - PropertyResolver propertyResolver; - - /** - * Flag to indicate that the Eureka client is enabled. - */ - private boolean enabled = true; - - @NestedConfigurationProperty - private EurekaTransportConfig transport = new CloudEurekaTransportConfig(); - - /** - * Indicates how often(in seconds) to fetch the registry information from the eureka - * server. - */ - private int registryFetchIntervalSeconds = 30; - - /** - * Indicates how often(in seconds) to replicate instance changes to be replicated to - * the eureka server. - */ - private int instanceInfoReplicationIntervalSeconds = 30; - - /** - * Indicates how long initially (in seconds) to replicate instance info to the eureka - * server - */ - private int initialInstanceInfoReplicationIntervalSeconds = 40; - - /** - * Indicates how often(in seconds) to poll for changes to eureka server information. - * Eureka servers could be added or removed and this setting controls how soon the - * eureka clients should know about it. - */ - private int eurekaServiceUrlPollIntervalSeconds = 5 * MINUTES; - - /** - * Gets the proxy port to eureka server if any. - */ - private String proxyPort; - - /** - * Gets the proxy host to eureka server if any. - */ - private String proxyHost; - - /** - * Gets the proxy user name if any. - */ - private String proxyUserName; - - /** - * Gets the proxy password if any. - */ - private String proxyPassword; - - /** - * Indicates how long to wait (in seconds) before a read from eureka server needs to - * timeout. - */ - private int eurekaServerReadTimeoutSeconds = 8; - - /** - * Indicates how long to wait (in seconds) before a connection to eureka server needs - * to timeout. Note that the connections in the client are pooled by - * org.apache.http.client.HttpClient and this setting affects the actual connection - * creation and also the wait time to get the connection from the pool. - */ - private int eurekaServerConnectTimeoutSeconds = 5; - - /** - * Gets the name of the implementation which implements BackupRegistry to fetch the - * registry information as a fall back option for only the first time when the eureka - * client starts. - * - * This may be needed for applications which needs additional resiliency for registry - * information without which it cannot operate. - */ - private String backupRegistryImpl; - - /** - * Gets the total number of connections that is allowed from eureka client to all - * eureka servers. - */ - private int eurekaServerTotalConnections = 200; - - /** - * Gets the total number of connections that is allowed from eureka client to a eureka - * server host. - */ - private int eurekaServerTotalConnectionsPerHost = 50; - - /** - * Gets the URL context to be used to construct the service url to contact eureka - * server when the list of eureka servers come from the DNS. This information is not - * required if the contract returns the service urls from eurekaServerServiceUrls. - * - * The DNS mechanism is used when useDnsForFetchingServiceUrls is set to true and the - * eureka client expects the DNS to configured a certain way so that it can fetch - * changing eureka servers dynamically. The changes are effective at runtime. - */ - private String eurekaServerURLContext; - - /** - * Gets the port to be used to construct the service url to contact eureka server when - * the list of eureka servers come from the DNS.This information is not required if - * the contract returns the service urls eurekaServerServiceUrls(String). - * - * The DNS mechanism is used when useDnsForFetchingServiceUrls is set to true and the - * eureka client expects the DNS to configured a certain way so that it can fetch - * changing eureka servers dynamically. - * - * The changes are effective at runtime. - */ - private String eurekaServerPort; - - /** - * Gets the DNS name to be queried to get the list of eureka servers.This information - * is not required if the contract returns the service urls by implementing - * serviceUrls. - * - * The DNS mechanism is used when useDnsForFetchingServiceUrls is set to true and the - * eureka client expects the DNS to configured a certain way so that it can fetch - * changing eureka servers dynamically. - * - * The changes are effective at runtime. - */ - private String eurekaServerDNSName; - - /** - * Gets the region (used in AWS datacenters) where this instance resides. - */ - private String region = "us-east-1"; - - /** - * Indicates how much time (in seconds) that the HTTP connections to eureka server can - * stay idle before it can be closed. - * - * In the AWS environment, it is recommended that the values is 30 seconds or less, - * since the firewall cleans up the connection information after a few mins leaving - * the connection hanging in limbo - */ - private int eurekaConnectionIdleTimeoutSeconds = 30; - - /** - * Indicates whether the client is only interested in the registry information for a - * single VIP. - */ - private String registryRefreshSingleVipAddress; - - /** - * The thread pool size for the heartbeatExecutor to initialise with - */ - private int heartbeatExecutorThreadPoolSize = 2; - - /** - * Heartbeat executor exponential back off related property. It is a maximum - * multiplier value for retry delay, in case where a sequence of timeouts occurred. - */ - private int heartbeatExecutorExponentialBackOffBound = 10; - - /** - * The thread pool size for the cacheRefreshExecutor to initialise with - */ - private int cacheRefreshExecutorThreadPoolSize = 2; - - /** - * Cache refresh executor exponential back off related property. It is a maximum - * multiplier value for retry delay, in case where a sequence of timeouts occurred. - */ - private int cacheRefreshExecutorExponentialBackOffBound = 10; - - /** - * Map of availability zone to list of fully qualified URLs to communicate with eureka - * server. Each value can be a single URL or a comma separated list of alternative - * locations. - * - * Typically the eureka server URLs carry protocol,host,port,context and version - * information if any. Example: - * http://ec2-256-156-243-129.compute-1.amazonaws.com:7001/eureka/ - * - * The changes are effective at runtime at the next service url refresh cycle as - * specified by eurekaServiceUrlPollIntervalSeconds. - */ - private Map serviceUrl = new HashMap<>(); - - { - this.serviceUrl.put(DEFAULT_ZONE, DEFAULT_URL); - } - - /** - * Indicates whether the content fetched from eureka server has to be compressed - * whenever it is supported by the server. The registry information from the eureka - * server is compressed for optimum network traffic. - */ - private boolean gZipContent = true; - - /** - * Indicates whether the eureka client should use the DNS mechanism to fetch a list of - * eureka servers to talk to. When the DNS name is updated to have additional servers, - * that information is used immediately after the eureka client polls for that - * information as specified in eurekaServiceUrlPollIntervalSeconds. - * - * Alternatively, the service urls can be returned serviceUrls, but the users should - * implement their own mechanism to return the updated list in case of changes. - * - * The changes are effective at runtime. - */ - private boolean useDnsForFetchingServiceUrls = false; - - /** - * Indicates whether or not this instance should register its information with eureka - * server for discovery by others. - * - * In some cases, you do not want your instances to be discovered whereas you just - * want do discover other instances. - */ - private boolean registerWithEureka = true; - - /** - * Indicates whether or not this instance should try to use the eureka server in the - * same zone for latency and/or other reason. - * - * Ideally eureka clients are configured to talk to servers in the same zone - * - * The changes are effective at runtime at the next registry fetch cycle as specified - * by registryFetchIntervalSeconds - */ - private boolean preferSameZoneEureka = true; - - /** - * Indicates whether to log differences between the eureka server and the eureka - * client in terms of registry information. - * - * Eureka client tries to retrieve only delta changes from eureka server to minimize - * network traffic. After receiving the deltas, eureka client reconciles the - * information from the server to verify it has not missed out some information. - * Reconciliation failures could happen when the client has had network issues - * communicating to server.If the reconciliation fails, eureka client gets the full - * registry information. - * - * While getting the full registry information, the eureka client can log the - * differences between the client and the server and this setting controls that. - * - * The changes are effective at runtime at the next registry fetch cycle as specified - * by registryFetchIntervalSecondsr - */ - private boolean logDeltaDiff; - - /** - * Indicates whether the eureka client should disable fetching of delta and should - * rather resort to getting the full registry information. - * - * Note that the delta fetches can reduce the traffic tremendously, because the rate - * of change with the eureka server is normally much lower than the rate of fetches. - * - * The changes are effective at runtime at the next registry fetch cycle as specified - * by registryFetchIntervalSeconds - */ - private boolean disableDelta; - - /** - * Comma separated list of regions for which the eureka registry information will be - * fetched. It is mandatory to define the availability zones for each of these regions - * as returned by availabilityZones. Failing to do so, will result in failure of - * discovery client startup. - * - */ - private String fetchRemoteRegionsRegistry; - - /** - * Gets the list of availability zones (used in AWS data centers) for the region in - * which this instance resides. - * - * The changes are effective at runtime at the next registry fetch cycle as specified - * by registryFetchIntervalSeconds. - */ - private Map availabilityZones = new HashMap<>(); - - /** - * Indicates whether to get the applications after filtering the applications for - * instances with only InstanceStatus UP states. - */ - private boolean filterOnlyUpInstances = true; - - /** - * Indicates whether this client should fetch eureka registry information from eureka - * server. - */ - private boolean fetchRegistry = true; - - /** - * Get a replacement string for Dollar sign $ during - * serializing/deserializing information in eureka server. - */ - private String dollarReplacement = "_-"; - - /** - * Get a replacement string for underscore sign _ during - * serializing/deserializing information in eureka server. - */ - private String escapeCharReplacement = "__"; - - /** - * Indicates whether server can redirect a client request to a backup server/cluster. - * If set to false, the server will handle the request directly, If set to true, it - * may send HTTP redirect to the client, with a new server location. - */ - private boolean allowRedirects = false; - - /** - * If set to true, local status updates via ApplicationInfoManager will trigger - * on-demand (but rate limited) register/updates to remote eureka servers - */ - private boolean onDemandUpdateStatusChange = true; - - /** - * This is a transient config and once the latest codecs are stable, can be removed - * (as there will only be one) - */ - private String encoderName; - - /** - * This is a transient config and once the latest codecs are stable, can be removed - * (as there will only be one) - */ - private String decoderName; - - /** - * EurekaAccept name for client data accept - */ - private String clientDataAccept = EurekaAccept.full.name(); - - /** - * Indicates whether the client should explicitly unregister itself from the remote server - * on client shutdown. - */ - private boolean shouldUnregisterOnShutdown = true; - - /** - * Indicates whether the client should enforce registration during initialization. Defaults to false. - */ - private boolean shouldEnforceRegistrationAtInit = false; - - @Override - public boolean shouldGZipContent() { - return this.gZipContent; - } - - @Override - public boolean shouldUseDnsForFetchingServiceUrls() { - return this.useDnsForFetchingServiceUrls; - } - - @Override - public boolean shouldRegisterWithEureka() { - return this.registerWithEureka; - } - - @Override - public boolean shouldPreferSameZoneEureka() { - return this.preferSameZoneEureka; - } - - @Override - public boolean shouldLogDeltaDiff() { - return this.logDeltaDiff; - } - - @Override - public boolean shouldDisableDelta() { - return this.disableDelta; - } - - @Override - public boolean shouldUnregisterOnShutdown() { - return this.shouldUnregisterOnShutdown; - } - - @Override - public boolean shouldEnforceRegistrationAtInit() { - return this.shouldEnforceRegistrationAtInit; - } - - @Override - public String fetchRegistryForRemoteRegions() { - return this.fetchRemoteRegionsRegistry; - } - - @Override - public String[] getAvailabilityZones(String region) { - String value = this.availabilityZones.get(region); - if (value == null) { - value = DEFAULT_ZONE; - } - return value.split(","); - } - - @Override - public List getEurekaServerServiceUrls(String myZone) { - String serviceUrls = this.serviceUrl.get(myZone); - if (serviceUrls == null || serviceUrls.isEmpty()) { - serviceUrls = this.serviceUrl.get(DEFAULT_ZONE); - } - if (!StringUtils.isEmpty(serviceUrls)) { - final String[] serviceUrlsSplit = StringUtils.commaDelimitedListToStringArray(serviceUrls); - List eurekaServiceUrls = new ArrayList<>(serviceUrlsSplit.length); - for (String eurekaServiceUrl : serviceUrlsSplit) { - if (!endsWithSlash(eurekaServiceUrl)) { - eurekaServiceUrl += "/"; - } - eurekaServiceUrls.add(eurekaServiceUrl); - } - return eurekaServiceUrls; - } - - return new ArrayList<>(); - } - - private boolean endsWithSlash(String url) { - return url.endsWith("/"); - } - - @Override - public boolean shouldFilterOnlyUpInstances() { - return this.filterOnlyUpInstances; - } - - @Override - public boolean shouldFetchRegistry() { - return this.fetchRegistry; - } - - @Override - public boolean allowRedirects() { - return this.allowRedirects; - } - - @Override - public boolean shouldOnDemandUpdateStatusChange() { - return this.onDemandUpdateStatusChange; - } - - @Override - public String getExperimental(String name) { - if (this.propertyResolver != null) { - return this.propertyResolver.getProperty(PREFIX + ".experimental." + name, - String.class, null); - } - return null; - } - - @Override - public EurekaTransportConfig getTransportConfig() { - return getTransport(); - } - - public PropertyResolver getPropertyResolver() { - return propertyResolver; - } - - public void setPropertyResolver(PropertyResolver propertyResolver) { - this.propertyResolver = propertyResolver; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public EurekaTransportConfig getTransport() { - return transport; - } - - public void setTransport(EurekaTransportConfig transport) { - this.transport = transport; - } - - @Override - public int getRegistryFetchIntervalSeconds() { - return registryFetchIntervalSeconds; - } - - public void setRegistryFetchIntervalSeconds(int registryFetchIntervalSeconds) { - this.registryFetchIntervalSeconds = registryFetchIntervalSeconds; - } - - @Override - public int getInstanceInfoReplicationIntervalSeconds() { - return instanceInfoReplicationIntervalSeconds; - } - - public void setInstanceInfoReplicationIntervalSeconds( - int instanceInfoReplicationIntervalSeconds) { - this.instanceInfoReplicationIntervalSeconds = instanceInfoReplicationIntervalSeconds; - } - - @Override - public int getInitialInstanceInfoReplicationIntervalSeconds() { - return initialInstanceInfoReplicationIntervalSeconds; - } - - public void setInitialInstanceInfoReplicationIntervalSeconds( - int initialInstanceInfoReplicationIntervalSeconds) { - this.initialInstanceInfoReplicationIntervalSeconds = initialInstanceInfoReplicationIntervalSeconds; - } - - @Override - public int getEurekaServiceUrlPollIntervalSeconds() { - return eurekaServiceUrlPollIntervalSeconds; - } - - public void setEurekaServiceUrlPollIntervalSeconds( - int eurekaServiceUrlPollIntervalSeconds) { - this.eurekaServiceUrlPollIntervalSeconds = eurekaServiceUrlPollIntervalSeconds; - } - - @Override - public String getProxyPort() { - return proxyPort; - } - - public void setProxyPort(String proxyPort) { - this.proxyPort = proxyPort; - } - - @Override - public String getProxyHost() { - return proxyHost; - } - - public void setProxyHost(String proxyHost) { - this.proxyHost = proxyHost; - } - - @Override - public String getProxyUserName() { - return proxyUserName; - } - - public void setProxyUserName(String proxyUserName) { - this.proxyUserName = proxyUserName; - } - - @Override - public String getProxyPassword() { - return proxyPassword; - } - - public void setProxyPassword(String proxyPassword) { - this.proxyPassword = proxyPassword; - } - - @Override - public int getEurekaServerReadTimeoutSeconds() { - return eurekaServerReadTimeoutSeconds; - } - - public void setEurekaServerReadTimeoutSeconds(int eurekaServerReadTimeoutSeconds) { - this.eurekaServerReadTimeoutSeconds = eurekaServerReadTimeoutSeconds; - } - - @Override - public int getEurekaServerConnectTimeoutSeconds() { - return eurekaServerConnectTimeoutSeconds; - } - - public void setEurekaServerConnectTimeoutSeconds( - int eurekaServerConnectTimeoutSeconds) { - this.eurekaServerConnectTimeoutSeconds = eurekaServerConnectTimeoutSeconds; - } - - @Override - public String getBackupRegistryImpl() { - return backupRegistryImpl; - } - - public void setBackupRegistryImpl(String backupRegistryImpl) { - this.backupRegistryImpl = backupRegistryImpl; - } - - @Override - public int getEurekaServerTotalConnections() { - return eurekaServerTotalConnections; - } - - public void setEurekaServerTotalConnections(int eurekaServerTotalConnections) { - this.eurekaServerTotalConnections = eurekaServerTotalConnections; - } - - @Override - public int getEurekaServerTotalConnectionsPerHost() { - return eurekaServerTotalConnectionsPerHost; - } - - public void setEurekaServerTotalConnectionsPerHost( - int eurekaServerTotalConnectionsPerHost) { - this.eurekaServerTotalConnectionsPerHost = eurekaServerTotalConnectionsPerHost; - } - - @Override - public String getEurekaServerURLContext() { - return eurekaServerURLContext; - } - - public void setEurekaServerURLContext(String eurekaServerURLContext) { - this.eurekaServerURLContext = eurekaServerURLContext; - } - - @Override - public String getEurekaServerPort() { - return eurekaServerPort; - } - - public void setEurekaServerPort(String eurekaServerPort) { - this.eurekaServerPort = eurekaServerPort; - } - - @Override - public String getEurekaServerDNSName() { - return eurekaServerDNSName; - } - - public void setEurekaServerDNSName(String eurekaServerDNSName) { - this.eurekaServerDNSName = eurekaServerDNSName; - } - - @Override - public String getRegion() { - return region; - } - - public void setRegion(String region) { - this.region = region; - } - - @Override - public int getEurekaConnectionIdleTimeoutSeconds() { - return eurekaConnectionIdleTimeoutSeconds; - } - - public void setEurekaConnectionIdleTimeoutSeconds( - int eurekaConnectionIdleTimeoutSeconds) { - this.eurekaConnectionIdleTimeoutSeconds = eurekaConnectionIdleTimeoutSeconds; - } - - @Override - public String getRegistryRefreshSingleVipAddress() { - return registryRefreshSingleVipAddress; - } - - public void setRegistryRefreshSingleVipAddress( - String registryRefreshSingleVipAddress) { - this.registryRefreshSingleVipAddress = registryRefreshSingleVipAddress; - } - - @Override - public int getHeartbeatExecutorThreadPoolSize() { - return heartbeatExecutorThreadPoolSize; - } - - public void setHeartbeatExecutorThreadPoolSize(int heartbeatExecutorThreadPoolSize) { - this.heartbeatExecutorThreadPoolSize = heartbeatExecutorThreadPoolSize; - } - - @Override - public int getHeartbeatExecutorExponentialBackOffBound() { - return heartbeatExecutorExponentialBackOffBound; - } - - public void setHeartbeatExecutorExponentialBackOffBound( - int heartbeatExecutorExponentialBackOffBound) { - this.heartbeatExecutorExponentialBackOffBound = heartbeatExecutorExponentialBackOffBound; - } - - @Override - public int getCacheRefreshExecutorThreadPoolSize() { - return cacheRefreshExecutorThreadPoolSize; - } - - public void setCacheRefreshExecutorThreadPoolSize( - int cacheRefreshExecutorThreadPoolSize) { - this.cacheRefreshExecutorThreadPoolSize = cacheRefreshExecutorThreadPoolSize; - } - - @Override - public int getCacheRefreshExecutorExponentialBackOffBound() { - return cacheRefreshExecutorExponentialBackOffBound; - } - - public void setCacheRefreshExecutorExponentialBackOffBound( - int cacheRefreshExecutorExponentialBackOffBound) { - this.cacheRefreshExecutorExponentialBackOffBound = cacheRefreshExecutorExponentialBackOffBound; - } - - public Map getServiceUrl() { - return serviceUrl; - } - - public void setServiceUrl(Map serviceUrl) { - this.serviceUrl = serviceUrl; - } - - public boolean isgZipContent() { - return gZipContent; - } - - public void setgZipContent(boolean gZipContent) { - this.gZipContent = gZipContent; - } - - public boolean isUseDnsForFetchingServiceUrls() { - return useDnsForFetchingServiceUrls; - } - - public void setUseDnsForFetchingServiceUrls(boolean useDnsForFetchingServiceUrls) { - this.useDnsForFetchingServiceUrls = useDnsForFetchingServiceUrls; - } - - public boolean isRegisterWithEureka() { - return registerWithEureka; - } - - public void setRegisterWithEureka(boolean registerWithEureka) { - this.registerWithEureka = registerWithEureka; - } - - public boolean isPreferSameZoneEureka() { - return preferSameZoneEureka; - } - - public void setPreferSameZoneEureka(boolean preferSameZoneEureka) { - this.preferSameZoneEureka = preferSameZoneEureka; - } - - public boolean isLogDeltaDiff() { - return logDeltaDiff; - } - - public void setLogDeltaDiff(boolean logDeltaDiff) { - this.logDeltaDiff = logDeltaDiff; - } - - public boolean isDisableDelta() { - return disableDelta; - } - - public void setDisableDelta(boolean disableDelta) { - this.disableDelta = disableDelta; - } - - public String getFetchRemoteRegionsRegistry() { - return fetchRemoteRegionsRegistry; - } - - public void setFetchRemoteRegionsRegistry(String fetchRemoteRegionsRegistry) { - this.fetchRemoteRegionsRegistry = fetchRemoteRegionsRegistry; - } - - public Map getAvailabilityZones() { - return availabilityZones; - } - - public void setAvailabilityZones(Map availabilityZones) { - this.availabilityZones = availabilityZones; - } - - public boolean isFilterOnlyUpInstances() { - return filterOnlyUpInstances; - } - - public void setFilterOnlyUpInstances(boolean filterOnlyUpInstances) { - this.filterOnlyUpInstances = filterOnlyUpInstances; - } - - public boolean isFetchRegistry() { - return fetchRegistry; - } - - public void setFetchRegistry(boolean fetchRegistry) { - this.fetchRegistry = fetchRegistry; - } - - @Override - public String getDollarReplacement() { - return dollarReplacement; - } - - public void setDollarReplacement(String dollarReplacement) { - this.dollarReplacement = dollarReplacement; - } - - @Override - public String getEscapeCharReplacement() { - return escapeCharReplacement; - } - - public void setEscapeCharReplacement(String escapeCharReplacement) { - this.escapeCharReplacement = escapeCharReplacement; - } - - public boolean isAllowRedirects() { - return allowRedirects; - } - - public void setAllowRedirects(boolean allowRedirects) { - this.allowRedirects = allowRedirects; - } - - public boolean isOnDemandUpdateStatusChange() { - return onDemandUpdateStatusChange; - } - - public void setOnDemandUpdateStatusChange(boolean onDemandUpdateStatusChange) { - this.onDemandUpdateStatusChange = onDemandUpdateStatusChange; - } - - @Override - public String getEncoderName() { - return encoderName; - } - - public void setEncoderName(String encoderName) { - this.encoderName = encoderName; - } - - @Override - public String getDecoderName() { - return decoderName; - } - - public void setDecoderName(String decoderName) { - this.decoderName = decoderName; - } - - @Override - public String getClientDataAccept() { - return clientDataAccept; - } - - public void setClientDataAccept(String clientDataAccept) { - this.clientDataAccept = clientDataAccept; - } - - public boolean isShouldUnregisterOnShutdown() { - return shouldUnregisterOnShutdown; - } - - public void setShouldUnregisterOnShutdown(boolean shouldUnregisterOnShutdown) { - this.shouldUnregisterOnShutdown = shouldUnregisterOnShutdown; - } - - public boolean isShouldEnforceRegistrationAtInit() { - return shouldEnforceRegistrationAtInit; - } - - public void setShouldEnforceRegistrationAtInit(boolean shouldEnforceRegistrationAtInit) { - this.shouldEnforceRegistrationAtInit = shouldEnforceRegistrationAtInit; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - EurekaClientConfigBean that = (EurekaClientConfigBean) o; - return Objects.equals(propertyResolver, that.propertyResolver) && - enabled == that.enabled && - Objects.equals(transport, that.transport) && - registryFetchIntervalSeconds == that.registryFetchIntervalSeconds && - instanceInfoReplicationIntervalSeconds == that.instanceInfoReplicationIntervalSeconds && - initialInstanceInfoReplicationIntervalSeconds == that.initialInstanceInfoReplicationIntervalSeconds && - eurekaServiceUrlPollIntervalSeconds == that.eurekaServiceUrlPollIntervalSeconds && - eurekaServerReadTimeoutSeconds == that.eurekaServerReadTimeoutSeconds && - eurekaServerConnectTimeoutSeconds == that.eurekaServerConnectTimeoutSeconds && - eurekaServerTotalConnections == that.eurekaServerTotalConnections && - eurekaServerTotalConnectionsPerHost == that.eurekaServerTotalConnectionsPerHost && - eurekaConnectionIdleTimeoutSeconds == that.eurekaConnectionIdleTimeoutSeconds && - heartbeatExecutorThreadPoolSize == that.heartbeatExecutorThreadPoolSize && - heartbeatExecutorExponentialBackOffBound == that.heartbeatExecutorExponentialBackOffBound && - cacheRefreshExecutorThreadPoolSize == that.cacheRefreshExecutorThreadPoolSize && - cacheRefreshExecutorExponentialBackOffBound == that.cacheRefreshExecutorExponentialBackOffBound && - gZipContent == that.gZipContent && - useDnsForFetchingServiceUrls == that.useDnsForFetchingServiceUrls && - registerWithEureka == that.registerWithEureka && - preferSameZoneEureka == that.preferSameZoneEureka && - logDeltaDiff == that.logDeltaDiff && - disableDelta == that.disableDelta && - filterOnlyUpInstances == that.filterOnlyUpInstances && - fetchRegistry == that.fetchRegistry && - allowRedirects == that.allowRedirects && - onDemandUpdateStatusChange == that.onDemandUpdateStatusChange && - shouldUnregisterOnShutdown == that.shouldUnregisterOnShutdown && - shouldEnforceRegistrationAtInit == that.shouldEnforceRegistrationAtInit && - Objects.equals(proxyPort, that.proxyPort) && - Objects.equals(proxyHost, that.proxyHost) && - Objects.equals(proxyUserName, that.proxyUserName) && - Objects.equals(proxyPassword, that.proxyPassword) && - Objects.equals(backupRegistryImpl, that.backupRegistryImpl) && - Objects.equals(eurekaServerURLContext, that.eurekaServerURLContext) && - Objects.equals(eurekaServerPort, that.eurekaServerPort) && - Objects.equals(eurekaServerDNSName, that.eurekaServerDNSName) && - Objects.equals(region, that.region) && - Objects.equals(registryRefreshSingleVipAddress, that.registryRefreshSingleVipAddress) && - Objects.equals(serviceUrl, that.serviceUrl) && - Objects.equals(fetchRemoteRegionsRegistry, that.fetchRemoteRegionsRegistry) && - Objects.equals(availabilityZones, that.availabilityZones) && - Objects.equals(dollarReplacement, that.dollarReplacement) && - Objects.equals(escapeCharReplacement, that.escapeCharReplacement) && - Objects.equals(encoderName, that.encoderName) && - Objects.equals(decoderName, that.decoderName) && - Objects.equals(clientDataAccept, that.clientDataAccept); - } - - @Override - public int hashCode() { - return Objects.hash(propertyResolver, enabled, transport, - registryFetchIntervalSeconds, instanceInfoReplicationIntervalSeconds, - initialInstanceInfoReplicationIntervalSeconds, - eurekaServiceUrlPollIntervalSeconds, proxyPort, proxyHost, proxyUserName, - proxyPassword, eurekaServerReadTimeoutSeconds, - eurekaServerConnectTimeoutSeconds, backupRegistryImpl, - eurekaServerTotalConnections, eurekaServerTotalConnectionsPerHost, - eurekaServerURLContext, eurekaServerPort, eurekaServerDNSName, region, - eurekaConnectionIdleTimeoutSeconds, registryRefreshSingleVipAddress, - heartbeatExecutorThreadPoolSize, heartbeatExecutorExponentialBackOffBound, - cacheRefreshExecutorThreadPoolSize, - cacheRefreshExecutorExponentialBackOffBound, serviceUrl, gZipContent, - useDnsForFetchingServiceUrls, registerWithEureka, preferSameZoneEureka, - logDeltaDiff, disableDelta, fetchRemoteRegionsRegistry, availabilityZones, - filterOnlyUpInstances, fetchRegistry, dollarReplacement, - escapeCharReplacement, allowRedirects, onDemandUpdateStatusChange, - encoderName, decoderName, clientDataAccept, shouldUnregisterOnShutdown, - shouldEnforceRegistrationAtInit); - } - - @Override - public String toString() { - return new StringBuilder("EurekaClientConfigBean{") - .append("propertyResolver=").append(propertyResolver).append(", ") - .append("enabled=").append(enabled).append(", ") - .append("transport=").append(transport).append(", ") - .append("registryFetchIntervalSeconds=").append(registryFetchIntervalSeconds).append(", ") - .append("instanceInfoReplicationIntervalSeconds=").append(instanceInfoReplicationIntervalSeconds).append(", ") - .append("initialInstanceInfoReplicationIntervalSeconds=").append(initialInstanceInfoReplicationIntervalSeconds).append(", ") - .append("eurekaServiceUrlPollIntervalSeconds=").append(eurekaServiceUrlPollIntervalSeconds).append(", ") - .append("proxyPort='").append(proxyPort).append("', ") - .append("proxyHost='").append(proxyHost).append("', ") - .append("proxyUserName='").append(proxyUserName).append("', ") - .append("proxyPassword='").append(proxyPassword).append("', ") - .append("eurekaServerReadTimeoutSeconds=").append(eurekaServerReadTimeoutSeconds).append(", ") - .append("eurekaServerConnectTimeoutSeconds=").append(eurekaServerConnectTimeoutSeconds).append(", ") - .append("backupRegistryImpl='").append(backupRegistryImpl).append("', ") - .append("eurekaServerTotalConnections=").append(eurekaServerTotalConnections).append(", ") - .append("eurekaServerTotalConnectionsPerHost=").append(eurekaServerTotalConnectionsPerHost).append(", ") - .append("eurekaServerURLContext='").append(eurekaServerURLContext).append("', ") - .append("eurekaServerPort='").append(eurekaServerPort).append("', ") - .append("eurekaServerDNSName='").append(eurekaServerDNSName).append("', ") - .append("region='").append(region).append("', ") - .append("eurekaConnectionIdleTimeoutSeconds=").append(eurekaConnectionIdleTimeoutSeconds).append(", ") - .append("registryRefreshSingleVipAddress='").append(registryRefreshSingleVipAddress).append("', ") - .append("heartbeatExecutorThreadPoolSize=").append(heartbeatExecutorThreadPoolSize).append(", ") - .append("heartbeatExecutorExponentialBackOffBound=").append(heartbeatExecutorExponentialBackOffBound).append(", ") - .append("cacheRefreshExecutorThreadPoolSize=").append(cacheRefreshExecutorThreadPoolSize).append(", ") - .append("cacheRefreshExecutorExponentialBackOffBound=").append(cacheRefreshExecutorExponentialBackOffBound).append(", ") - .append("serviceUrl=").append(serviceUrl).append(", ") - .append("gZipContent=").append(gZipContent).append(", ") - .append("useDnsForFetchingServiceUrls=").append(useDnsForFetchingServiceUrls).append(", ") - .append("registerWithEureka=").append(registerWithEureka).append(", ") - .append("preferSameZoneEureka=").append(preferSameZoneEureka).append(", ") - .append("logDeltaDiff=").append(logDeltaDiff).append(", ") - .append("disableDelta=").append(disableDelta).append(", ") - .append("fetchRemoteRegionsRegistry='").append(fetchRemoteRegionsRegistry).append("', ") - .append("availabilityZones=").append(availabilityZones).append(", ") - .append("filterOnlyUpInstances=").append(filterOnlyUpInstances).append(", ") - .append("fetchRegistry=").append(fetchRegistry).append(", ") - .append("dollarReplacement='").append(dollarReplacement).append("', ") - .append("escapeCharReplacement='").append(escapeCharReplacement).append("', ") - .append("allowRedirects=").append(allowRedirects).append(", ") - .append("onDemandUpdateStatusChange=").append(onDemandUpdateStatusChange).append(", ") - .append("encoderName='").append(encoderName).append("', ") - .append("decoderName='").append(decoderName).append("', ") - .append("clientDataAccept='").append(clientDataAccept).append("'").append("}") - .append("=shouldUnregisterOnShutdown'").append(shouldUnregisterOnShutdown).append("'").append("}") - .append("shouldEnforceRegistrationAtInit='").append(shouldEnforceRegistrationAtInit).append("'").append("}") - .toString(); - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaConstants.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaConstants.java deleted file mode 100644 index 1f24480a..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaConstants.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -/** - * @author Spencer Gibb - */ -public class EurekaConstants { - - public static final String DEFAULT_PREFIX = "/eureka"; - - private EurekaConstants() { - throw new AssertionError("Must not instantiate constant utility class"); - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClient.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClient.java deleted file mode 100644 index d45889b2..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClient.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.springframework.cloud.client.DefaultServiceInstance; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.util.Assert; - -import com.netflix.appinfo.EurekaInstanceConfig; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.shared.Application; -import com.netflix.discovery.shared.Applications; - -import static com.netflix.appinfo.InstanceInfo.PortType.SECURE; - -/** - * @author Spencer Gibb - */ -public class EurekaDiscoveryClient implements DiscoveryClient { - - public static final String DESCRIPTION = "Spring Cloud Eureka Discovery Client"; - - private final EurekaInstanceConfig config; - - private final EurekaClient eurekaClient; - - public EurekaDiscoveryClient(EurekaInstanceConfig config, EurekaClient eurekaClient) { - this.config = config; - this.eurekaClient = eurekaClient; - } - - @Override - public String description() { - return DESCRIPTION; - } - - @Override - public List getInstances(String serviceId) { - List infos = this.eurekaClient.getInstancesByVipAddress(serviceId, - false); - List instances = new ArrayList<>(); - for (InstanceInfo info : infos) { - instances.add(new EurekaServiceInstance(info)); - } - return instances; - } - - public static class EurekaServiceInstance implements ServiceInstance { - private InstanceInfo instance; - - public EurekaServiceInstance(InstanceInfo instance) { - Assert.notNull(instance, "Service instance required"); - this.instance = instance; - } - - public InstanceInfo getInstanceInfo() { - return instance; - } - - @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 getMetadata() { - return this.instance.getMetadata(); - } - } - - @Override - public List getServices() { - Applications applications = this.eurekaClient.getApplications(); - if (applications == null) { - return Collections.emptyList(); - } - List registered = applications.getRegisteredApplications(); - List names = new ArrayList<>(); - for (Application app : registered) { - if (app.getInstances().isEmpty()) { - continue; - } - names.add(app.getName().toLowerCase()); - - } - return names; - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClientConfiguration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClientConfiguration.java deleted file mode 100644 index 07a8edd3..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClientConfiguration.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.eureka; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.health.HealthAggregator; -import org.springframework.boot.actuate.health.OrderedHealthAggregator; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent; -import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.event.EventListener; - -import com.netflix.appinfo.HealthCheckHandler; -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.EurekaClientConfig; - -/** - * @author Dave Syer - * @author Spencer Gibb - * @author Jon Schneider - * @author Jakub Narloch - */ -@Configuration -@EnableConfigurationProperties -@ConditionalOnClass(EurekaClientConfig.class) -@ConditionalOnProperty(value = "eureka.client.enabled", matchIfMissing = true) -public class EurekaDiscoveryClientConfiguration { - - class Marker {} - - @Bean - public Marker eurekaDiscoverClientMarker() { - return new Marker(); - } - - @Configuration - @ConditionalOnClass(RefreshScopeRefreshedEvent.class) - protected static class EurekaClientConfigurationRefresher { - - @Autowired(required = false) - private EurekaClient eurekaClient; - - @Autowired(required = false) - private EurekaAutoServiceRegistration autoRegistration; - - @EventListener(RefreshScopeRefreshedEvent.class) - public void onApplicationEvent(RefreshScopeRefreshedEvent event) { - //This will force the creation of the EurkaClient bean if not already created - //to make sure the client will be reregistered after a refresh event - if(eurekaClient != null) { - eurekaClient.getApplications(); - } - if (autoRegistration != null) { - // register in case meta data changed - this.autoRegistration.stop(); - this.autoRegistration.start(); - } - } - } - - - @Configuration - @ConditionalOnProperty(value = "eureka.client.healthcheck.enabled", matchIfMissing = false) - protected static class EurekaHealthCheckHandlerConfiguration { - - @Autowired(required = false) - private HealthAggregator healthAggregator = new OrderedHealthAggregator(); - - @Bean - @ConditionalOnMissingBean(HealthCheckHandler.class) - public EurekaHealthCheckHandler eurekaHealthCheckHandler() { - return new EurekaHealthCheckHandler(this.healthAggregator); - } - } -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaHealthCheckHandler.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaHealthCheckHandler.java deleted file mode 100644 index 0ab3d745..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaHealthCheckHandler.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -import java.util.HashMap; -import java.util.Map; - -import com.netflix.appinfo.HealthCheckHandler; -import com.netflix.appinfo.InstanceInfo; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.boot.actuate.health.CompositeHealthIndicator; -import org.springframework.boot.actuate.health.HealthAggregator; -import org.springframework.boot.actuate.health.HealthIndicator; -import org.springframework.boot.actuate.health.Status; -import org.springframework.cloud.client.discovery.health.DiscoveryCompositeHealthIndicator; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.util.Assert; - -import static com.netflix.appinfo.InstanceInfo.InstanceStatus; - -/** - * A Eureka health checker, maps the application status into {@link InstanceStatus} - * that will be propagated to Eureka registry. - * - * On each heartbeat Eureka performs the health check invoking registered {@link HealthCheckHandler}. By default this - * implementation will perform aggregation of all registered {@link HealthIndicator} - * through registered {@link HealthAggregator}. - * - * @author Jakub Narloch - * @see HealthCheckHandler - * @see HealthAggregator - */ -public class EurekaHealthCheckHandler implements HealthCheckHandler, ApplicationContextAware, InitializingBean { - - private static final Map STATUS_MAPPING = - new HashMap() {{ - put(Status.UNKNOWN, InstanceStatus.UNKNOWN); - put(Status.OUT_OF_SERVICE, InstanceStatus.OUT_OF_SERVICE); - put(Status.DOWN, InstanceStatus.DOWN); - put(Status.UP, InstanceStatus.UP); - }}; - - private final CompositeHealthIndicator healthIndicator; - - private ApplicationContext applicationContext; - - public EurekaHealthCheckHandler(HealthAggregator healthAggregator) { - Assert.notNull(healthAggregator, "HealthAggregator must not be null"); - this.healthIndicator = new CompositeHealthIndicator(healthAggregator); - } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } - - @Override - public void afterPropertiesSet() throws Exception { - final Map healthIndicators = applicationContext.getBeansOfType(HealthIndicator.class); - - for (Map.Entry entry : healthIndicators.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 DiscoveryCompositeHealthIndicator) { - DiscoveryCompositeHealthIndicator indicator = (DiscoveryCompositeHealthIndicator) entry.getValue(); - for (DiscoveryCompositeHealthIndicator.Holder holder : indicator.getHealthIndicators()) { - if (!(holder.getDelegate() instanceof EurekaHealthIndicator)) { - healthIndicator.addHealthIndicator(holder.getDelegate().getName(), holder); - } - } - - } - else { - healthIndicator.addHealthIndicator(entry.getKey(), entry.getValue()); - } - } - } - - @Override - public InstanceStatus getStatus(InstanceStatus instanceStatus) { - return getHealthStatus(); - } - - protected InstanceStatus getHealthStatus() { - final Status status = getHealthIndicator().health().getStatus(); - return mapToInstanceStatus(status); - } - - protected InstanceStatus mapToInstanceStatus(Status status) { - if (!STATUS_MAPPING.containsKey(status)) { - return InstanceStatus.UNKNOWN; - } - return STATUS_MAPPING.get(status); - } - - protected CompositeHealthIndicator getHealthIndicator() { - return healthIndicator; - } -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaHealthIndicator.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaHealthIndicator.java deleted file mode 100644 index d7dc499a..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaHealthIndicator.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.springframework.boot.actuate.health.Health; -import org.springframework.boot.actuate.health.Health.Builder; -import org.springframework.boot.actuate.health.Status; -import org.springframework.cloud.client.discovery.health.DiscoveryHealthIndicator; - -import com.netflix.appinfo.EurekaInstanceConfig; -import com.netflix.discovery.DiscoveryClient; -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.EurekaClientConfig; -import com.netflix.discovery.shared.Application; -import com.netflix.discovery.shared.Applications; - -/** - * @author Dave Syer - */ -public 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() { - Builder builder = Health.unknown(); - Status status = getStatus(builder); - return builder.status(status).withDetail("applications", getApplications()) - .build(); - } - - private Status getStatus(Builder builder) { - Status status = new Status( - this.eurekaClient.getInstanceRemoteStatus().toString(), - "Remote status from Eureka server"); - - if (eurekaClient instanceof DiscoveryClient && clientConfig.shouldFetchRegistry()) { - DiscoveryClient discoveryClient = (DiscoveryClient) eurekaClient; - 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 Map getApplications() { - Applications applications = this.eurekaClient.getApplications(); - if (applications == null) { - return Collections.emptyMap(); - } - Map result = new HashMap<>(); - for (Application application : applications.getRegisteredApplications()) { - result.put(application.getName(), application.getInstances().size()); - } - return result; - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBean.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBean.java deleted file mode 100644 index 47c43c10..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBean.java +++ /dev/null @@ -1,650 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.commons.util.InetUtils.HostInfo; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.env.Environment; -import org.springframework.util.StringUtils; - -import com.netflix.appinfo.DataCenterInfo; -import com.netflix.appinfo.InstanceInfo.InstanceStatus; -import com.netflix.appinfo.MyDataCenterInfo; - -/** - * @author Dave Syer - * @author Spencer Gibb - * @author Ryan Baxter - * @author Gregor Zurowski - */ -@ConfigurationProperties("eureka.instance") -public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, EnvironmentAware { - - private static final String UNKNOWN = "unknown"; - - private HostInfo hostInfo; - - private InetUtils inetUtils; - - /** - * Get the name of the application to be registered with eureka. - */ - private String appname = UNKNOWN; - - /** - * Get the name of the application group to be registered with eureka. - */ - private String appGroupName; - - /** - * Indicates whether the instance should be enabled for taking traffic as soon as it - * is registered with eureka. Sometimes the application might need to do some - * pre-processing before it is ready to take traffic. - */ - private boolean instanceEnabledOnit; - - /** - * Get the non-secure port on which the instance should receive traffic. - */ - private int nonSecurePort = 80; - - /** - * Get the Secure port on which the instance should receive traffic. - */ - private int securePort = 443; - - /** - * Indicates whether the non-secure port should be enabled for traffic or not. - */ - private boolean nonSecurePortEnabled = true; - - /** - * Indicates whether the secure port should be enabled for traffic or not. - */ - private boolean securePortEnabled; - - /** - * Indicates how often (in seconds) the eureka client needs to send heartbeats to - * eureka server to indicate that it is still alive. If the heartbeats are not - * received for the period specified in leaseExpirationDurationInSeconds, eureka - * server will remove the instance from its view, there by disallowing traffic to this - * instance. - * - * Note that the instance could still not take traffic if it implements - * HealthCheckCallback and then decides to make itself unavailable. - */ - private int leaseRenewalIntervalInSeconds = 30; - - /** - * Indicates the time in seconds that the eureka server waits since it received the - * last heartbeat before it can remove this instance from its view and there by - * disallowing traffic to this instance. - * - * Setting this value too long could mean that the traffic could be routed to the - * instance even though the instance is not alive. Setting this value too small could - * mean, the instance may be taken out of traffic because of temporary network - * glitches.This value to be set to atleast higher than the value specified in - * leaseRenewalIntervalInSeconds. - */ - private int leaseExpirationDurationInSeconds = 90; - - /** - * Gets the virtual host name defined for this instance. - * - * This is typically the way other instance would find this instance by using the - * virtual host name.Think of this as similar to the fully qualified domain name, that - * the users of your services will need to find this instance. - */ - private String virtualHostName = UNKNOWN; - - /** - * Get the unique Id (within the scope of the appName) of this instance to be - * registered with eureka. - */ - private String instanceId; - - /** - * Gets the secure virtual host name defined for this instance. - * - * This is typically the way other instance would find this instance by using the - * secure virtual host name.Think of this as similar to the fully qualified domain - * name, that the users of your services will need to find this instance. - */ - private String secureVirtualHostName = UNKNOWN; - - /** - * Gets the AWS autoscaling group name associated with this instance. This information - * is specifically used in an AWS environment to automatically put an instance out of - * service after the instance is launched and it has been disabled for traffic.. - */ - private String aSGName; - - /** - * Gets the metadata name/value pairs associated with this instance. This information - * is sent to eureka server and can be used by other instances. - */ - private Map metadataMap = new HashMap<>(); - - /** - * Returns the data center this instance is deployed. This information is used to get - * some AWS specific instance information if the instance is deployed in AWS. - */ - private DataCenterInfo dataCenterInfo = new MyDataCenterInfo( - DataCenterInfo.Name.MyOwn); - - /** - * Get the IPAdress of the instance. This information is for academic purposes only as - * the communication from other instances primarily happen using the information - * supplied in {@link #getHostName(boolean)}. - */ - private String ipAddress; - - /** - * Gets the relative status page URL path for this instance. The status page URL is - * then constructed out of the hostName and the type of communication - secure or - * unsecure as specified in securePort and nonSecurePort. - * - * It is normally used for informational purposes for other services to find about the - * status of this instance. Users can provide a simple HTML indicating what is the - * current status of the instance. - */ - private String statusPageUrlPath = "/info"; - - /** - * Gets the absolute status page URL path for this instance. The users can provide the - * statusPageUrlPath if the status page resides in the same instance talking to - * eureka, else in the cases where the instance is a proxy for some other server, - * users can provide the full URL. If the full URL is provided it takes precedence. - * - * It is normally used for informational purposes for other services to find about the - * status of this instance. Users can provide a simple HTML indicating what is the - * current status of the instance. - */ - private String statusPageUrl; - - /** - * Gets the relative home page URL Path for this instance. The home page URL is then - * constructed out of the hostName and the type of communication - secure or unsecure. - * - * It is normally used for informational purposes for other services to use it as a - * landing page. - */ - private String homePageUrlPath = "/"; - - /** - * Gets the absolute home page URL for this instance. The users can provide the - * homePageUrlPath if the home page resides in the same instance talking to eureka, - * else in the cases where the instance is a proxy for some other server, users can - * provide the full URL. If the full URL is provided it takes precedence. - * - * It is normally used for informational purposes for other services to use it as a - * landing page. The full URL should follow the format http://${eureka.hostname}:7001/ - * where the value ${eureka.hostname} is replaced at runtime. - */ - private String homePageUrl; - - /** - * Gets the relative health check URL path for this instance. The health check page - * URL is then constructed out of the hostname and the type of communication - secure - * or unsecure as specified in securePort and nonSecurePort. - * - * It is normally used for making educated decisions based on the health of the - * instance - for example, it can be used to determine whether to proceed deployments - * to an entire farm or stop the deployments without causing further damage. - */ - private String healthCheckUrlPath = "/health"; - - /** - * Gets the absolute health check page URL for this instance. The users can provide - * the healthCheckUrlPath if the health check page resides in the same instance - * talking to eureka, else in the cases where the instance is a proxy for some other - * server, users can provide the full URL. If the full URL is provided it takes - * precedence. - * - *

- * It is normally used for making educated decisions based on the health of the - * instance - for example, it can be used to determine whether to proceed deployments - * to an entire farm or stop the deployments without causing further damage. The full - * URL should follow the format http://${eureka.hostname}:7001/ where the value - * ${eureka.hostname} is replaced at runtime. - */ - private String healthCheckUrl; - - /** - * Gets the absolute secure health check page URL for this instance. The users can - * provide the secureHealthCheckUrl if the health check page resides in the same - * instance talking to eureka, else in the cases where the instance is a proxy for - * some other server, users can provide the full URL. If the full URL is provided it - * takes precedence. - * - *

- * It is normally used for making educated decisions based on the health of the - * instance - for example, it can be used to determine whether to proceed deployments - * to an entire farm or stop the deployments without causing further damage. The full - * URL should follow the format http://${eureka.hostname}:7001/ where the value - * ${eureka.hostname} is replaced at runtime. - */ - private String secureHealthCheckUrl; - - /** - * Get the namespace used to find properties. Ignored in Spring Cloud. - */ - private String namespace = "eureka"; - - /** - * The hostname if it can be determined at configuration time (otherwise it will be - * guessed from OS primitives). - */ - private String hostname; - - /** - * Flag to say that, when guessing a hostname, the IP address of the server should be - * used in prference to the hostname reported by the OS. - */ - private boolean preferIpAddress = false; - - /** - * Initial status to register with rmeote Eureka server. - */ - private InstanceStatus initialStatus = InstanceStatus.UP; - - private String[] defaultAddressResolutionOrder = new String[0]; - private Environment environment; - - public String getHostname() { - return getHostName(false); - } - - @SuppressWarnings("unused") - private EurekaInstanceConfigBean() { - } - - public EurekaInstanceConfigBean(InetUtils inetUtils) { - this.inetUtils = inetUtils; - this.hostInfo = this.inetUtils.findFirstNonLoopbackHostInfo(); - this.ipAddress = this.hostInfo.getIpAddress(); - this.hostname = this.hostInfo.getHostname(); - } - - @Override - public String getInstanceId() { - if (this.instanceId == null && this.metadataMap != null) { - return this.metadataMap.get("instanceId"); - } - return this.instanceId; - } - - @Override - public boolean getSecurePortEnabled() { - return this.securePortEnabled; - } - - public void setHostname(String hostname) { - this.hostname = hostname; - this.hostInfo.override = true; - } - - public void setIpAddress(String ipAddress) { - this.ipAddress = ipAddress; - this.hostInfo.override = true; - } - - @Override - public String getHostName(boolean refresh) { - if (refresh && !this.hostInfo.override) { - this.ipAddress = this.hostInfo.getIpAddress(); - this.hostname = this.hostInfo.getHostname(); - } - return this.preferIpAddress ? this.ipAddress : this.hostname; - } - - @Override - public void setEnvironment(Environment environment) { - this.environment = environment; - // set some defaults from the environment, but allow the defaults to use relaxed binding - String springAppName = this.environment.getProperty("spring.application.name", ""); - if(StringUtils.hasText(springAppName)) { - setAppname(springAppName); - setVirtualHostName(springAppName); - setSecureVirtualHostName(springAppName); - } - } - - private HostInfo getHostInfo() { - return hostInfo; - } - - private void setHostInfo(HostInfo hostInfo) { - this.hostInfo = hostInfo; - } - - private InetUtils getInetUtils() { - return inetUtils; - } - - private void setInetUtils(InetUtils inetUtils) { - this.inetUtils = inetUtils; - } - - public String getAppname() { - return appname; - } - - public void setAppname(String appname) { - this.appname = appname; - } - - public String getAppGroupName() { - return appGroupName; - } - - public void setAppGroupName(String appGroupName) { - this.appGroupName = appGroupName; - } - - public boolean isInstanceEnabledOnit() { - return instanceEnabledOnit; - } - - public void setInstanceEnabledOnit(boolean instanceEnabledOnit) { - this.instanceEnabledOnit = instanceEnabledOnit; - } - - public int getNonSecurePort() { - return nonSecurePort; - } - - public void setNonSecurePort(int nonSecurePort) { - this.nonSecurePort = nonSecurePort; - } - - public int getSecurePort() { - return securePort; - } - - public void setSecurePort(int securePort) { - this.securePort = securePort; - } - - public boolean isNonSecurePortEnabled() { - return nonSecurePortEnabled; - } - - public void setNonSecurePortEnabled(boolean nonSecurePortEnabled) { - this.nonSecurePortEnabled = nonSecurePortEnabled; - } - - public boolean isSecurePortEnabled() { - return securePortEnabled; - } - - public void setSecurePortEnabled(boolean securePortEnabled) { - this.securePortEnabled = securePortEnabled; - } - - public int getLeaseRenewalIntervalInSeconds() { - return leaseRenewalIntervalInSeconds; - } - - public void setLeaseRenewalIntervalInSeconds(int leaseRenewalIntervalInSeconds) { - this.leaseRenewalIntervalInSeconds = leaseRenewalIntervalInSeconds; - } - - public int getLeaseExpirationDurationInSeconds() { - return leaseExpirationDurationInSeconds; - } - - public void setLeaseExpirationDurationInSeconds( - int leaseExpirationDurationInSeconds) { - this.leaseExpirationDurationInSeconds = leaseExpirationDurationInSeconds; - } - - public String getVirtualHostName() { - return virtualHostName; - } - - public void setVirtualHostName(String virtualHostName) { - this.virtualHostName = virtualHostName; - } - - public void setInstanceId(String instanceId) { - this.instanceId = instanceId; - } - - public String getSecureVirtualHostName() { - return secureVirtualHostName; - } - - public void setSecureVirtualHostName(String secureVirtualHostName) { - this.secureVirtualHostName = secureVirtualHostName; - } - - public String getASGName() { - return aSGName; - } - - public void setASGName(String aSGName) { - this.aSGName = aSGName; - } - - public Map getMetadataMap() { - return metadataMap; - } - - public void setMetadataMap(Map metadataMap) { - this.metadataMap = metadataMap; - } - - public DataCenterInfo getDataCenterInfo() { - return dataCenterInfo; - } - - public void setDataCenterInfo(DataCenterInfo dataCenterInfo) { - this.dataCenterInfo = dataCenterInfo; - } - - public String getIpAddress() { - return ipAddress; - } - - public String getStatusPageUrlPath() { - return statusPageUrlPath; - } - - public void setStatusPageUrlPath(String statusPageUrlPath) { - this.statusPageUrlPath = statusPageUrlPath; - } - - public String getStatusPageUrl() { - return statusPageUrl; - } - - public void setStatusPageUrl(String statusPageUrl) { - this.statusPageUrl = statusPageUrl; - } - - public String getHomePageUrlPath() { - return homePageUrlPath; - } - - public void setHomePageUrlPath(String homePageUrlPath) { - this.homePageUrlPath = homePageUrlPath; - } - - public String getHomePageUrl() { - return homePageUrl; - } - - public void setHomePageUrl(String homePageUrl) { - this.homePageUrl = homePageUrl; - } - - public String getHealthCheckUrlPath() { - return healthCheckUrlPath; - } - - public void setHealthCheckUrlPath(String healthCheckUrlPath) { - this.healthCheckUrlPath = healthCheckUrlPath; - } - - public String getHealthCheckUrl() { - return healthCheckUrl; - } - - public void setHealthCheckUrl(String healthCheckUrl) { - this.healthCheckUrl = healthCheckUrl; - } - - public String getSecureHealthCheckUrl() { - return secureHealthCheckUrl; - } - - public void setSecureHealthCheckUrl(String secureHealthCheckUrl) { - this.secureHealthCheckUrl = secureHealthCheckUrl; - } - - public String getNamespace() { - return namespace; - } - - public void setNamespace(String namespace) { - this.namespace = namespace; - } - - public boolean isPreferIpAddress() { - return preferIpAddress; - } - - public void setPreferIpAddress(boolean preferIpAddress) { - this.preferIpAddress = preferIpAddress; - } - - public InstanceStatus getInitialStatus() { - return initialStatus; - } - - public void setInitialStatus(InstanceStatus initialStatus) { - this.initialStatus = initialStatus; - } - - public String[] getDefaultAddressResolutionOrder() { - return defaultAddressResolutionOrder; - } - - public void setDefaultAddressResolutionOrder(String[] defaultAddressResolutionOrder) { - this.defaultAddressResolutionOrder = defaultAddressResolutionOrder; - } - - public Environment getEnvironment() { - return environment; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - EurekaInstanceConfigBean that = (EurekaInstanceConfigBean) o; - return Objects.equals(hostInfo, that.hostInfo) && - Objects.equals(inetUtils, that.inetUtils) && - Objects.equals(appname, that.appname) && - Objects.equals(appGroupName, that.appGroupName) && - instanceEnabledOnit == that.instanceEnabledOnit && - nonSecurePort == that.nonSecurePort && - securePort == that.securePort && - nonSecurePortEnabled == that.nonSecurePortEnabled && - securePortEnabled == that.securePortEnabled && - leaseRenewalIntervalInSeconds == that.leaseRenewalIntervalInSeconds && - leaseExpirationDurationInSeconds == that.leaseExpirationDurationInSeconds && - Objects.equals(virtualHostName, that.virtualHostName) && - Objects.equals(instanceId, that.instanceId) && - Objects.equals(secureVirtualHostName, that.secureVirtualHostName) && - Objects.equals(aSGName, that.aSGName) && - Objects.equals(metadataMap, that.metadataMap) && - Objects.equals(dataCenterInfo, that.dataCenterInfo) && - Objects.equals(ipAddress, that.ipAddress) && - Objects.equals(statusPageUrlPath, that.statusPageUrlPath) && - Objects.equals(statusPageUrl, that.statusPageUrl) && - Objects.equals(homePageUrlPath, that.homePageUrlPath) && - Objects.equals(homePageUrl, that.homePageUrl) && - Objects.equals(healthCheckUrlPath, that.healthCheckUrlPath) && - Objects.equals(healthCheckUrl, that.healthCheckUrl) && - Objects.equals(secureHealthCheckUrl, that.secureHealthCheckUrl) && - Objects.equals(namespace, that.namespace) && - Objects.equals(hostname, that.hostname) && - preferIpAddress == that.preferIpAddress && - Objects.equals(initialStatus, that.initialStatus) && - Arrays.equals(defaultAddressResolutionOrder, that.defaultAddressResolutionOrder) && - Objects.equals(environment, that.environment); - } - - @Override - public int hashCode() { - return Objects.hash(hostInfo, inetUtils, appname, appGroupName, - instanceEnabledOnit, nonSecurePort, securePort, nonSecurePortEnabled, - securePortEnabled, leaseRenewalIntervalInSeconds, - leaseExpirationDurationInSeconds, virtualHostName, instanceId, - secureVirtualHostName, aSGName, metadataMap, dataCenterInfo, ipAddress, - statusPageUrlPath, statusPageUrl, homePageUrlPath, homePageUrl, - healthCheckUrlPath, healthCheckUrl, secureHealthCheckUrl, namespace, - hostname, preferIpAddress, initialStatus, defaultAddressResolutionOrder, environment); - } - - @Override - public String toString() { - return new StringBuilder("EurekaInstanceConfigBean{") - .append("hostInfo=").append(hostInfo).append(", ") - .append("inetUtils=").append(inetUtils).append(", ") - .append("appname='").append(appname).append("', ") - .append("appGroupName='").append(appGroupName).append("', ") - .append("instanceEnabledOnit=").append(instanceEnabledOnit).append(", ") - .append("nonSecurePort=").append(nonSecurePort).append(", ") - .append("securePort=").append(securePort).append(", ") - .append("nonSecurePortEnabled=").append(nonSecurePortEnabled).append(", ") - .append("securePortEnabled=").append(securePortEnabled).append(", ") - .append("leaseRenewalIntervalInSeconds=").append(leaseRenewalIntervalInSeconds).append(", ") - .append("leaseExpirationDurationInSeconds=").append(leaseExpirationDurationInSeconds).append(", ") - .append("virtualHostName='").append(virtualHostName).append("', ") - .append("instanceId='").append(instanceId).append("', ") - .append("secureVirtualHostName='").append(secureVirtualHostName).append("', ") - .append("aSGName='").append(aSGName).append("', ") - .append("metadataMap=").append(metadataMap).append(", ") - .append("dataCenterInfo=").append(dataCenterInfo).append(", ") - .append("ipAddress='").append(ipAddress).append("', ") - .append("statusPageUrlPath='").append(statusPageUrlPath).append("', ") - .append("statusPageUrl='").append(statusPageUrl).append("', ") - .append("homePageUrlPath='").append(homePageUrlPath).append("', ") - .append("homePageUrl='").append(homePageUrl).append("', ") - .append("healthCheckUrlPath='").append(healthCheckUrlPath).append("', ") - .append("healthCheckUrl='").append(healthCheckUrl).append("', ") - .append("secureHealthCheckUrl='").append(secureHealthCheckUrl).append("', ") - .append("namespace='").append(namespace).append("', ") - .append("hostname='").append(hostname).append("', ") - .append("preferIpAddress=").append(preferIpAddress).append(", ") - .append("initialStatus=").append(initialStatus).append(", ") - .append("defaultAddressResolutionOrder=").append(Arrays.toString(defaultAddressResolutionOrder)).append(", ") - .append("environment=").append(environment).append(", ").append("}") - .toString(); - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/InstanceInfoFactory.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/InstanceInfoFactory.java deleted file mode 100644 index f92891ca..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/InstanceInfoFactory.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -import java.util.Map; - -import com.netflix.appinfo.EurekaInstanceConfig; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.appinfo.LeaseInfo; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * See com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider - * @author Spencer Gibb - */ -public class InstanceInfoFactory { - - private static final Log log = LogFactory.getLog(InstanceInfoFactory.class); - - public InstanceInfo create(EurekaInstanceConfig config) { - 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 mapEntry : config.getMetadataMap().entrySet()) { - String key = mapEntry.getKey(); - String value = mapEntry.getValue(); - builder.add(key, value); - } - - InstanceInfo instanceInfo = builder.build(); - instanceInfo.setLeaseInfo(leaseInfoBuilder.build()); - return instanceInfo; - } -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/MutableDiscoveryClientOptionalArgs.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/MutableDiscoveryClientOptionalArgs.java deleted file mode 100644 index f19b0cdb..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/MutableDiscoveryClientOptionalArgs.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -import java.util.Collection; -import java.util.LinkedHashSet; - -import com.netflix.discovery.DiscoveryClient.DiscoveryClientOptionalArgs; -import com.sun.jersey.api.client.filter.ClientFilter; - -/** - * @author Dave Syer - */ -public class MutableDiscoveryClientOptionalArgs extends DiscoveryClientOptionalArgs { - - private Collection additionalFilters; - - @Override - public void setAdditionalFilters(Collection additionalFilters) { - additionalFilters = new LinkedHashSet<>(additionalFilters); - this.additionalFilters = additionalFilters; - super.setAdditionalFilters(additionalFilters); - } - - public Collection getAdditionalFilters() { - return this.additionalFilters; - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/DiscoveryClientOptionalArgsConfiguration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/DiscoveryClientOptionalArgsConfiguration.java deleted file mode 100644 index d0439afb..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/DiscoveryClientOptionalArgsConfiguration.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.config; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; -import org.springframework.boot.autoconfigure.condition.SearchStrategy; -import org.springframework.cloud.netflix.eureka.MutableDiscoveryClientOptionalArgs; -import org.springframework.cloud.netflix.eureka.http.RestTemplateDiscoveryClientOptionalArgs; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs; - -/** - * @author Daniel Lavoie - */ -@Configuration -public class DiscoveryClientOptionalArgsConfiguration { - @Bean - @ConditionalOnMissingClass("com.sun.jersey.api.client.filter.ClientFilter") - @ConditionalOnMissingBean(value = AbstractDiscoveryClientOptionalArgs.class, search = SearchStrategy.CURRENT) - public RestTemplateDiscoveryClientOptionalArgs restTemplateDiscoveryClientOptionalArgs() { - return new RestTemplateDiscoveryClientOptionalArgs(); - } - - @Bean - @ConditionalOnClass(name = "com.sun.jersey.api.client.filter.ClientFilter") - @ConditionalOnMissingBean(value = AbstractDiscoveryClientOptionalArgs.class, search = SearchStrategy.CURRENT) - public MutableDiscoveryClientOptionalArgs discoveryClientOptionalArgs() { - return new MutableDiscoveryClientOptionalArgs(); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaClientConfigServerAutoConfiguration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaClientConfigServerAutoConfiguration.java deleted file mode 100644 index 48623bad..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaClientConfigServerAutoConfiguration.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.config; - -import javax.annotation.PostConstruct; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.config.server.config.ConfigServerProperties; -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.StringUtils; - -import com.netflix.appinfo.EurekaInstanceConfig; -import com.netflix.discovery.EurekaClient; - -/** - * Extra configuration for config server if it happens to be a Eureka instance. - * - * @author Dave Syer - */ -@Configuration -@EnableConfigurationProperties -@ConditionalOnClass({ EurekaInstanceConfigBean.class, EurekaClient.class, - ConfigServerProperties.class }) -public class EurekaClientConfigServerAutoConfiguration { - - @Autowired(required = false) - private EurekaInstanceConfig instance; - - @Autowired(required = false) - private ConfigServerProperties server; - - @PostConstruct - public void init() { - if (this.instance == null || this.server == null) { - return; - } - String prefix = this.server.getPrefix(); - if (StringUtils.hasText(prefix)) { - this.instance.getMetadataMap().put("configPath", prefix); - } - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaDiscoveryClientConfigServiceAutoConfiguration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaDiscoveryClientConfigServiceAutoConfiguration.java deleted file mode 100644 index bbfcc094..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaDiscoveryClientConfigServiceAutoConfiguration.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.config; - -import javax.annotation.PostConstruct; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration; -import org.springframework.context.ConfigurableApplicationContext; - -import com.netflix.discovery.EurekaClient; - -/** - * Bootstrap configuration for a config client that wants to lookup the config server via - * discovery. - * - * @author Dave Syer - */ -@ConditionalOnBean({ EurekaDiscoveryClientConfiguration.class }) -@ConditionalOnProperty(value = "spring.cloud.config.discovery.enabled", matchIfMissing = false) -public class EurekaDiscoveryClientConfigServiceAutoConfiguration { - - @Autowired - private ConfigurableApplicationContext context; - - @PostConstruct - public void init() { - if (this.context.getParent() != null) { - if (this.context.getBeanNamesForType(EurekaClient.class).length > 0 - && this.context.getParent() - .getBeanNamesForType(EurekaClient.class).length > 0) { - // If the parent has a EurekaClient as well it should be shutdown, so the - // local one can register accurate instance info - this.context.getParent().getBean(EurekaClient.class).shutdown(); - } - } - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaDiscoveryClientConfigServiceBootstrapConfiguration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaDiscoveryClientConfigServiceBootstrapConfiguration.java deleted file mode 100644 index e194076b..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaDiscoveryClientConfigServiceBootstrapConfiguration.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.config; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.config.client.ConfigServicePropertySourceLocator; -import org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration; -import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -/** - * Eureka-specific helper for config client that wants to lookup the config server via - * discovery. - * - * @author Dave Syer - */ -@ConditionalOnClass(ConfigServicePropertySourceLocator.class) -@ConditionalOnProperty(value = "spring.cloud.config.discovery.enabled", matchIfMissing = false) -@Configuration -@Import({ EurekaDiscoveryClientConfiguration.class, // this emulates @EnableDiscoveryClient, the import selector doesn't run before the bootstrap phase - EurekaClientAutoConfiguration.class }) -public class EurekaDiscoveryClientConfigServiceBootstrapConfiguration { -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/EurekaApplications.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/EurekaApplications.java deleted file mode 100644 index 44906b1b..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/EurekaApplications.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.http; - -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.netflix.discovery.shared.Application; -import com.netflix.discovery.shared.Applications; - -/** - * A simple wrapper class for {@link Applications} that insure proprer Jackson - * serialization through the JsonPropert overwrites. - * - * @author Daniel Lavoie - */ -public class EurekaApplications extends com.netflix.discovery.shared.Applications { - - @JsonCreator - public EurekaApplications(@JsonProperty("apps__hashcode") String appsHashCode, - @JsonProperty("versions__delta") Long versionDelta, - @JsonProperty("application") List registeredApplications) { - super(appsHashCode, versionDelta, registeredApplications); - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateDiscoveryClientOptionalArgs.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateDiscoveryClientOptionalArgs.java deleted file mode 100644 index b0eba96f..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateDiscoveryClientOptionalArgs.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.http; - -import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs; - -/** - * @author Daniel Lavoie - */ -public class RestTemplateDiscoveryClientOptionalArgs - extends AbstractDiscoveryClientOptionalArgs { - public RestTemplateDiscoveryClientOptionalArgs() { - setTransportClientFactories(new RestTemplateTransportClientFactories()); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateEurekaHttpClient.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateEurekaHttpClient.java deleted file mode 100644 index 12f205b4..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateEurekaHttpClient.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.http; - -import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.RestTemplate; - -import com.netflix.appinfo.InstanceInfo; -import com.netflix.appinfo.InstanceInfo.InstanceStatus; -import com.netflix.discovery.shared.Application; -import com.netflix.discovery.shared.Applications; -import com.netflix.discovery.shared.transport.EurekaHttpClient; -import com.netflix.discovery.shared.transport.EurekaHttpResponse; -import com.netflix.discovery.shared.transport.EurekaHttpResponse.EurekaHttpResponseBuilder; -import com.netflix.discovery.util.StringUtil; - -/** - * @author Daniel Lavoie - */ -public class RestTemplateEurekaHttpClient implements EurekaHttpClient { - - protected final Log logger = LogFactory.getLog(getClass()); - - private RestTemplate restTemplate; - private String serviceUrl; - - public RestTemplateEurekaHttpClient(RestTemplate restTemplate, String serviceUrl) { - this.restTemplate = restTemplate; - this.serviceUrl = serviceUrl; - } - - @Override - public EurekaHttpResponse register(InstanceInfo info) { - 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 response = restTemplate.exchange(urlPath, HttpMethod.POST, - new HttpEntity(info, headers), Void.class); - - return anEurekaHttpResponse(response.getStatusCodeValue()) - .headers(headersOf(response)).build(); - } - - @Override - public EurekaHttpResponse cancel(String appName, String id) { - String urlPath = serviceUrl + "apps/" + appName + '/' + id; - - ResponseEntity response = restTemplate.exchange(urlPath, HttpMethod.DELETE, - null, Void.class); - - return anEurekaHttpResponse(response.getStatusCodeValue()) - .headers(headersOf(response)).build(); - } - - @Override - public EurekaHttpResponse 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 response = restTemplate.exchange(urlPath, - HttpMethod.PUT, null, InstanceInfo.class); - - EurekaHttpResponseBuilder eurekaResponseBuilder = anEurekaHttpResponse( - response.getStatusCodeValue(), InstanceInfo.class) - .headers(headersOf(response)); - - if (response.hasBody()) - eurekaResponseBuilder.entity(response.getBody()); - - return eurekaResponseBuilder.build(); - } - - @Override - public EurekaHttpResponse statusUpdate(String appName, String id, - InstanceStatus newStatus, InstanceInfo info) { - String urlPath = serviceUrl + "apps/" + appName + '/' + id + "?status=" - + newStatus.name() + "&lastDirtyTimestamp=" - + info.getLastDirtyTimestamp().toString(); - - ResponseEntity response = restTemplate.exchange(urlPath, HttpMethod.PUT, - null, Void.class); - - return anEurekaHttpResponse(response.getStatusCodeValue()) - .headers(headersOf(response)).build(); - } - - @Override - public EurekaHttpResponse deleteStatusOverride(String appName, String id, - InstanceInfo info) { - String urlPath = serviceUrl + "apps/" + appName + '/' + id - + "/status?lastDirtyTimestamp=" + info.getLastDirtyTimestamp().toString(); - - ResponseEntity response = restTemplate.exchange(urlPath, HttpMethod.DELETE, - null, Void.class); - - return anEurekaHttpResponse(response.getStatusCodeValue()) - .headers(headersOf(response)).build(); - } - - @Override - public EurekaHttpResponse getApplications(String... regions) { - return getApplicationsInternal("apps/", regions); - } - - private EurekaHttpResponse getApplicationsInternal(String urlPath, - String[] regions) { - String url = serviceUrl + urlPath; - - if (regions != null && regions.length > 0) - urlPath = (urlPath.contains("?") ? "&" : "?") + "regions=" - + StringUtil.join(regions); - - ResponseEntity response = restTemplate.exchange(url, - HttpMethod.GET, null, EurekaApplications.class); - - return anEurekaHttpResponse(response.getStatusCodeValue(), - response.getStatusCode().value() == HttpStatus.OK.value() - && response.hasBody() ? (Applications) response.getBody() : null) - .headers(headersOf(response)).build(); - } - - @Override - public EurekaHttpResponse getDelta(String... regions) { - return getApplicationsInternal("apps/delta", regions); - } - - @Override - public EurekaHttpResponse getVip(String vipAddress, String... regions) { - return getApplicationsInternal("vips/" + vipAddress, regions); - } - - @Override - public EurekaHttpResponse getSecureVip(String secureVipAddress, - String... regions) { - return getApplicationsInternal("svips/" + secureVipAddress, regions); - } - - @Override - public EurekaHttpResponse getApplication(String appName) { - String urlPath = serviceUrl + "apps/" + appName; - - ResponseEntity response = restTemplate.exchange(urlPath, - HttpMethod.GET, null, Application.class); - - Application application = response.getStatusCodeValue() == HttpStatus.OK.value() - && response.hasBody() ? response.getBody() : null; - - return anEurekaHttpResponse(response.getStatusCodeValue(), application) - .headers(headersOf(response)).build(); - } - - @Override - public EurekaHttpResponse getInstance(String appName, String id) { - return getInstanceInternal("apps/" + appName + '/' + id); - } - - @Override - public EurekaHttpResponse getInstance(String id) { - return getInstanceInternal("instances/" + id); - } - - private EurekaHttpResponse getInstanceInternal(String urlPath) { - urlPath = serviceUrl + urlPath; - - ResponseEntity response = restTemplate.exchange(urlPath, - HttpMethod.GET, null, InstanceInfo.class); - - return anEurekaHttpResponse(response.getStatusCodeValue(), - response.getStatusCodeValue() == HttpStatus.OK.value() - && response.hasBody() ? response.getBody() : null) - .headers(headersOf(response)).build(); - } - - @Override - public void shutdown() { - // Nothing to do - } - - private static Map headersOf(ResponseEntity response) { - HttpHeaders httpHeaders = response.getHeaders(); - if (httpHeaders == null || httpHeaders.isEmpty()) { - return Collections.emptyMap(); - } - Map headers = new HashMap<>(); - for (Entry> entry : httpHeaders.entrySet()) { - if (!entry.getValue().isEmpty()) { - headers.put(entry.getKey(), entry.getValue().get(0)); - } - } - return headers; - } -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactories.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactories.java deleted file mode 100644 index d437703b..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactories.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.http; - -import java.util.Collection; -import java.util.Optional; - -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.EurekaClientConfig; -import com.netflix.discovery.shared.transport.TransportClientFactory; -import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClient; -import com.netflix.discovery.shared.transport.jersey.TransportClientFactories; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; - -/** - * @author Daniel Lavoie - */ -public class RestTemplateTransportClientFactories - implements TransportClientFactories { - - @Override - public TransportClientFactory newTransportClientFactory( - Collection additionalFilters, EurekaJerseyClient providedJerseyClient) { - throw new UnsupportedOperationException(); - } - - @Override - public TransportClientFactory newTransportClientFactory( - EurekaClientConfig clientConfig, Collection additionalFilters, - InstanceInfo myInstanceInfo) { - return new RestTemplateTransportClientFactory(); - } - - @Override - public TransportClientFactory newTransportClientFactory(final EurekaClientConfig clientConfig, - final Collection additionalFilters, - final InstanceInfo myInstanceInfo, - final Optional sslContext, - final Optional hostnameVerifier) { - return new RestTemplateTransportClientFactory(); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactory.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactory.java deleted file mode 100644 index 9258a311..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactory.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.http; - -import java.net.URI; -import java.net.URISyntaxException; - -import org.springframework.http.client.support.BasicAuthorizationInterceptor; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.BeanDescription; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.PropertyNamingStrategy; -import com.fasterxml.jackson.databind.SerializationConfig; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.databind.module.SimpleModule; -import com.fasterxml.jackson.databind.ser.BeanSerializerModifier; -import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.converters.jackson.mixin.ApplicationsJsonMixIn; -import com.netflix.discovery.converters.jackson.mixin.InstanceInfoJsonMixIn; -import com.netflix.discovery.converters.jackson.serializer.InstanceInfoJsonBeanSerializer; -import com.netflix.discovery.shared.Applications; -import com.netflix.discovery.shared.resolver.EurekaEndpoint; -import com.netflix.discovery.shared.transport.EurekaHttpClient; -import com.netflix.discovery.shared.transport.TransportClientFactory; - -/** - * Provides the custom {@link RestTemplate} required by the - * {@link RestTemplateEurekaHttpClient}. Relies on Jackson for serialization and - * deserialization. - * - * @author Daniel Lavoie - */ -public class RestTemplateTransportClientFactory implements TransportClientFactory { - - @Override - public EurekaHttpClient newClient(EurekaEndpoint serviceUrl) { - return new RestTemplateEurekaHttpClient(restTemplate(serviceUrl.getServiceUrl()), - serviceUrl.getServiceUrl()); - } - - private RestTemplate restTemplate(String serviceUrl) { - RestTemplate restTemplate = new RestTemplate(); - try { - URI serviceURI = new URI(serviceUrl); - if (serviceURI.getUserInfo() != null) { - String[] credentials = serviceURI.getUserInfo().split(":"); - if (credentials.length == 2) { - restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor( - credentials[0], credentials[1])); - } - } - } - catch (URISyntaxException ignore) { - - } - - restTemplate.getMessageConverters().add(0, mappingJacksonHttpMessageConverter()); - - return restTemplate; - } - - /** - * 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. Achived with - * {@link SerializationFeature.WRAP_ROOT_VALUE} and - * {@link DeserializationFeature.UNWRAP_ROOT_VALUE}. - * {@link PropertyNamingStrategy.SnakeCaseStrategy} is applied to the underlying - * {@link ObjectMapper}. - * - * - * @return - */ - public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() { - MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); - converter.setObjectMapper(new ObjectMapper() - .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)); - - SimpleModule jsonModule = new SimpleModule(); - jsonModule.setSerializerModifier(createJsonSerializerModifier());//keyFormatter, compact)); - converter.getObjectMapper().registerModule(jsonModule); - - converter.getObjectMapper().configure(SerializationFeature.WRAP_ROOT_VALUE, true); - converter.getObjectMapper().configure(DeserializationFeature.UNWRAP_ROOT_VALUE, - true); - converter.getObjectMapper().addMixIn(Applications.class, ApplicationsJsonMixIn.class); - converter.getObjectMapper().addMixIn(InstanceInfo.class, InstanceInfoJsonMixIn.class); - - // converter.getObjectMapper().addMixIn(DataCenterInfo.class, DataCenterInfoXmlMixIn.class); - // converter.getObjectMapper().addMixIn(InstanceInfo.PortWrapper.class, PortWrapperXmlMixIn.class); - // converter.getObjectMapper().addMixIn(Application.class, ApplicationXmlMixIn.class); - // converter.getObjectMapper().addMixIn(Applications.class, ApplicationsXmlMixIn.class); - - - return converter; - } - - public static BeanSerializerModifier createJsonSerializerModifier() {//final KeyFormatter keyFormatter, final boolean compactMode) { - return new BeanSerializerModifier() { - @Override - public JsonSerializer modifySerializer(SerializationConfig config, - BeanDescription beanDesc, JsonSerializer serializer) { - /*if (beanDesc.getBeanClass().isAssignableFrom(Applications.class)) { - return new ApplicationsJsonBeanSerializer((BeanSerializerBase) serializer, keyFormatter); - }*/ - if (beanDesc.getBeanClass().isAssignableFrom(InstanceInfo.class)) { - return new InstanceInfoJsonBeanSerializer((BeanSerializerBase) serializer, false); - } - return serializer; - } - }; - } - - @Override - public void shutdown() { - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/DefaultManagementMetadataProvider.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/DefaultManagementMetadataProvider.java deleted file mode 100644 index 4f19b003..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/DefaultManagementMetadataProvider.java +++ /dev/null @@ -1,97 +0,0 @@ -package org.springframework.cloud.netflix.eureka.metadata; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; -import org.springframework.util.StringUtils; - -import java.net.MalformedURLException; -import java.net.URL; - -public 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); - String statusPageUrl = getStatusPageUrl(instance, serverPort, serverContextPath, - managementContextPath, managementPort); - - return new ManagementMetadata(healthCheckUrl, statusPageUrl, managementPort == null ? serverPort : managementPort); - } - - private boolean isRandom(Integer port) { - return port != null && port == RANDOM_PORT; - } - - private String getHealthCheckUrl(EurekaInstanceConfigBean instance, int serverPort, String serverContextPath, - String managementContextPath, Integer managementPort) { - String healthCheckUrlPath = instance.getHealthCheckUrlPath(); - String healthCheckUrl = getUrl(instance, serverPort, serverContextPath, managementContextPath, - managementPort, healthCheckUrlPath); - 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); - 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) { - managementContextPath = refineManagementContextPath(serverContextPath, managementContextPath, managementPort); - if (managementPort == null) { - managementPort = serverPort; - } - String scheme = instance.getSecurePortEnabled() ? "https" : "http"; - return constructValidUrl(scheme, instance.getHostname(), managementPort, managementContextPath, urlPath); - } - - private String refineManagementContextPath(String serverContextPath, String managementContextPath, - Integer managementPort) { - if(managementContextPath != null) { - return managementContextPath; - } - if(managementPort != null) { - return "/"; - } - return serverContextPath; - } - - private String constructValidUrl(String scheme, String hostname, int port, - String contextPath, String statusPath) { - try { - if (!contextPath.endsWith("/")) { - contextPath = contextPath + "/"; - } - URL base = new URL(scheme, hostname, port, contextPath); - String refinedStatusPath = StringUtils.trimLeadingCharacter(statusPath, '/'); - return new URL(base, refinedStatusPath).toString(); - } catch (MalformedURLException e) { - String message = getErrorMessage(scheme, hostname, port, contextPath, statusPath); - throw new IllegalStateException(message, e); - } - } - - 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); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/ManagementMetadata.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/ManagementMetadata.java deleted file mode 100644 index baa4a4ac..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/ManagementMetadata.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.springframework.cloud.netflix.eureka.metadata; - -import java.util.Objects; - -public class ManagementMetadata { - - private final String healthCheckUrl; - private final String statusPageUrl; - private final Integer managementPort; - - public ManagementMetadata(String healthCheckUrl, String statusPageUrl, Integer managementPort) { - this.healthCheckUrl = healthCheckUrl; - this.statusPageUrl = statusPageUrl; - this.managementPort = managementPort; - } - - public String getHealthCheckUrl() { - return healthCheckUrl; - } - - public String getStatusPageUrl() { - return statusPageUrl; - } - - public Integer getManagementPort() { - return managementPort; - } - - @Override - public boolean equals(Object o) { - 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); - } - - @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(); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/ManagementMetadataProvider.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/ManagementMetadataProvider.java deleted file mode 100644 index 98bc770e..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/ManagementMetadataProvider.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.springframework.cloud.netflix.eureka.metadata; - -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; - -public interface ManagementMetadataProvider { - - ManagementMetadata get(EurekaInstanceConfigBean instance, int serverPort, - String serverContextPath, String managementContextPath, Integer managementPort); - -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaAutoServiceRegistration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaAutoServiceRegistration.java deleted file mode 100644 index 984842ef..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaAutoServiceRegistration.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.eureka.serviceregistry; - -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent; -import org.springframework.cloud.client.discovery.event.InstanceRegisteredEvent; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistration; -import org.springframework.context.ApplicationContext; -import org.springframework.context.SmartLifecycle; -import org.springframework.context.event.ContextClosedEvent; -import org.springframework.context.event.EventListener; -import org.springframework.core.Ordered; - -/** - * @author Dave Syer - * @author Spencer Gibb - * @author Jon Schneider - * @author Jakub Narloch - * @author raiyan - */ -public class EurekaAutoServiceRegistration implements AutoServiceRegistration, SmartLifecycle, Ordered { - - private static final Log log = LogFactory.getLog(EurekaAutoServiceRegistration.class); - - private AtomicBoolean running = new AtomicBoolean(false); - - private int order = 0; - - private AtomicInteger port = new AtomicInteger(0); - - private ApplicationContext context; - - private EurekaServiceRegistry serviceRegistry; - - private EurekaRegistration registration; - - public EurekaAutoServiceRegistration(ApplicationContext context, EurekaServiceRegistry serviceRegistry, EurekaRegistration registration) { - this.context = context; - this.serviceRegistry = serviceRegistry; - this.registration = registration; - } - - @Override - public void start() { - // only set the port if the nonSecurePort or securePort is 0 and this.port != 0 - if (this.port.get() != 0) { - if (this.registration.getNonSecurePort() == 0) { - this.registration.setNonSecurePort(this.port.get()); - } - - if (this.registration.getSecurePort() == 0 && this.registration.isSecure()) { - this.registration.setSecurePort(this.port.get()); - } - } - - // only initialize if nonSecurePort is greater than 0 and it isn't already running - // because of containerPortInitializer below - if (!this.running.get() && this.registration.getNonSecurePort() > 0) { - - this.serviceRegistry.register(this.registration); - - this.context.publishEvent( - new InstanceRegisteredEvent<>(this, this.registration.getInstanceConfig())); - this.running.set(true); - } - } - @Override - public void stop() { - this.serviceRegistry.deregister(this.registration); - this.running.set(false); - } - - @Override - public boolean isRunning() { - return this.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 this.order; - } - - @EventListener(ServletWebServerInitializedEvent.class) - public void onApplicationEvent(ServletWebServerInitializedEvent event) { - // TODO: take SSL into account - int localPort = event.getWebServer().getPort(); - if (this.port.get() == 0) { - log.info("Updating port to " + localPort); - this.port.compareAndSet(0, localPort); - start(); - } - } - - @EventListener(ContextClosedEvent.class) - public void onApplicationEvent(ContextClosedEvent event) { - if( event.getApplicationContext() == context ) { - stop(); - } - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaRegistration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaRegistration.java deleted file mode 100644 index 76e0b9a6..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaRegistration.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.eureka.serviceregistry; - -import java.io.Closeable; -import java.io.IOException; -import java.net.URI; -import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.aop.framework.Advised; -import org.springframework.aop.support.AopUtils; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.cloud.client.DefaultServiceInstance; -import org.springframework.cloud.client.serviceregistry.Registration; -import org.springframework.cloud.netflix.eureka.CloudEurekaClient; -import org.springframework.cloud.netflix.eureka.CloudEurekaInstanceConfig; -import org.springframework.cloud.netflix.eureka.InstanceInfoFactory; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.util.Assert; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.HealthCheckHandler; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.EurekaClientConfig; - -/** - * @author Spencer Gibb - */ -public class EurekaRegistration implements Registration, Closeable { - private static final Log log = LogFactory.getLog(EurekaRegistration.class); - - private final EurekaClient eurekaClient; - private final AtomicReference cloudEurekaClient = new AtomicReference<>(); - private final CloudEurekaInstanceConfig instanceConfig; - private final ApplicationInfoManager applicationInfoManager; - private ObjectProvider healthCheckHandler; - - private EurekaRegistration(CloudEurekaInstanceConfig instanceConfig, EurekaClient eurekaClient, ApplicationInfoManager applicationInfoManager, ObjectProvider healthCheckHandler) { - this.eurekaClient = eurekaClient; - this.instanceConfig = instanceConfig; - this.applicationInfoManager = applicationInfoManager; - this.healthCheckHandler = healthCheckHandler; - } - - public static Builder builder(CloudEurekaInstanceConfig instanceConfig) { - return new Builder(instanceConfig); - } - - public static class Builder { - private final CloudEurekaInstanceConfig instanceConfig; - private ApplicationInfoManager applicationInfoManager; - private EurekaClient eurekaClient; - private ObjectProvider healthCheckHandler; - - private EurekaClientConfig clientConfig; - private ApplicationEventPublisher publisher; - - 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) { - this.healthCheckHandler = healthCheckHandler; - return this; - } - - public Builder with(EurekaClientConfig clientConfig, ApplicationEventPublisher publisher) { - this.clientConfig = clientConfig; - this.publisher = publisher; - return this; - } - - public EurekaRegistration build() { - 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"); - - this.eurekaClient = new CloudEurekaClient(this.applicationInfoManager, this.clientConfig, this.publisher); - } - return new EurekaRegistration(instanceConfig, eurekaClient, applicationInfoManager, healthCheckHandler); - } - - } - - @Override - public String getServiceId() { - return this.instanceConfig.getAppname(); - } - - @Override - public String getHost() { - return this.instanceConfig.getHostName(false); - } - - @Override - public int getPort() { - if (this.instanceConfig.getSecurePortEnabled()) { - return this.instanceConfig.getSecurePort(); - } - return this.instanceConfig.getNonSecurePort(); - } - - @Override - public boolean isSecure() { - return this.instanceConfig.getSecurePortEnabled(); - } - - @Override - public URI getUri() { - return DefaultServiceInstance.getUri(this); - } - - @Override - public Map getMetadata() { - return this.instanceConfig.getMetadataMap(); - } - - public CloudEurekaClient getEurekaClient() { - if (this.cloudEurekaClient.get() == null) { - try { - this.cloudEurekaClient.compareAndSet(null, getTargetObject(eurekaClient, CloudEurekaClient.class)); - } catch (Exception e) { - log.error("error getting CloudEurekaClient", e); - } - } - return this.cloudEurekaClient.get(); - } - - @SuppressWarnings({"unchecked"}) - protected T getTargetObject(Object proxy, Class targetClass) throws Exception { - if (AopUtils.isJdkDynamicProxy(proxy)) { - return (T) ((Advised) proxy).getTargetSource().getTarget(); - } else { - return (T) proxy; // expected to be cglib proxy then, which is simply a specialized class - } - } - - public CloudEurekaInstanceConfig getInstanceConfig() { - return instanceConfig; - } - - public ApplicationInfoManager getApplicationInfoManager() { - return applicationInfoManager; - } - - public ObjectProvider getHealthCheckHandler() { - return healthCheckHandler; - } - - public void setHealthCheckHandler(ObjectProvider healthCheckHandler) { - this.healthCheckHandler = healthCheckHandler; - } - - public void setNonSecurePort(int port) { - this.instanceConfig.setNonSecurePort(port); - } - - public int getNonSecurePort() { - return this.instanceConfig.getNonSecurePort(); - } - - public void setSecurePort(int port) { - this.instanceConfig.setSecurePort(port); - } - - public int getSecurePort() { - return this.instanceConfig.getSecurePort(); - } - - @Override - public void close() throws IOException { - this.eurekaClient.shutdown(); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaServiceRegistry.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaServiceRegistry.java deleted file mode 100644 index 47b4ddbb..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaServiceRegistry.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.eureka.serviceregistry; - -import java.util.HashMap; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.client.serviceregistry.ServiceRegistry; - -import com.netflix.appinfo.InstanceInfo; - -import static com.netflix.appinfo.InstanceInfo.InstanceStatus.UNKNOWN; - -/** - * @author Spencer Gibb - */ -public class EurekaServiceRegistry implements ServiceRegistry { - - private static final Log log = LogFactory.getLog(EurekaServiceRegistry.class); - - @Override - public void register(EurekaRegistration reg) { - maybeInitializeClient(reg); - - if (log.isInfoEnabled()) { - log.info("Registering application " + reg.getInstanceConfig().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) { - if (reg.getApplicationInfoManager().getInfo() != null) { - - if (log.isInfoEnabled()) { - log.info("Unregistering application " + reg.getInstanceConfig().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() - } - } - - @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); - } - - @Override - public Object getStatus(EurekaRegistration registration) { - String appname = registration.getInstanceConfig().getAppname(); - String instanceId = registration.getInstanceConfig().getInstanceId(); - InstanceInfo info = registration.getEurekaClient().getInstanceInfo(appname, instanceId); - - HashMap 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() { - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/ConditionalOnRibbonAndEurekaEnabled.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/ConditionalOnRibbonAndEurekaEnabled.java deleted file mode 100644 index 5df8b539..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/ConditionalOnRibbonAndEurekaEnabled.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.springframework.cloud.netflix.ribbon.eureka; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.springframework.boot.autoconfigure.condition.AllNestedConditions; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.context.annotation.Conditional; - -import com.netflix.discovery.EurekaClient; -import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList; - -@Target({ElementType.TYPE, ElementType.METHOD}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Conditional(ConditionalOnRibbonAndEurekaEnabled.OnRibbonAndEurekaEnabledCondition.class) -public @interface ConditionalOnRibbonAndEurekaEnabled { - - class OnRibbonAndEurekaEnabledCondition extends AllNestedConditions { - - public OnRibbonAndEurekaEnabledCondition() { - super(ConfigurationPhase.REGISTER_BEAN); - } - - @ConditionalOnClass(DiscoveryEnabledNIWSServerList.class) - @ConditionalOnBean(SpringClientFactory.class) - @ConditionalOnProperty(value = "ribbon.eureka.enabled", matchIfMissing = true) - static class Defaults {} - - @ConditionalOnBean(EurekaClient.class) - static class EurekaBeans {} - - @ConditionalOnProperty(value = "eureka.client.enabled", matchIfMissing = true) - static class OnEurekaClientEnabled {} - } -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/DomainExtractingServerList.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/DomainExtractingServerList.java deleted file mode 100644 index 714e57a4..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/DomainExtractingServerList.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.eureka; - -import java.util.ArrayList; -import java.util.List; - -import org.springframework.cloud.netflix.ribbon.RibbonProperties; - -import com.netflix.appinfo.InstanceInfo; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; - -/** - * @author Dave Syer - */ -public class DomainExtractingServerList implements ServerList { - - private ServerList list; - private final RibbonProperties ribbon; - - private boolean approximateZoneFromHostname; - - public DomainExtractingServerList(ServerList list, - IClientConfig clientConfig, boolean approximateZoneFromHostname) { - this.list = list; - this.ribbon = RibbonProperties.from(clientConfig); - this.approximateZoneFromHostname = approximateZoneFromHostname; - } - - @Override - public List getInitialListOfServers() { - List servers = setZones(this.list - .getInitialListOfServers()); - return servers; - } - - @Override - public List getUpdatedListOfServers() { - List servers = setZones(this.list - .getUpdatedListOfServers()); - return servers; - } - - private List setZones(List servers) { - List result = new ArrayList<>(); - boolean isSecure = this.ribbon.isSecure(true); - boolean shouldUseIpAddr = this.ribbon.isUseIPAddrForServer(); - for (DiscoveryEnabledServer server : servers) { - result.add(new DomainExtractingServer(server, isSecure, shouldUseIpAddr, - this.approximateZoneFromHostname)); - } - return result; - } - -} - -class DomainExtractingServer extends DiscoveryEnabledServer { - - private String id; - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) { - this.id = id; - } - - public DomainExtractingServer(DiscoveryEnabledServer server, boolean useSecurePort, - boolean useIpAddr, boolean approximateZoneFromHostname) { - // host and port are set in super() - super(server.getInstanceInfo(), useSecurePort, useIpAddr); - if (server.getInstanceInfo().getMetadata().containsKey("zone")) { - setZone(server.getInstanceInfo().getMetadata().get("zone")); - } - else if (approximateZoneFromHostname) { - setZone(ZoneUtils.extractApproximateZone(server.getHost())); - } - else { - setZone(server.getZone()); - } - setId(extractId(server)); - setAlive(server.isAlive()); - setReadyToServe(server.isReadyToServe()); - } - - private String extractId(Server server) { - if (server instanceof DiscoveryEnabledServer) { - DiscoveryEnabledServer enabled = (DiscoveryEnabledServer) server; - InstanceInfo instance = enabled.getInstanceInfo(); - if (instance.getMetadata().containsKey("instanceId")) { - return instance.getHostName()+":"+instance.getMetadata().get("instanceId"); - } - } - return super.getId(); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientConfiguration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientConfiguration.java deleted file mode 100644 index 512d3b19..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientConfiguration.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.eureka; - -import javax.annotation.PostConstruct; -import javax.inject.Provider; - -import com.netflix.discovery.EurekaClient; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.cloud.netflix.ribbon.PropertiesFactory; -import org.springframework.cloud.netflix.ribbon.RibbonClientName; -import org.springframework.cloud.netflix.ribbon.RibbonUtils; -import org.springframework.cloud.netflix.ribbon.ServerIntrospector; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.StringUtils; - -import com.netflix.appinfo.EurekaInstanceConfig; -import com.netflix.client.config.IClientConfig; -import com.netflix.config.ConfigurationManager; -import com.netflix.config.DeploymentContext.ContextKey; -import com.netflix.discovery.EurekaClientConfig; -import com.netflix.loadbalancer.IPing; -import com.netflix.loadbalancer.ServerList; -import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList; -import com.netflix.niws.loadbalancer.NIWSDiscoveryPing; - -/** - * Preprocessor that configures defaults for eureka-discovered ribbon clients. Such as: - * @zone, NIWSServerListClassName, DeploymentContextBasedVipAddresses, - * NFLoadBalancerRuleClassName, NIWSServerListFilterClassName and more - * - * @author Spencer Gibb - * @author Dave Syer - * @author Ryan Baxter - */ -@Configuration -public class EurekaRibbonClientConfiguration { - - private static final Log log = LogFactory.getLog(EurekaRibbonClientConfiguration.class); - - @Value("${ribbon.eureka.approximateZoneFromHostname:false}") - private boolean approximateZoneFromHostname = false; - - @RibbonClientName - private String serviceId = "client"; - - @Autowired(required = false) - private EurekaClientConfig clientConfig; - - @Autowired(required = false) - private EurekaInstanceConfig eurekaConfig; - - @Autowired - private PropertiesFactory propertiesFactory; - - public EurekaRibbonClientConfiguration() { - } - - public EurekaRibbonClientConfiguration(EurekaClientConfig clientConfig, - String serviceId, EurekaInstanceConfig eurekaConfig, - boolean approximateZoneFromHostname) { - this.clientConfig = clientConfig; - this.serviceId = serviceId; - this.eurekaConfig = eurekaConfig; - this.approximateZoneFromHostname = approximateZoneFromHostname; - } - - @Bean - @ConditionalOnMissingBean - public IPing ribbonPing(IClientConfig config) { - if (this.propertiesFactory.isSet(IPing.class, serviceId)) { - return this.propertiesFactory.get(IPing.class, config, serviceId); - } - NIWSDiscoveryPing ping = new NIWSDiscoveryPing(); - ping.initWithNiwsConfig(config); - return ping; - } - - @Bean - @ConditionalOnMissingBean - public ServerList ribbonServerList(IClientConfig config, Provider eurekaClientProvider) { - if (this.propertiesFactory.isSet(ServerList.class, serviceId)) { - return this.propertiesFactory.get(ServerList.class, config, serviceId); - } - DiscoveryEnabledNIWSServerList discoveryServerList = new DiscoveryEnabledNIWSServerList( - config, eurekaClientProvider); - DomainExtractingServerList serverList = new DomainExtractingServerList( - discoveryServerList, config, this.approximateZoneFromHostname); - return serverList; - } - - @Bean - public ServerIntrospector serverIntrospector() { - return new EurekaServerIntrospector(); - } - - @PostConstruct - public void preprocess() { - String zone = ConfigurationManager.getDeploymentContext() - .getValue(ContextKey.zone); - if (this.clientConfig != null && StringUtils.isEmpty(zone)) { - if (this.approximateZoneFromHostname && this.eurekaConfig != null) { - String approxZone = ZoneUtils - .extractApproximateZone(this.eurekaConfig.getHostName(false)); - log.debug("Setting Zone To " + approxZone); - ConfigurationManager.getDeploymentContext().setValue(ContextKey.zone, - approxZone); - } - else { - String availabilityZone = this.eurekaConfig == null ? null - : this.eurekaConfig.getMetadataMap().get("zone"); - if (availabilityZone == null) { - String[] zones = this.clientConfig - .getAvailabilityZones(this.clientConfig.getRegion()); - // Pick the first one from the regions we want to connect to - availabilityZone = zones != null && zones.length > 0 ? zones[0] - : null; - } - if (availabilityZone != null) { - // You can set this with archaius.deployment.* (maybe requires - // custom deployment context)? - ConfigurationManager.getDeploymentContext().setValue(ContextKey.zone, - availabilityZone); - } - } - } - RibbonUtils.initializeRibbonDefaults(serviceId); - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaServerIntrospector.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaServerIntrospector.java deleted file mode 100644 index 4bf4f74a..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaServerIntrospector.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.eureka; - -import java.util.Map; - -import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector; - -import com.netflix.appinfo.InstanceInfo; -import com.netflix.loadbalancer.Server; -import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; - -/** - * @author Spencer Gibb - */ -public class EurekaServerIntrospector extends DefaultServerIntrospector { - - @Override - public boolean isSecure(Server server) { - if (server instanceof DiscoveryEnabledServer) { - DiscoveryEnabledServer discoveryServer = (DiscoveryEnabledServer) server; - return discoveryServer.getInstanceInfo().isPortEnabled(InstanceInfo.PortType.SECURE); - } - return super.isSecure(server); - } - - @Override - public Map getMetadata(Server server) { - if (server instanceof DiscoveryEnabledServer) { - DiscoveryEnabledServer discoveryServer = (DiscoveryEnabledServer) server; - return discoveryServer.getInstanceInfo().getMetadata(); - } - return super.getMetadata(server); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonEurekaAutoConfiguration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonEurekaAutoConfiguration.java deleted file mode 100644 index 0419690a..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonEurekaAutoConfiguration.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.eureka; - -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.context.annotation.Configuration; - -/** - * Spring configuration for configuring Ribbon defaults to be Eureka based - * if Eureka client is enabled - * - * @author Dave Syer - * @author Biju Kunjummen - */ -@Configuration -@EnableConfigurationProperties -@ConditionalOnRibbonAndEurekaEnabled -@AutoConfigureAfter(RibbonAutoConfiguration.class) -@RibbonClients(defaultConfiguration = EurekaRibbonClientConfiguration.class) -public class RibbonEurekaAutoConfiguration { - - -} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/ZoneUtils.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/ZoneUtils.java deleted file mode 100644 index fa8677a5..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/ZoneUtils.java +++ /dev/null @@ -1,37 +0,0 @@ -/* Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.cloud.netflix.ribbon.eureka; - -import org.springframework.util.StringUtils; - -/** - * Utility class for dealing with zones. - * @author Ryan Baxter - * - */ -public class ZoneUtils { - - /** - * 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) { - String[] split = StringUtils.split(host, "."); - return split == null ? host : split[1]; - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/main/resources/META-INF/spring.factories b/spring-cloud-netflix-eureka-client/src/main/resources/META-INF/spring.factories deleted file mode 100644 index e8c77025..00000000 --- a/spring-cloud-netflix-eureka-client/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,10 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -org.springframework.cloud.netflix.eureka.config.EurekaClientConfigServerAutoConfiguration,\ -org.springframework.cloud.netflix.eureka.config.EurekaDiscoveryClientConfigServiceAutoConfiguration,\ -org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration,\ -org.springframework.cloud.netflix.ribbon.eureka.RibbonEurekaAutoConfiguration,\ -org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration - -org.springframework.cloud.bootstrap.BootstrapConfiguration=\ -org.springframework.cloud.netflix.eureka.config.EurekaDiscoveryClientConfigServiceBootstrapConfiguration - diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/ConditionalOnRefreshScopeTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/ConditionalOnRefreshScopeTests.java deleted file mode 100644 index f94d8ce5..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/ConditionalOnRefreshScopeTests.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -import org.junit.Test; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; -import org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration.ConditionalOnRefreshScope; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Dave Syer - * @author Biju Kunjummen - */ -public class ConditionalOnRefreshScopeTests { - - @Test - public void refreshScopeIncluded() { - new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RefreshAutoConfiguration.class)) - .withUserConfiguration(Beans.class).run(c -> { - assertThat(c).hasSingleBean( - org.springframework.cloud.context.scope.refresh.RefreshScope.class); - assertThat(c.getBean("foo")).isEqualTo("foo"); - }); - } - - @Test - public void refreshScopeNotIncluded() { - new ApplicationContextRunner().withUserConfiguration(Beans.class).run(c -> { - assertThat(c).doesNotHaveBean("foo"); - }); - } - - @Configuration - protected static class Beans { - @Bean - @ConditionalOnRefreshScope - public String foo() { - return "foo"; - } - } - -} \ No newline at end of file diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfigurationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfigurationTests.java deleted file mode 100644 index 913f73d9..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfigurationTests.java +++ /dev/null @@ -1,568 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -import java.io.IOException; -import java.util.concurrent.CountDownLatch; -import java.util.HashMap; -import java.util.Map; - -import org.junit.After; -import org.junit.Test; -import org.mockito.Mockito; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.SearchStrategy; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.context.properties.source.ConfigurationPropertySources; -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; -import org.springframework.cloud.commons.util.UtilAutoConfiguration; -import org.springframework.cloud.context.scope.GenericScope; -import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.MutablePropertySources; -import org.springframework.core.env.SystemEnvironmentPropertySource; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.EurekaClientConfig; -import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClient; -import com.sun.jersey.client.apache4.ApacheHttpClient4; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.springframework.boot.test.util.EnvironmentTestUtils.addEnvironment; - -/** - * @author Spencer Gibb - * @author Matt Jenkins - */ -public class EurekaClientAutoConfigurationTests { - private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - - @After - public void after() { - if (this.context != null && this.context.isActive()) { - this.context.close(); - } - } - - private void setupContext(Class... config) { - ConfigurationPropertySources.attach(this.context.getEnvironment()); - this.context.register(PropertyPlaceholderAutoConfiguration.class, EurekaDiscoveryClientConfiguration.class); - for (Class value : config) { - this.context.register(value); - } - this.context.register(TestConfiguration.class); - this.context.refresh(); - } - - @Test - public void shouldSetManagementPortInMetadataMapIfEqualToServerPort() throws Exception { - addEnvironment(this.context, "server.port=8989"); - setupContext(RefreshAutoConfiguration.class); - - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - - assertEquals("8989", instance.getMetadataMap().get("management.port")); - } - - @Test - public void shouldNotSetManagementAndJmxPortsInMetadataMap() throws Exception { - addEnvironment(this.context, "server.port=8989", "management.server.port=0"); - setupContext(RefreshAutoConfiguration.class); - - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - - assertEquals(null, instance.getMetadataMap().get("management.port")); - assertEquals(null, instance.getMetadataMap().get("jmx.port")); - } - - @Test - public void shouldSetManagementAndJmxPortsInMetadataMap() throws Exception { - addEnvironment(this.context, "management.server.port=9999", - "com.sun.management.jmxremote.port=6789"); - setupContext(RefreshAutoConfiguration.class); - - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - assertEquals("9999", instance.getMetadataMap().get("management.port")); - assertEquals("6789", instance.getMetadataMap().get("jmx.port")); - } - - @Test - public void shouldNotResetManagementAndJmxPortsInMetadataMap() throws Exception { - addEnvironment(this.context, "management.server.port=9999", - "eureka.instance.metadata-map.jmx.port=9898", - "eureka.instance.metadata-map.management.port=7878"); - setupContext(RefreshAutoConfiguration.class); - - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - assertEquals("7878", instance.getMetadataMap().get("management.port")); - assertEquals("9898", instance.getMetadataMap().get("jmx.port")); - } - - @Test - public void nonSecurePortPeriods() { - testNonSecurePort("server.port"); - } - - @Test - public void nonSecurePortUnderscores() { - testNonSecurePortSystemProp("SERVER_PORT"); - } - - @Test - public void nonSecurePort() { - testNonSecurePortSystemProp("PORT"); - assertEquals("eurekaClient", - this.context.getBeanDefinition("eurekaClient").getFactoryMethodName()); - } - - @Test - public void securePortPeriods() { - testSecurePort("server.port"); - } - - @Test - public void securePortUnderscores() { - TestPropertyValues.of("eureka.instance.secure-port-enabled=true").applyTo(this.context); - addSystemEnvironment(this.context.getEnvironment(), "SERVER_PORT:8443"); - setupContext(); - assertEquals(8443, getInstanceConfig().getSecurePort()); - } - - @Test - public void securePort() { - testSecurePort("PORT"); - assertEquals("eurekaClient", - this.context.getBeanDefinition("eurekaClient").getFactoryMethodName()); - } - - @Test - public void managementPort() { - TestPropertyValues.of("server.port=8989", - "management.server.port=9999").applyTo(this.context); - setupContext(RefreshAutoConfiguration.class); - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().contains("9999")); - } - - @Test - public void statusPageUrlPathAndManagementPort() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", - "eureka.instance.statusPageUrlPath=/myStatusPage").applyTo(this.context); - setupContext(RefreshAutoConfiguration.class); - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().contains("/myStatusPage")); - } - - @Test - public void healthCheckUrlPathAndManagementPort() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", - "eureka.instance.healthCheckUrlPath=/myHealthCheck").applyTo(this.context); - setupContext(RefreshAutoConfiguration.class); - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong health check: " + instance.getHealthCheckUrl(), - instance.getHealthCheckUrl().contains("/myHealthCheck")); - } - - @Test - public void statusPageUrl_and_healthCheckUrl_do_not_contain_server_context_path() throws Exception { - addEnvironment(this.context, "server.port=8989", - "management.server.port=9999", "server.contextPath=/service"); - - setupContext(RefreshAutoConfiguration.class); - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().endsWith(":9999/info")); - assertTrue("Wrong health check: " + instance.getHealthCheckUrl(), - instance.getHealthCheckUrl().endsWith(":9999/health")); - } - - @Test - public void statusPageUrl_and_healthCheckUrl_contain_management_context_path() throws Exception { - addEnvironment(this.context, - "server.port=8989", "management.server.context-path=/management"); - - setupContext(RefreshAutoConfiguration.class); - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().endsWith(":8989/management/info")); - assertTrue("Wrong health check: " + instance.getHealthCheckUrl(), - instance.getHealthCheckUrl().endsWith(":8989/management/health")); - } - - @Test - public void statusPageUrlPathAndManagementPortAndContextPath() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", "management.server.context-path=/manage", - "eureka.instance.status-page-url-path=/myStatusPage").applyTo(this.context); - setupContext(RefreshAutoConfiguration.class); - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().endsWith(":9999/manage/myStatusPage")); - } - - @Test - public void healthCheckUrlPathAndManagementPortAndContextPath() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", "management.server.context-path=/manage", - "eureka.instance.health-check-url-path=/myHealthCheck").applyTo(this.context); - setupContext(RefreshAutoConfiguration.class); - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong health check: " + instance.getHealthCheckUrl(), - instance.getHealthCheckUrl().endsWith(":9999/manage/myHealthCheck")); - } - - @Test - public void statusPageUrlPathAndManagementPortAndContextPathKebobCase() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", "management.server.context-path=/manage", - "eureka.instance.status-page-url-path=/myStatusPage").applyTo(this.context); - setupContext(RefreshAutoConfiguration.class); - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().endsWith(":9999/manage/myStatusPage")); - } - - @Test - public void healthCheckUrlPathAndManagementPortAndContextPathKebobCase() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", "management.server.context-path=/manage", - "eureka.instance.health-check-url-path=/myHealthCheck").applyTo(this.context); - setupContext(RefreshAutoConfiguration.class); - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong health check: " + instance.getHealthCheckUrl(), - instance.getHealthCheckUrl().endsWith(":9999/manage/myHealthCheck")); - } - - @Test - public void statusPageUrlPathAndManagementPortKabobCase() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", - "eureka.instance.status-page-url-path=/myStatusPage").applyTo(this.context); - setupContext(RefreshAutoConfiguration.class); - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().contains("/myStatusPage")); - } - - @Test - public void statusPageUrlAndPreferIpAddress() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", "eureka.instance.hostname=foo", - "eureka.instance.preferIpAddress:true").applyTo(this.context); - - setupContext(RefreshAutoConfiguration.class); - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - - assertEquals("statusPageUrl is wrong", "http://" + instance.getIpAddress() + ":9999/info", - instance.getStatusPageUrl()); - assertEquals("healthCheckUrl is wrong", "http://" + instance.getIpAddress() + ":9999/health", - instance.getHealthCheckUrl()); - } - - @Test - public void statusPageAndHealthCheckUrlsShouldSetUserDefinedIpAddress() { - addEnvironment(this.context, "server.port=8989", - "management.server.port=9999", "eureka.instance.hostname=foo", - "eureka.instance.ipAddress:192.168.13.90", - "eureka.instance.preferIpAddress:true"); - - setupContext(RefreshAutoConfiguration.class); - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - - assertEquals("statusPageUrl is wrong", "http://192.168.13.90:9999/info", - instance.getStatusPageUrl()); - assertEquals("healthCheckUrl is wrong", "http://192.168.13.90:9999/health", - instance.getHealthCheckUrl()); - } - - @Test - public void healthCheckUrlPathAndManagementPortKabobCase() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", - "eureka.instance.health-check-url-path=/myHealthCheck").applyTo(this.context); - setupContext(RefreshAutoConfiguration.class); - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong health check: " + instance.getHealthCheckUrl(), - instance.getHealthCheckUrl().contains("/myHealthCheck")); - } - - @Test - public void statusPageUrlPathAndManagementPortUpperCase() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999").applyTo(this.context); - addSystemEnvironment(this.context.getEnvironment(), "EUREKA_INSTANCE_STATUS_PAGE_URL_PATH=/myStatusPage"); - setupContext(RefreshAutoConfiguration.class); - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().contains("/myStatusPage")); - } - - @Test - public void healthCheckUrlPathAndManagementPortUpperCase() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999").applyTo(this.context); - addSystemEnvironment(this.context.getEnvironment(), "EUREKA_INSTANCE_HEALTH_CHECK_URL_PATH=/myHealthCheck"); - setupContext(RefreshAutoConfiguration.class); - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong health check: " + instance.getHealthCheckUrl(), - instance.getHealthCheckUrl().contains("/myHealthCheck")); - } - - @Test - public void hostname() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", "eureka.instance.hostname=foo").applyTo(this.context); - setupContext(RefreshAutoConfiguration.class); - EurekaInstanceConfigBean instance = this.context - .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().contains("foo")); - } - - @Test - public void refreshScopedBeans() { - setupContext(RefreshAutoConfiguration.class); - assertThat(this.context.getBeanDefinition("eurekaClient").getBeanClassName()) - .startsWith(GenericScope.class.getName()+"$LockedScopedProxyFactoryBean"); - assertThat(this.context.getBeanDefinition("eurekaApplicationInfoManager").getBeanClassName()) - .startsWith(GenericScope.class.getName()+"$LockedScopedProxyFactoryBean"); - } - - @Test - public void basicAuth() { - TestPropertyValues.of( "server.port=8989", - "eureka.client.serviceUrl.defaultZone=http://user:foo@example.com:80/eureka").applyTo(this.context); - setupContext(MockClientConfiguration.class); - // ApacheHttpClient4 http = this.context.getBean(ApacheHttpClient4.class); - // Mockito.verify(http).addFilter(Matchers.any(HTTPBasicAuthFilter.class)); - } - - @Test - public void testDefaultAppName() throws Exception { - setupContext(); - assertEquals("unknown", getInstanceConfig().getAppname()); - assertEquals("unknown", getInstanceConfig().getVirtualHostName()); - assertEquals("unknown", getInstanceConfig().getSecureVirtualHostName()); - } - - @Test - public void testAppName() throws Exception { - TestPropertyValues.of( "spring.application.name=mytest").applyTo(this.context); - setupContext(); - assertEquals("mytest", getInstanceConfig().getAppname()); - assertEquals("mytest", getInstanceConfig().getVirtualHostName()); - assertEquals("mytest", getInstanceConfig().getSecureVirtualHostName()); - } - - @Test - public void testAppNameUpper() throws Exception { - addSystemEnvironment(this.context.getEnvironment(), "SPRING_APPLICATION_NAME=mytestupper"); - setupContext(); - assertEquals("mytestupper", getInstanceConfig().getAppname()); - assertEquals("mytestupper", getInstanceConfig().getVirtualHostName()); - assertEquals("mytestupper", getInstanceConfig().getSecureVirtualHostName()); - } - - private void addSystemEnvironment(ConfigurableEnvironment environment, String... pairs) { - MutablePropertySources sources = environment.getPropertySources(); - Map map = getOrAdd(sources, "testsysenv"); - for (String pair : pairs) { - int index = getSeparatorIndex(pair); - String key = pair.substring(0, index > 0 ? index : pair.length()); - String value = index > 0 ? pair.substring(index + 1) : ""; - map.put(key.trim(), value.trim()); - } - } - - @SuppressWarnings("unchecked") - private static Map getOrAdd(MutablePropertySources sources, - String name) { - if (sources.contains(name)) { - return (Map) sources.get(name).getSource(); - } - Map map = new HashMap<>(); - sources.addFirst(new SystemEnvironmentPropertySource(name, map)); - return map; - } - - private static int getSeparatorIndex(String pair) { - int colonIndex = pair.indexOf(":"); - int equalIndex = pair.indexOf("="); - if (colonIndex == -1) { - return equalIndex; - } - if (equalIndex == -1) { - return colonIndex; - } - return Math.min(colonIndex, equalIndex); - } - - @Test - public void testInstanceNamePreferred() throws Exception { - addSystemEnvironment(this.context.getEnvironment(), "SPRING_APPLICATION_NAME=mytestspringappname"); - TestPropertyValues.of( "eureka.instance.appname=mytesteurekaappname").applyTo(this.context); - setupContext(); - assertEquals("mytesteurekaappname", getInstanceConfig().getAppname()); - } - - @Test - public void eurekaHealthIndicatorCreated() { - setupContext(); - this.context.getBean(EurekaHealthIndicator.class); - } - - @Test - public void eurekaClientClosed() { - setupContext(TestEurekaClientConfiguration.class); - if (this.context != null) { - CountDownLatch latch = this.context.getBean(CountDownLatch.class); - this.context.close(); - assertThat(latch.getCount()).isEqualTo(0); - } - } - - @Test - public void eurekaRegistrationClosed() throws IOException { - setupContext(TestEurekaRegistrationConfiguration.class); - if (this.context != null) { - EurekaRegistration registration = this.context.getBean(EurekaRegistration.class); - this.context.close(); - verify(registration).close(); - } - } - - private void testNonSecurePortSystemProp(String propName) { - addSystemEnvironment(this.context.getEnvironment(), propName + ":8888"); - setupContext(); - assertEquals(8888, getInstanceConfig().getNonSecurePort()); - } - - private void testNonSecurePort(String propName) { - TestPropertyValues.of(propName + ":8888").applyTo(this.context); - setupContext(); - assertEquals(8888, getInstanceConfig().getNonSecurePort()); - } - - private void testSecurePort(String propName) { - TestPropertyValues.of("eureka.instance.secure-port-enabled=true", propName+":8443").applyTo(this.context); - setupContext(); - assertEquals(8443, getInstanceConfig().getSecurePort()); - } - - private EurekaInstanceConfigBean getInstanceConfig() { - return this.context.getBean(EurekaInstanceConfigBean.class); - } - - @Configuration - @EnableConfigurationProperties - @Import({ UtilAutoConfiguration.class, EurekaClientAutoConfiguration.class }) - protected static class TestConfiguration { } - - @Configuration - protected static class TestEurekaClientConfiguration { - - @Bean - public CountDownLatch countDownLatch() { - return new CountDownLatch(1); - } - - @Bean(destroyMethod = "shutdown") - @ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT) - public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config, ApplicationContext context) { - return new CloudEurekaClient(manager, config, null, context) { - @Override - public synchronized void shutdown() { - CountDownLatch latch = countDownLatch(); - if (latch.getCount() == 1) { - latch.countDown(); - } - super.shutdown(); - } - }; - } - } - - @Configuration - protected static class TestEurekaRegistrationConfiguration { - - @Bean - public EurekaRegistration eurekaRegistration(EurekaClient eurekaClient, CloudEurekaInstanceConfig instanceConfig, ApplicationInfoManager applicationInfoManager) { - return spy(EurekaRegistration.builder(instanceConfig) - .with(applicationInfoManager) - .with(eurekaClient) - .build()); - } - } - - @Configuration - protected static class MockClientConfiguration { - - @Bean - public MutableDiscoveryClientOptionalArgs mutableDiscoveryClientOptionalArgs() { - MutableDiscoveryClientOptionalArgs args = new MutableDiscoveryClientOptionalArgs(); - args.setEurekaJerseyClient(jerseyClient()); - return args; - } - - @Bean - public EurekaJerseyClient jerseyClient() { - EurekaJerseyClient mock = Mockito.mock(EurekaJerseyClient.class); - Mockito.when(mock.getClient()).thenReturn(apacheClient()); - return mock; - } - - @Bean - public ApacheHttpClient4 apacheClient() { - return Mockito.mock(ApacheHttpClient4.class); - } - } -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBeanTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBeanTests.java deleted file mode 100644 index bedd2c08..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBeanTests.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -import java.util.Collections; - -import org.junit.After; -import org.junit.Test; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.test.util.EnvironmentTestUtils; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.CompositePropertySource; -import org.springframework.core.env.MapPropertySource; - -import static org.junit.Assert.assertEquals; - -/** - * @author Dave Syer - */ -public class EurekaClientConfigBeanTests { - - private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - - @After - public void init() { - if (this.context != null) { - this.context.close(); - } - } - - @Test - public void basicBinding() { - EnvironmentTestUtils.addEnvironment(this.context, - "eureka.client.proxyHost=example.com"); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - TestConfiguration.class); - this.context.refresh(); - assertEquals("example.com", this.context.getBean(EurekaClientConfigBean.class) - .getProxyHost()); - } - - @Test - public void serviceUrl() { - EnvironmentTestUtils.addEnvironment(this.context, - "eureka.client.serviceUrl.defaultZone:http://example.com"); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - TestConfiguration.class); - this.context.refresh(); - assertEquals("{defaultZone=http://example.com}", - this.context.getBean(EurekaClientConfigBean.class).getServiceUrl() - .toString()); - assertEquals("[http://example.com/]", getEurekaServiceUrlsForDefaultZone()); - } - - @Test - public void serviceUrlWithCompositePropertySource() { - CompositePropertySource source = new CompositePropertySource("composite"); - this.context.getEnvironment().getPropertySources().addFirst(source); - source.addPropertySource(new MapPropertySource("config", Collections - . singletonMap("eureka.client.serviceUrl.defaultZone", - "http://example.com,http://example2.com"))); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - TestConfiguration.class); - this.context.refresh(); - assertEquals("{defaultZone=http://example.com,http://example2.com}", - this.context.getBean(EurekaClientConfigBean.class).getServiceUrl() - .toString()); - assertEquals("[http://example.com/, http://example2.com/]", - getEurekaServiceUrlsForDefaultZone()); - } - - @Test - public void serviceUrlWithDefault() { - EnvironmentTestUtils.addEnvironment(this.context, - "eureka.client.serviceUrl.defaultZone:http://example.com"); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - TestConfiguration.class); - this.context.refresh(); - assertEquals("[http://example.com/]", getEurekaServiceUrlsForDefaultZone()); - } - - @Test - public void serviceUrlWithCustomZone() { - EnvironmentTestUtils.addEnvironment(this.context, - "eureka.client.serviceUrl.customZone:http://custom-example.com"); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - TestConfiguration.class); - this.context.refresh(); - assertEquals("[http://custom-example.com/]", getEurekaServiceUrls("customZone")); - } - - @Test - public void serviceUrlWithEmptyServiceUrls() { - EnvironmentTestUtils.addEnvironment(this.context, - "eureka.client.serviceUrl.defaultZone:"); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - TestConfiguration.class); - this.context.refresh(); - assertEquals("[]", getEurekaServiceUrlsForDefaultZone()); - } - - private String getEurekaServiceUrlsForDefaultZone() { - return getEurekaServiceUrls("defaultZone"); - } - - private String getEurekaServiceUrls(String myZone) { - return this.context.getBean(EurekaClientConfigBean.class) - .getEurekaServerServiceUrls(myZone).toString(); - } - - @Configuration - @EnableConfigurationProperties(EurekaClientConfigBean.class) - protected static class TestConfiguration { - - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaHealthCheckHandlerTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaHealthCheckHandlerTests.java deleted file mode 100644 index bd1c7ac6..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaHealthCheckHandlerTests.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -import java.util.List; - -import com.netflix.appinfo.InstanceInfo.InstanceStatus; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.boot.actuate.health.AbstractHealthIndicator; -import org.springframework.boot.actuate.health.Health; -import org.springframework.boot.actuate.health.HealthIndicator; -import org.springframework.boot.actuate.health.OrderedHealthAggregator; -import org.springframework.cloud.client.discovery.health.DiscoveryClientHealthIndicator; -import org.springframework.cloud.client.discovery.health.DiscoveryCompositeHealthIndicator; -import org.springframework.cloud.client.discovery.health.DiscoveryHealthIndicator; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; - -import static org.junit.Assert.assertEquals; - -/** - * Tests the {@link EurekaHealthCheckHandler} with different health indicator registered. - * - * @author Jakub Narloch - */ -public class EurekaHealthCheckHandlerTests { - - private EurekaHealthCheckHandler healthCheckHandler; - - @Before - public void setUp() throws Exception { - - healthCheckHandler = new EurekaHealthCheckHandler(new OrderedHealthAggregator()); - } - - @Test - public void testNoHealthCheckRegistered() throws Exception { - - InstanceStatus status = healthCheckHandler.getStatus(InstanceStatus.UNKNOWN); - assertEquals(InstanceStatus.UNKNOWN, status); - } - - @Test - public void testAllUp() throws Exception { - - initialize(UpHealthConfiguration.class); - - InstanceStatus status = healthCheckHandler.getStatus(InstanceStatus.UNKNOWN); - assertEquals(InstanceStatus.UP, status); - } - - @Test - public void testDown() throws Exception { - - initialize(UpHealthConfiguration.class, DownHealthConfiguration.class); - - InstanceStatus status = healthCheckHandler.getStatus(InstanceStatus.UNKNOWN); - assertEquals(InstanceStatus.DOWN, status); - } - - @Test - public void testUnknown() throws Exception { - - initialize(FatalHealthConfiguration.class); - - InstanceStatus status = healthCheckHandler.getStatus(InstanceStatus.UNKNOWN); - assertEquals(InstanceStatus.UNKNOWN, status); - } - - @Test - public void testEurekaIgnored() throws Exception { - - initialize(EurekaDownHealthConfiguration.class); - - InstanceStatus status = healthCheckHandler.getStatus(InstanceStatus.UP); - assertEquals(InstanceStatus.UP, status); - } - - private void initialize(Class... configurations) throws Exception { - ApplicationContext applicationContext = new AnnotationConfigApplicationContext(configurations); - healthCheckHandler.setApplicationContext(applicationContext); - healthCheckHandler.afterPropertiesSet(); - } - - public static class UpHealthConfiguration { - - @Bean - public HealthIndicator healthIndicator() { - return new AbstractHealthIndicator() { - @Override - protected void doHealthCheck(Health.Builder builder) throws Exception { - builder.up(); - } - }; - } - } - - public static class DownHealthConfiguration { - - @Bean - public HealthIndicator healthIndicator() { - return new AbstractHealthIndicator() { - @Override - protected void doHealthCheck(Health.Builder builder) throws Exception { - builder.down(); - } - }; - } - } - - public static class FatalHealthConfiguration { - - @Bean - public HealthIndicator healthIndicator() { - return new AbstractHealthIndicator() { - @Override - protected void doHealthCheck(Health.Builder builder) throws Exception { - builder.status("fatal"); - } - }; - } - } - - - public static class EurekaDownHealthConfiguration { - @Bean - public DiscoveryHealthIndicator discoveryHealthIndicator() { - return new DiscoveryClientHealthIndicator(null) { - @Override - public Health health() { - return Health.up().build(); - } - }; - } - - @Bean - public DiscoveryHealthIndicator eurekaHealthIndicator() { - return new EurekaHealthIndicator(null, null, null) { - @Override - public Health health() { - return Health.down().build(); - } - }; - } - - @Bean - public DiscoveryCompositeHealthIndicator discoveryCompositeHealthIndicator(List indicators) { - return new DiscoveryCompositeHealthIndicator(new OrderedHealthAggregator(), indicators); - } - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBeanTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBeanTests.java deleted file mode 100644 index 17f67964..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBeanTests.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - Copyright 2013-2017 the original author or authors. - * - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - * - http://www.apache.org/licenses/LICENSE-2.0 - * - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.BeanCreationException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.commons.util.InetUtilsProperties; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.util.StringUtils; -import com.netflix.appinfo.InstanceInfo.InstanceStatus; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.springframework.boot.test.util.EnvironmentTestUtils.addEnvironment; - -/** - * @author Dave Syer - * @author Spencer Gibb - * @author Ryan Baxter - */ -public class EurekaInstanceConfigBeanTests { - - private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - private String hostName; - private String ipAddress; - - @Before - public void init() throws Exception { - try (InetUtils utils = new InetUtils(new InetUtilsProperties())) { - InetUtils.HostInfo hostInfo = utils.findFirstNonLoopbackHostInfo(); - this.hostName = hostInfo.getHostname(); - this.ipAddress = hostInfo.getIpAddress(); - } - } - - @After - public void clear() { - if (this.context != null) { - this.context.close(); - } - } - - @Test - public void basicBinding() { - addEnvironment(this.context, "eureka.instance.appGroupName=mygroup"); - setupContext(); - assertEquals("mygroup", getInstanceConfig().getAppGroupName()); - } - - @Test - public void nonSecurePort() { - addEnvironment(this.context, "eureka.instance.nonSecurePort:8888"); - setupContext(); - assertEquals(8888, getInstanceConfig().getNonSecurePort()); - } - - @Test - public void instanceId() { - addEnvironment(this.context, "eureka.instance.instanceId:special"); - setupContext(); - EurekaInstanceConfigBean instance = getInstanceConfig(); - assertEquals("special", instance.getInstanceId()); - } - - @Test - public void initialHostName() { - addEnvironment(this.context, "eureka.instance.appGroupName=mygroup"); - setupContext(); - if (this.hostName != null) { - assertEquals(this.hostName, getInstanceConfig().getHostname()); - } - } - - @Test - public void refreshHostName() { - addEnvironment(this.context, "eureka.instance.appGroupName=mygroup"); - setupContext(); - ReflectionTestUtils.setField(getInstanceConfig(), "hostname", "marvin"); - assertEquals("marvin", getInstanceConfig().getHostname()); - getInstanceConfig().getHostName(true); - if (this.hostName != null) { - assertEquals(this.hostName, getInstanceConfig().getHostname()); - } - } - - @Test - public void refreshHostNameWhenSetByUser() { - addEnvironment(this.context, "eureka.instance.appGroupName=mygroup"); - setupContext(); - getInstanceConfig().setHostname("marvin"); - assertEquals("marvin", getInstanceConfig().getHostname()); - getInstanceConfig().getHostName(true); - assertEquals("marvin", getInstanceConfig().getHostname()); - } - - @Test - public void initialIpAddress() { - addEnvironment(this.context, "eureka.instance.appGroupName=mygroup"); - setupContext(); - if (this.ipAddress != null) { - assertEquals(this.ipAddress, getInstanceConfig().getIpAddress()); - } - } - - @Test - public void refreshIpAddress() { - addEnvironment(this.context, "eureka.instance.appGroupName=mygroup"); - setupContext(); - ReflectionTestUtils.setField(getInstanceConfig(), "ipAddress", "10.0.0.1"); - assertEquals("10.0.0.1", getInstanceConfig().getIpAddress()); - getInstanceConfig().getHostName(true); - if (this.ipAddress != null) { - assertEquals(this.ipAddress, getInstanceConfig().getIpAddress()); - } - } - - @Test - public void refreshIpAddressWhenSetByUser() { - addEnvironment(this.context, "eureka.instance.appGroupName=mygroup"); - setupContext(); - getInstanceConfig().setIpAddress("10.0.0.1"); - assertEquals("10.0.0.1", getInstanceConfig().getIpAddress()); - getInstanceConfig().getHostName(true); - assertEquals("10.0.0.1", getInstanceConfig().getIpAddress()); - } - - @Test - public void testDefaultInitialStatus() { - setupContext(); - assertEquals("initialStatus wrong", InstanceStatus.UP, - getInstanceConfig().getInitialStatus()); - } - - @Test(expected = BeanCreationException.class) - public void testBadInitialStatus() { - addEnvironment(this.context, "eureka.instance.initial-status:FOO"); - setupContext(); - } - - @Test - public void testCustomInitialStatus() { - addEnvironment(this.context, "eureka.instance.initial-status:STARTING"); - setupContext(); - assertEquals("initialStatus wrong", InstanceStatus.STARTING, - getInstanceConfig().getInitialStatus()); - } - - @Test - public void testPreferIpAddress() throws Exception { - addEnvironment(this.context, "eureka.instance.preferIpAddress:true"); - setupContext(); - EurekaInstanceConfigBean instance = getInstanceConfig(); - assertTrue("Wrong hostname: " + instance.getHostname(), - getInstanceConfig().getHostname().equals(instance.getIpAddress())); - - } - - @Test - public void testDefaultVirtualHostName() throws Exception { - addEnvironment(this.context, "spring.application.name:myapp"); - setupContext(); - assertEquals("virtualHostName wrong", "myapp", getInstanceConfig().getVirtualHostName()); - assertEquals("secureVirtualHostName wrong", "myapp", getInstanceConfig().getSecureVirtualHostName()); - - } - - @Test - public void testCustomVirtualHostName() throws Exception { - addEnvironment(this.context, "spring.application.name:myapp", "eureka.instance.virtualHostName=myvirthost", - "eureka.instance.secureVirtualHostName=mysecurevirthost"); - setupContext(); - assertEquals("virtualHostName wrong", "myvirthost", getInstanceConfig().getVirtualHostName()); - assertEquals("secureVirtualHostName wrong", "mysecurevirthost", getInstanceConfig().getSecureVirtualHostName()); - - } - - @Test - public void testDefaultAppName() throws Exception { - setupContext(); - assertEquals("default app name is wrong", "unknown", getInstanceConfig().getAppname()); - assertEquals("default virtual hostname is wrong", "unknown", getInstanceConfig().getVirtualHostName()); - assertEquals("default secure virtual hostname is wrong", "unknown", getInstanceConfig().getSecureVirtualHostName()); - } - - private void setupContext() { - this.context.register(PropertyPlaceholderAutoConfiguration.class, - TestConfiguration.class); - this.context.refresh(); - } - - private EurekaInstanceConfigBean getInstanceConfig() { - return this.context.getBean(EurekaInstanceConfigBean.class); - } - - @Configuration - @EnableConfigurationProperties - protected static class TestConfiguration { - @Autowired - ConfigurableEnvironment env; - @Bean - public EurekaInstanceConfigBean eurekaInstanceConfigBean() { - EurekaInstanceConfigBean configBean = new EurekaInstanceConfigBean(new InetUtils(new InetUtilsProperties())); - String springAppName = this.env.getProperty("spring.application.name", ""); - if(StringUtils.hasText(springAppName)) { - configBean.setSecureVirtualHostName(springAppName); - configBean.setVirtualHostName(springAppName); - configBean.setAppname(springAppName); - } - return configBean; - } - - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/InstanceInfoFactoryTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/InstanceInfoFactoryTests.java deleted file mode 100644 index d88544bc..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/InstanceInfoFactoryTests.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.springframework.cloud.netflix.eureka; - -import java.io.IOException; - -import org.junit.Test; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.commons.util.InetUtilsProperties; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.netflix.appinfo.InstanceInfo; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.springframework.boot.test.util.EnvironmentTestUtils.addEnvironment; - -public class InstanceInfoFactoryTests { - private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - - @Test - public void instanceIdIsHostNameByDefault() throws IOException { - InstanceInfo instanceInfo = setupInstance(); - try (InetUtils utils = new InetUtils(new InetUtilsProperties())) { - assertEquals(utils.findFirstNonLoopbackHostInfo().getHostname(), - instanceInfo.getId()); - } - } - - @Test - public void instanceIdIsIpWhenIpPreferred() throws Exception { - InstanceInfo instanceInfo = setupInstance("eureka.instance.preferIpAddress:true"); - assertTrue(instanceInfo.getId().matches("(\\d+\\.){3}\\d+")); - } - - @Test - public void instanceInfoIdIsInstanceIdWhenSet() { - InstanceInfo instanceInfo = setupInstance("eureka.instance.instanceId:special"); - assertEquals("special", instanceInfo.getId()); - } - - private InstanceInfo setupInstance(String... pairs) { - for (String pair : pairs) { - addEnvironment(this.context, pair); - } - - this.context.register(PropertyPlaceholderAutoConfiguration.class, - TestConfiguration.class); - this.context.refresh(); - - EurekaInstanceConfigBean instanceConfig = getInstanceConfig(); - return new InstanceInfoFactory().create(instanceConfig); - } - - private EurekaInstanceConfigBean getInstanceConfig() { - return this.context.getBean(EurekaInstanceConfigBean.class); - } - - @Configuration - @EnableConfigurationProperties - protected static class TestConfiguration { - @Bean - public EurekaInstanceConfigBean eurekaInstanceConfigBean() { - return new EurekaInstanceConfigBean(new InetUtils(new InetUtilsProperties())); - } - } -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/ConfigRefreshTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/ConfigRefreshTests.java deleted file mode 100644 index e5c9e76d..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/ConfigRefreshTests.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.eureka.config; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent; -import org.springframework.cloud.netflix.eureka.sample.RefreshEurekaSampleApplication; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.test.context.junit4.SpringRunner; - -import com.netflix.discovery.EurekaClient; - -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author Ryan Baxter - */ -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT, classes = RefreshEurekaSampleApplication.class) -public class ConfigRefreshTests { - - @Autowired - private ApplicationEventPublisher publisher; - - @Autowired - //Mocked in RefreshEurekaSampleApplication - private EurekaClient client; - - @Test - // This test is used to verify that getApplications is called the correct number of times - // when a refresh event is fired. The getApplications call in EurekaClientConfigurationRefresher.onApplicationEvent - // ensures that the EurekaClient bean is recreated after a refresh event and that we reregister the client with - //the server - public void verifyGetApplications() { - if(publisher != null) { - publisher.publishEvent(new RefreshScopeRefreshedEvent()); - } - verify(client, times(3)).getApplications(); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/DiscoveryClientConfigServiceAutoConfigurationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/DiscoveryClientConfigServiceAutoConfigurationTests.java deleted file mode 100644 index 31de017d..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/DiscoveryClientConfigServiceAutoConfigurationTests.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.config; - -import java.util.Arrays; - -import org.junit.After; -import org.junit.Test; -import org.mockito.Mockito; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.test.util.EnvironmentTestUtils; -import org.springframework.cloud.commons.util.UtilAutoConfiguration; -import org.springframework.cloud.config.client.ConfigClientProperties; -import org.springframework.cloud.config.client.DiscoveryClientConfigServiceBootstrapConfiguration; -import org.springframework.cloud.netflix.eureka.CloudEurekaClient; -import org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration; -import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.EurekaClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.times; -import static org.springframework.cloud.config.client.ConfigClientProperties.Discovery.DEFAULT_CONFIG_SERVER; - -/** - * @author Dave Syer - */ -public class DiscoveryClientConfigServiceAutoConfigurationTests { - - private AnnotationConfigApplicationContext context; - - @After - public void close() { - if (this.context != null) { - if (this.context.getParent() != null) { - ((AnnotationConfigApplicationContext) this.context.getParent()).close(); - } - this.context.close(); - } - } - - @Test - public void onWhenRequested() throws Exception { - setup("spring.cloud.config.discovery.enabled=true", - "eureka.instance.metadataMap.foo:bar", - "eureka.instance.nonSecurePort:7001", "eureka.instance.hostname:foo"); - assertEquals(1, this.context.getBeanNamesForType( - EurekaDiscoveryClientConfigServiceAutoConfiguration.class).length); - EurekaClient eurekaClient = this.context.getParent().getBean(EurekaClient.class); - Mockito.verify(eurekaClient, times(2)).getInstancesByVipAddress(DEFAULT_CONFIG_SERVER, - false); - Mockito.verify(eurekaClient, times(1)).shutdown(); - ConfigClientProperties locator = this.context - .getBean(ConfigClientProperties.class); - assertEquals("http://foo:7001/", locator.getRawUri()); - ApplicationInfoManager infoManager = this.context - .getBean(ApplicationInfoManager.class); - assertEquals("bar", infoManager.getInfo().getMetadata().get("foo")); - } - - private void setup(String... env) { - AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(parent, env); - parent.register(UtilAutoConfiguration.class, - EurekaDiscoveryClientConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, EnvironmentKnobbler.class, - EurekaDiscoveryClientConfigServiceBootstrapConfiguration.class, - DiscoveryClientConfigServiceBootstrapConfiguration.class, - ConfigClientProperties.class); - parent.refresh(); - this.context = new AnnotationConfigApplicationContext(); - this.context.setParent(parent); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - EurekaDiscoveryClientConfigServiceAutoConfiguration.class, - EurekaClientAutoConfiguration.class); - this.context.refresh(); - } - - @Configuration - protected static class EnvironmentKnobbler { - - @Bean - public EurekaClient eurekaClient(ApplicationInfoManager manager) { - InstanceInfo info = manager.getInfo(); - EurekaClient client = Mockito.mock(CloudEurekaClient.class); - given(client.getInstancesByVipAddress(DEFAULT_CONFIG_SERVER, false)) - .willReturn(Arrays.asList(info)); - return client; - } - - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/EurekaClientConfigServerAutoConfigurationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/EurekaClientConfigServerAutoConfigurationTests.java deleted file mode 100644 index 4486d1e2..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/EurekaClientConfigServerAutoConfigurationTests.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.config; - -import org.junit.Test; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.cloud.config.server.config.ConfigServerProperties; -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; - -import com.netflix.appinfo.EurekaInstanceConfig; - -import static org.junit.Assert.assertEquals; - -/** - * @author Dave Syer - * @author Biju Kunjummen - */ -public class EurekaClientConfigServerAutoConfigurationTests { - - @Test - public void offByDefault() { - new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(EurekaClientConfigServerAutoConfiguration.class)) - .run(c -> { - assertEquals(0, - c.getBeanNamesForType(EurekaInstanceConfigBean.class).length); - }); - } - - @Test - public void onWhenRequested() { - new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - EurekaClientConfigServerAutoConfiguration.class, - ConfigServerProperties.class, EurekaInstanceConfigBean.class)) - .withPropertyValues("spring.cloud.config.server.prefix=/config") - .run(c -> { - assertEquals(1, - c.getBeanNamesForType(EurekaInstanceConfig.class).length); - EurekaInstanceConfig instance = c.getBean(EurekaInstanceConfig.class); - assertEquals("/config", instance.getMetadataMap().get("configPath")); - }); - } - -} \ No newline at end of file diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/JerseyOptionalArgsConfigurationTest.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/JerseyOptionalArgsConfigurationTest.java deleted file mode 100644 index ed2930a1..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/JerseyOptionalArgsConfigurationTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.config; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.netflix.eureka.sample.EurekaSampleApplication; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.netflix.discovery.DiscoveryClient.DiscoveryClientOptionalArgs; - -/** - * @author Daniel Lavoie - */ -@DirtiesContext -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = EurekaSampleApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class JerseyOptionalArgsConfigurationTest { - @Autowired - private DiscoveryClientOptionalArgs optionalArgs; - - @Test - public void contextLoads() { - Assert.assertNotNull(optionalArgs); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/RestTemplateOptionalArgsConfigurationTest.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/RestTemplateOptionalArgsConfigurationTest.java deleted file mode 100644 index 32ebc9a7..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/RestTemplateOptionalArgsConfigurationTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.config; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.netflix.eureka.http.RestTemplateDiscoveryClientOptionalArgs; -import org.springframework.cloud.netflix.eureka.sample.EurekaSampleApplication; -import org.springframework.cloud.test.ClassPathExclusions; -import org.springframework.cloud.test.ModifiedClassPathRunner; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * @author Daniel Lavoie - */ -@RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions({ "jersey-client-*", "jersey-core-*", "jersey-apache-client4-*" }) -@SpringBootTest(classes = EurekaSampleApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class RestTemplateOptionalArgsConfigurationTest { - @Test - public void contextLoads() { - try (ConfigurableApplicationContext context = new SpringApplicationBuilder() - .web(WebApplicationType.NONE).sources(EurekaSampleApplication.class).run()) { - Assert.assertNotNull( - context.getBean(RestTemplateDiscoveryClientOptionalArgs.class)); - } - } -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/healthcheck/EurekaHealthCheckTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/healthcheck/EurekaHealthCheckTests.java deleted file mode 100644 index f9b5e7c2..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/healthcheck/EurekaHealthCheckTests.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.healthcheck; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.health.Health; -import org.springframework.boot.actuate.health.HealthIndicator; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.EurekaClient; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -/** - * Tests the Eureka health check handler. - * - * @author Jakub Narloch - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = EurekaHealthCheckTests.EurekaHealthCheckApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { - "eureka.client.healthcheck.enabled=true", "debug=true" }) -@DirtiesContext -public class EurekaHealthCheckTests { - - @Autowired - private EurekaClient discoveryClient; - - @Test - public void shouldRegisterService() { - - InstanceInfo.InstanceStatus status = this.discoveryClient.getHealthCheckHandler() - .getStatus(InstanceInfo.InstanceStatus.UNKNOWN); - - assertNotNull(status); - assertEquals(InstanceInfo.InstanceStatus.OUT_OF_SERVICE, status); - } - - @Configuration - @EnableAutoConfiguration - protected static class EurekaHealthCheckApplication { - - @Bean - public HealthIndicator healthIndicator() { - return new HealthIndicator() { - @Override - public Health health() { - return new Health.Builder().outOfService().build(); - } - }; - } - } -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/EurekaServerMockApplication.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/EurekaServerMockApplication.java deleted file mode 100644 index 2c9cbb36..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/EurekaServerMockApplication.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.http; - -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.Ordered; -import org.springframework.core.annotation.Order; -import org.springframework.http.HttpStatus; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.provisioning.InMemoryUserDetailsManager; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.bind.annotation.RestController; - -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.shared.Application; -import com.netflix.discovery.shared.Applications; - -import static com.netflix.appinfo.InstanceInfo.DEFAULT_PORT; -import static com.netflix.appinfo.InstanceInfo.DEFAULT_SECURE_PORT; -import static org.springframework.util.Assert.isTrue; - -/** - * Mocked Eureka Server - * - * @author Daniel Lavoie - */ -@Configuration -@RestController -@SpringBootApplication -public class EurekaServerMockApplication { - private static final InstanceInfo INFO = new InstanceInfo(null, null, null, null, - null, null, null, null, null, null, null, null, null, 0, null, null, null, - null, null, null, null, 0l, 0l, null, null); - - /** - * Simulates Eureka Server own's serialization. - * @return - */ - @Bean - public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() { - return new RestTemplateTransportClientFactory() - .mappingJacksonHttpMessageConverter(); - } - - @ResponseStatus(HttpStatus.OK) - @PostMapping("/apps/{appName}") - public void register(@PathVariable String appName, - @RequestBody InstanceInfo instanceInfo) { - isTrue(instanceInfo.getPort() != DEFAULT_PORT && instanceInfo.getPort() != 0, - "Port not received from client"); - isTrue(instanceInfo.getSecurePort() != DEFAULT_SECURE_PORT && instanceInfo.getSecurePort() != 0, - "Secure Port not received from client"); - // Nothing to do - } - - @ResponseStatus(HttpStatus.OK) - @DeleteMapping("/apps/{appName}/{id}") - public void cancel(@PathVariable String appName, @PathVariable String id) { - - } - - @ResponseStatus(HttpStatus.OK) - @PutMapping(value = "/apps/{appName}/{id}", params = { "status", - "lastDirtyTimestamp" }) - public InstanceInfo sendHeartBeat(@PathVariable String appName, - @PathVariable String id, @RequestParam String status, - @RequestParam String lastDirtyTimestamp, - @RequestParam(required = false) String overriddenstatus) { - return new InstanceInfo(null, null, null, null, null, null, null, null, null, - null, null, null, null, 0, null, null, null, null, null, null, null, 0l, - 0l, null, null); - } - - @ResponseStatus(HttpStatus.OK) - @PutMapping(value = "/apps/{appName}/{id}/status", params = { "value", - "lastDirtyTimestamp" }) - public void statusUpdate(@PathVariable String appName, @PathVariable String id, - @RequestParam String value, @RequestParam String lastDirtyTimestamp) { - - } - - @ResponseStatus(HttpStatus.OK) - @DeleteMapping(value = "/apps/{appName}/{id}/status", params = "lastDirtyTimestamp") - public void deleteStatusOverride(@PathVariable String appName, - @PathVariable String id, @RequestParam String lastDirtyTimestamp) { - - } - - @GetMapping(value = { "/apps", "/apps/delta", "/vips/{address}", "/svips/{address}" }) - public Applications getApplications(@PathVariable(required = false) String address, - @RequestParam(required = false) String regions) { - return new Applications(); - } - - @GetMapping(value = "/apps/{appName}") - public Application getApplication(@PathVariable String appName) { - return new Application(); - } - - @GetMapping(value = { "/apps/{appName}/{id}", "/instances/{id}" }) - public InstanceInfo getInstance(@PathVariable(required = false) String appName, - @PathVariable String id) { - return INFO; - } - - @Configuration - @Order(Ordered.HIGHEST_PRECEDENCE) - protected static class TestSecurityConfiguration extends WebSecurityConfigurerAdapter { - - - TestSecurityConfiguration() { - super(true); - } - - @Bean - public UserDetailsService userDetailsService() { - InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); - manager.createUser(User.withUsername("test").password("{noop}test").roles("USER").build()); - return manager; - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - // super.configure(http); - http.antMatcher("/apps/**") - .httpBasic(); - } - - } -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateEurekaHttpClientTest.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateEurekaHttpClientTest.java deleted file mode 100644 index 4545d62c..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateEurekaHttpClientTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.http; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; -import org.springframework.http.HttpStatus; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.netflix.appinfo.InstanceInfo; -import com.netflix.appinfo.InstanceInfo.InstanceStatus; -import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider; -import com.netflix.discovery.shared.resolver.DefaultEndpoint; -import com.netflix.discovery.shared.transport.EurekaHttpClient; - -/** - * @author Daniel Lavoie - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = EurekaServerMockApplication.class, properties = { "debug=true", - "security.basic.enabled=true" }, webEnvironment = WebEnvironment.RANDOM_PORT) -@DirtiesContext -public class RestTemplateEurekaHttpClientTest { - @Autowired - private InetUtils inetUtils; - - @Value("http://${security.user.name}:${security.user.password}@localhost:${local.server.port}") - private String serviceUrl; - - private EurekaHttpClient eurekaHttpClient; - private InstanceInfo info; - - @Before - public void setup() { - eurekaHttpClient = new RestTemplateTransportClientFactory() - .newClient(new DefaultEndpoint(serviceUrl)); - - EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(inetUtils); - - String appname = "customapp"; - config.setIpAddress("127.0.0.1"); - config.setHostname("localhost"); - config.setAppname(appname); - config.setVirtualHostName(appname); - config.setSecureVirtualHostName(appname); - config.setNonSecurePort(4444); - config.setSecurePort(8443); - config.setInstanceId("127.0.0.1:customapp:4444"); - - info = new EurekaConfigBasedInstanceInfoProvider(config).get(); - } - - @Test - public void testRegister() { - Assert.assertEquals(HttpStatus.OK.value(), - eurekaHttpClient.register(info).getStatusCode()); - } - - @Test - public void testCancel() { - Assert.assertEquals(HttpStatus.OK.value(), - eurekaHttpClient.cancel("test", "test").getStatusCode()); - } - - @Test - public void testSendHeartBeat() { - Assert.assertEquals(HttpStatus.OK.value(), eurekaHttpClient - .sendHeartBeat("test", "test", info, null).getStatusCode()); - } - - @Test - public void testStatusUpdate() { - Assert.assertEquals(HttpStatus.OK.value(), eurekaHttpClient - .statusUpdate("test", "test", InstanceStatus.UP, info).getStatusCode()); - } - - @Test - public void testDeleteStatusOverride() { - Assert.assertEquals(HttpStatus.OK.value(), eurekaHttpClient - .deleteStatusOverride("test", "test", info).getStatusCode()); - } - - @Test - public void testGetApplications() { - Assert.assertNotNull(eurekaHttpClient.getApplications().getEntity()); - Assert.assertNotNull(eurekaHttpClient.getApplications("us", "eu").getEntity()); - } - - @Test - public void testGetDelta() { - eurekaHttpClient.getDelta().getEntity(); - eurekaHttpClient.getDelta("us", "eu").getEntity(); - } - - @Test - public void testGetVips() { - eurekaHttpClient.getVip("test"); - eurekaHttpClient.getVip("test", "us", "eu"); - } - - @Test - public void testGetSecureVip() { - eurekaHttpClient.getSecureVip("test"); - eurekaHttpClient.getSecureVip("test", "us", "eu"); - } - - @Test - public void testGetApplication() { - eurekaHttpClient.getApplication("test"); - } - - @Test - public void testGetInstance() { - eurekaHttpClient.getInstance("test"); - eurekaHttpClient.getInstance("test", "test"); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactoriesTest.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactoriesTest.java deleted file mode 100644 index 88d02636..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactoriesTest.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.http; - -import org.junit.Test; - -/** - * @author Daniel Lavoie - */ -public class RestTemplateTransportClientFactoriesTest { - @Test(expected = UnsupportedOperationException.class) - public void testJerseyIsUnsuported() { - new RestTemplateTransportClientFactories().newTransportClientFactory(null, null); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactoryTest.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactoryTest.java deleted file mode 100644 index 50de78ae..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactoryTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.http; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.netflix.discovery.shared.resolver.DefaultEndpoint; - -/** - * @author Daniel Lavoie - */ -public class RestTemplateTransportClientFactoryTest { - private RestTemplateTransportClientFactory transportClientFatory; - - @Before - public void setup() { - transportClientFatory = new RestTemplateTransportClientFactory(); - } - - @Test - public void testWithoutUserInfo() { - transportClientFatory.newClient(new DefaultEndpoint("http://localhost:8761")); - } - - @Test - public void testInvalidUserInfo() { - transportClientFatory - .newClient(new DefaultEndpoint("http://test@localhost:8761")); - } - - @Test - public void testUserInfo() { - transportClientFatory - .newClient(new DefaultEndpoint("http://test:test@localhost:8761")); - } - - @After - public void shutdown() { - transportClientFatory.shutdown(); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/metadata/DefaultManagementMetadataProviderTest.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/metadata/DefaultManagementMetadataProviderTest.java deleted file mode 100644 index 11b028a5..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/metadata/DefaultManagementMetadataProviderTest.java +++ /dev/null @@ -1,138 +0,0 @@ -package org.springframework.cloud.netflix.eureka.metadata; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class DefaultManagementMetadataProviderTest { - - private static final EurekaInstanceConfigBean INSTANCE = mock(EurekaInstanceConfigBean.class); - private final ManagementMetadataProvider provider = new DefaultManagementMetadataProvider(); - - @Before - public void setUp() throws Exception { - when(INSTANCE.getHostname()).thenReturn("host"); - when(INSTANCE.getHealthCheckUrlPath()).thenReturn("health"); - when(INSTANCE.getStatusPageUrlPath()).thenReturn("info"); - } - - @Test - public void serverPortIsRandomAndManagementPortIsNull() throws Exception { - int serverPort = 0; - String serverContextPath = "/"; - String managementContextPath = null; - Integer managementPort = null; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); - - assertThat(actual).isNull(); - } - - @Test - public void managementPortIsRandom() throws Exception { - int serverPort = 0; - String serverContextPath = "/"; - String managementContextPath = null; - Integer managementPort = 0; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); - - assertThat(actual).isNull(); - } - - @Test - public void serverPort() throws Exception { - int serverPort = 7777; - String serverContextPath = "/"; - String managementContextPath = null; - Integer managementPort = null; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); - - assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:7777/health"); - assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:7777/info"); - assertThat(actual.getManagementPort()).isEqualTo(7777); - } - - @Test - public void serverPortManagementPort() throws Exception { - int serverPort = 7777; - String serverContextPath = "/"; - String managementContextPath = null; - Integer managementPort = 8888; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); - - assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:8888/health"); - assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:8888/info"); - assertThat(actual.getManagementPort()).isEqualTo(8888); - } - - @Test - public void serverPortManagementPortServerContextPath() throws Exception { - int serverPort = 7777; - String serverContextPath = "/Server"; - String managementContextPath = null; - Integer managementPort = 8888; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); - - assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:8888/health"); - assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:8888/info"); - assertThat(actual.getManagementPort()).isEqualTo(8888); - } - - @Test - public void serverPortManagementPortServerContextPathManagementContextPath() throws Exception { - int serverPort = 7777; - String serverContextPath = "/Server"; - String managementContextPath = "/Management"; - Integer managementPort = 8888; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); - - assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:8888/Management/health"); - assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:8888/Management/info"); - assertThat(actual.getManagementPort()).isEqualTo(8888); - } - - @Test - public void serverPortServerContextPathManagementContextPath() throws Exception { - int serverPort = 7777; - String serverContextPath = "/Server"; - String managementContextPath = "/Management"; - Integer managementPort = null; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); - - assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:7777/Management/health"); - assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:7777/Management/info"); - assertThat(actual.getManagementPort()).isEqualTo(7777); - } - - @Test - public void serverPortServerContextPath() throws Exception { - int serverPort = 7777; - String serverContextPath = "/Server"; - String managementContextPath = null; - Integer managementPort = null; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); - - assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:7777/Server/health"); - assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:7777/Server/info"); - assertThat(actual.getManagementPort()).isEqualTo(7777); - } - - @Test - public void serverPortManagementPortManagementContextPath() throws Exception { - int serverPort = 7777; - String serverContextPath = "/"; - String managementContextPath = "/Management"; - Integer managementPort = 8888; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); - - assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:8888/Management/health"); - assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:8888/Management/info"); - assertThat(actual.getManagementPort()).isEqualTo(8888); - - } - - -} \ No newline at end of file diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/ApplicationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/ApplicationTests.java deleted file mode 100644 index 3b72e97e..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/ApplicationTests.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.sample; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = EurekaSampleApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -@DirtiesContext -public class ApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/EurekaSampleApplication.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/EurekaSampleApplication.java deleted file mode 100644 index 390e6301..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/EurekaSampleApplication.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.sample; - -import java.io.Closeable; -import java.io.IOException; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.client.serviceregistry.ServiceRegistry; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.netflix.eureka.EurekaClientConfigBean; -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; -import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.netflix.appinfo.HealthCheckHandler; -import com.netflix.appinfo.InstanceInfo; - -import static org.springframework.web.bind.annotation.RequestMethod.POST; - -@Configuration -@ComponentScan -@EnableAutoConfiguration -@RestController -public class EurekaSampleApplication implements ApplicationContextAware, Closeable { - - @Autowired - private DiscoveryClient discoveryClient; - - @Autowired - private ServiceRegistry serviceRegistry; - - @Autowired - private InetUtils inetUtils; - - @Autowired - private EurekaClientConfigBean clientConfig; - - private ApplicationContext context; - - private EurekaRegistration registration; - - @Bean - public HealthCheckHandler healthCheckHandler() { - return new HealthCheckHandler() { - @Override - public InstanceInfo.InstanceStatus getStatus( - InstanceInfo.InstanceStatus currentStatus) { - return InstanceInfo.InstanceStatus.UP; - } - }; - } - - @RequestMapping("/") - public String home() { - return "Hello world "+ registration.getUri(); - } - - @Override - public void setApplicationContext(ApplicationContext context) throws BeansException { - this.context = context; - } - - @RequestMapping(path = "/register", method = POST) - public String register() { - EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(inetUtils); - String appname = "customapp"; - config.setIpAddress("127.0.0.1"); - config.setHostname("localhost"); - config.setAppname(appname); - config.setVirtualHostName(appname); - config.setSecureVirtualHostName(appname); - config.setNonSecurePort(4444); - config.setInstanceId("127.0.0.1:customapp:4444"); - - this.registration = EurekaRegistration.builder(config) - .with(this.clientConfig, this.context) - .build(); - - this.serviceRegistry.register(this.registration); - return config.getInstanceId(); - } - - @RequestMapping(path = "/deregister", method = POST) - public String deregister() { - this.serviceRegistry.deregister(this.registration); - return "deregister"; - } - - @Override - public void close() throws IOException { - deregister(); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/RefreshEurekaSampleApplication.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/RefreshEurekaSampleApplication.java deleted file mode 100644 index 6cbca2ee..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/RefreshEurekaSampleApplication.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.eureka.sample; - -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.cloud.netflix.eureka.CloudEurekaClient; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.bind.annotation.RestController; - -import com.netflix.discovery.EurekaClient; - -import static org.mockito.Mockito.mock; - -/** - * @author Ryan Baxter - */ -@Configuration -@ComponentScan -@EnableAutoConfiguration -@RestController -public class RefreshEurekaSampleApplication { - - @Bean - public EurekaClient getClient() { - return mock(CloudEurekaClient.class); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaServiceRegistryTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaServiceRegistryTests.java deleted file mode 100644 index eba2ce61..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaServiceRegistryTests.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.eureka.serviceregistry; - -import java.util.Map; - -import org.junit.Test; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.commons.util.InetUtilsProperties; -import org.springframework.cloud.netflix.eureka.CloudEurekaClient; -import org.springframework.cloud.netflix.eureka.EurekaClientConfigBean; -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; -import org.springframework.context.ApplicationEventPublisher; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.InstanceInfo; - -import static com.netflix.appinfo.InstanceInfo.InstanceStatus.DOWN; -import static com.netflix.appinfo.InstanceInfo.InstanceStatus.UNKNOWN; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -/** - * @author Spencer Gibb - */ -public class EurekaServiceRegistryTests { - - @Test - public void eurekaClientNotShutdownInDeregister() { - EurekaServiceRegistry registry = new EurekaServiceRegistry(); - - CloudEurekaClient eurekaClient = mock(CloudEurekaClient.class); - ApplicationInfoManager applicationInfoManager = mock(ApplicationInfoManager.class); - - when(applicationInfoManager.getInfo()).thenReturn(mock(InstanceInfo.class)); - - EurekaRegistration registration = EurekaRegistration.builder(new EurekaInstanceConfigBean(new InetUtils(new InetUtilsProperties()))) - .with(eurekaClient) - .with(applicationInfoManager) - .with(new EurekaClientConfigBean(), mock(ApplicationEventPublisher.class)) - .build(); - - registry.deregister(registration); - - verifyZeroInteractions(eurekaClient); - } - - @Test - public void eurekaClientGetStatus() { - EurekaServiceRegistry registry = new EurekaServiceRegistry(); - - EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(new InetUtils(new InetUtilsProperties())); - config.setAppname("myapp"); - config.setInstanceId("1234"); - - CloudEurekaClient eurekaClient = mock(CloudEurekaClient.class); - - InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() - .setAppName("myapp") - .setInstanceId("1234") - .setStatus(DOWN) - .setOverriddenStatus(UNKNOWN) - .build(); - when(eurekaClient.getInstanceInfo("myapp", "1234")) - .thenReturn(instanceInfo); - - EurekaRegistration registration = EurekaRegistration.builder(config) - .with(eurekaClient) - .with(mock(ApplicationInfoManager.class)) - .with(new EurekaClientConfigBean(), mock(ApplicationEventPublisher.class)) - .build(); - - Object status = registry.getStatus(registration); - - assertThat(status).isInstanceOf(Map.class); - - Map map = (Map) status; - - assertThat(map).hasSize(2) - .containsEntry("status", DOWN.toString()) - .containsEntry("overriddenStatus", UNKNOWN.toString()); - } - - - @Test - public void eurekaClientGetStatusNoInstance() { - EurekaServiceRegistry registry = new EurekaServiceRegistry(); - - EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(new InetUtils(new InetUtilsProperties())); - config.setAppname("myapp"); - config.setInstanceId("1234"); - - CloudEurekaClient eurekaClient = mock(CloudEurekaClient.class); - - when(eurekaClient.getInstanceInfo("myapp", "1234")) - .thenReturn(null); - - EurekaRegistration registration = EurekaRegistration.builder(config) - .with(eurekaClient) - .with(mock(ApplicationInfoManager.class)) - .with(new EurekaClientConfigBean(), mock(ApplicationEventPublisher.class)) - .build(); - - Object status = registry.getStatus(registration); - - assertThat(status).isInstanceOf(Map.class); - - Map map = (Map) status; - - assertThat(map).hasSize(1) - .containsEntry("status", UNKNOWN.toString()); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/DomainExtractingServerListTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/DomainExtractingServerListTests.java deleted file mode 100644 index 79a0b5d5..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/DomainExtractingServerListTests.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.eureka; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Test; - -import com.netflix.appinfo.InstanceInfo; -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - -/** - * @author Spencer Gibb - */ -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"; - - private Map metadata = Collections. singletonMap( - "instanceId", INSTANCE_ID); - - @Test - public void testDomainExtractingServer() { - DomainExtractingServerList serverList = getDomainExtractingServerList( - new DefaultClientConfigImpl(), true); - List 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()); - } - - @Test - public void testZoneInMetaData() { - this.metadata = new HashMap(); - this.metadata.put("zone", "us-west-1"); - this.metadata.put("instanceId", INSTANCE_ID); - DomainExtractingServerList serverList = getDomainExtractingServerList( - new DefaultClientConfigImpl(), false); - List servers = serverList.getInitialListOfServers(); - assertNotNull("servers was null", servers); - assertEquals("servers was not size 1", 1, servers.size()); - DomainExtractingServer des = assertDomainExtractingServer(servers, "us-west-1"); - assertEquals("Zone was wrong", "us-west-1", des.getZone()); - } - - @Test - public void testDomainExtractingServerDontApproximateZone() { - DomainExtractingServerList serverList = getDomainExtractingServerList( - new DefaultClientConfigImpl(), false); - List 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()); - } - - protected DomainExtractingServer assertDomainExtractingServer( - List servers, String zone) { - Server actualServer = servers.get(0); - assertTrue("server was not a DomainExtractingServer", - actualServer instanceof DomainExtractingServer); - DomainExtractingServer des = DomainExtractingServer.class.cast(actualServer); - assertEquals("zone was wrong", zone, des.getZone()); - assertEquals("instanceId was wrong", HOST_NAME + ":" + INSTANCE_ID, des.getId()); - return des; - } - - @Test - public void testDomainExtractingServerUseIpAddress() { - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.setProperty(CommonClientConfigKey.UseIPAddrForServer, true); - DomainExtractingServerList serverList = getDomainExtractingServerList(config, - true); - List 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()); - } - - protected DomainExtractingServerList getDomainExtractingServerList( - DefaultClientConfigImpl config, boolean approximateZoneFromHostname) { - DiscoveryEnabledServer server = mock(DiscoveryEnabledServer.class); - @SuppressWarnings("unchecked") - ServerList originalServerList = mock(ServerList.class); - InstanceInfo instanceInfo = mock(InstanceInfo.class); - given(server.getInstanceInfo()).willReturn(instanceInfo); - given(server.getHost()).willReturn(HOST_NAME); - given(instanceInfo.getMetadata()).willReturn(this.metadata); - given(instanceInfo.getHostName()).willReturn(HOST_NAME); - given(instanceInfo.getIPAddr()).willReturn(IP_ADDR); - given(instanceInfo.getPort()).willReturn(PORT); - given(originalServerList.getInitialListOfServers()).willReturn( - Arrays.asList(server)); - return new DomainExtractingServerList(originalServerList, config, - approximateZoneFromHostname); - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaDisabledRibbonClientIntegrationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaDisabledRibbonClientIntegrationTests.java deleted file mode 100644 index 2ced93ea..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaDisabledRibbonClientIntegrationTests.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.eureka; - -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAvoidanceRule; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; -import com.netflix.niws.loadbalancer.NIWSDiscoveryPing; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.commons.util.UtilAutoConfiguration; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration; -import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.ServerIntrospector; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.ribbon.eureka.EurekaRibbonClientPreprocessorIntegrationTests.TestConfiguration; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Ribbon Eureka client should be disabled if Eureka client is not enabled - * - * @author Biju Kunjummen - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = TestConfiguration.class, properties = "eureka.client.enabled=false") -@DirtiesContext -public class EurekaDisabledRibbonClientIntegrationTests { - - @Autowired - private SpringClientFactory factory; - - @Test - public void serverListShouldNotBeEurekaBased() throws Exception { - assertThat(getLoadBalancer().getServerListImpl()) - .isNotInstanceOf(DomainExtractingServerList.class); - } - - @Test - public void ruleDefaultsToZoneAvoidance() throws Exception { - ZoneAvoidanceRule.class.cast(getLoadBalancer().getRule()); - } - - @Test - public void pingShouldNotBeEurekaBased() throws Exception { - assertThat(getLoadBalancer().getPing()).isNotInstanceOf(NIWSDiscoveryPing.class); - } - - @Test - public void serverIntrospectorShouldNotBeEurekaBased() throws Exception { - assertThat(this.factory.getInstance("foo", ServerIntrospector.class)) - .isNotInstanceOf(EurekaServerIntrospector.class); - } - - @SuppressWarnings("unchecked") - private ZoneAwareLoadBalancer getLoadBalancer() { - return (ZoneAwareLoadBalancer) this.factory.getLoadBalancer("foo"); - } - - @Configuration - @RibbonClient("foo") - @Import({ UtilAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class, - EurekaDiscoveryClientConfiguration.class, EurekaClientAutoConfiguration.class, - RibbonEurekaAutoConfiguration.class }) - protected static class TestConfiguration { - - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientConfigurationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientConfigurationTests.java deleted file mode 100644 index 0aee7709..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientConfigurationTests.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.eureka; - -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.commons.util.InetUtilsProperties; -import org.springframework.cloud.netflix.eureka.EurekaClientConfigBean; -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; - -import com.netflix.config.ConfigurationManager; -import com.netflix.config.DeploymentContext.ContextKey; -import com.netflix.config.DynamicStringProperty; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; -import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.springframework.cloud.netflix.ribbon.RibbonUtils.VALUE_NOT_SET; -import static org.springframework.cloud.netflix.ribbon.RibbonUtils.getProperty; -import static org.springframework.cloud.netflix.ribbon.RibbonUtils.getRibbonKey; -import static org.springframework.cloud.netflix.ribbon.RibbonUtils.setRibbonProperty; - -/** - * @author Dave Syer - * @author Ryan Baxter - */ -public class EurekaRibbonClientConfigurationTests { - - @After - @Before - public void close() { - ConfigurationManager.getDeploymentContext().setValue(ContextKey.zone, ""); - } - - @Test - @Ignore - public void basicConfigurationCreatedForLoadBalancer() { - EurekaClientConfigBean client = new EurekaClientConfigBean(); - EurekaInstanceConfigBean configBean = getEurekaInstanceConfigBean(); - client.getAvailabilityZones().put(client.getRegion(), "foo"); - SpringClientFactory clientFactory = new SpringClientFactory(); - EurekaRibbonClientConfiguration clientPreprocessor = new EurekaRibbonClientConfiguration( - client, "service", configBean, false); - clientPreprocessor.preprocess(); - ILoadBalancer balancer = clientFactory.getLoadBalancer("service"); - assertNotNull(balancer); - @SuppressWarnings("unchecked") - ZoneAwareLoadBalancer aware = (ZoneAwareLoadBalancer) balancer; - assertTrue(aware.getServerListImpl() instanceof DomainExtractingServerList); - assertEquals("foo", - ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone)); - } - - private EurekaInstanceConfigBean getEurekaInstanceConfigBean() { - return new EurekaInstanceConfigBean(new InetUtils(new InetUtilsProperties())); - } - - @Test - public void testSetProp() { - EurekaClientConfigBean client = new EurekaClientConfigBean(); - EurekaInstanceConfigBean configBean = getEurekaInstanceConfigBean(); - EurekaRibbonClientConfiguration preprocessor = new EurekaRibbonClientConfiguration( - client, "myService", configBean, false); - String serviceId = "myService"; - String suffix = "mySuffix"; - String value = "myValue"; - DynamicStringProperty property = getProperty(getRibbonKey(serviceId, suffix)); - assertEquals("property doesn't have default value", VALUE_NOT_SET, - property.get()); - setRibbonProperty(serviceId, suffix, value); - assertEquals("property has wrong value", value, property.get()); - setRibbonProperty(serviceId, suffix, value); - assertEquals("property has wrong value", value, property.get()); - } - - @Test - public void testExplicitZone() { - EurekaClientConfigBean client = new EurekaClientConfigBean(); - EurekaInstanceConfigBean configBean = getEurekaInstanceConfigBean(); - configBean.getMetadataMap().put("zone", "myZone"); - EurekaRibbonClientConfiguration preprocessor = new EurekaRibbonClientConfiguration( - client, "myService", configBean, false); - preprocessor.preprocess(); - assertEquals("myZone", - ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone)); - } - - @Test - public void testDefaultZone() { - EurekaClientConfigBean client = new EurekaClientConfigBean(); - EurekaInstanceConfigBean configBean = getEurekaInstanceConfigBean(); - EurekaRibbonClientConfiguration preprocessor = new EurekaRibbonClientConfiguration( - client, "myService", configBean, false); - preprocessor.preprocess(); - assertEquals("defaultZone", - ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone)); - } - - @Test - public void testApproximateZone() { - EurekaClientConfigBean client = new EurekaClientConfigBean(); - EurekaInstanceConfigBean configBean = getEurekaInstanceConfigBean(); - configBean.setHostname("this.is.a.test.com"); - EurekaRibbonClientConfiguration preprocessor = new EurekaRibbonClientConfiguration( - client, "myService", configBean, true); - preprocessor.preprocess(); - assertEquals("is.a.test.com", - ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone)); - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientPreprocessorIntegrationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientPreprocessorIntegrationTests.java deleted file mode 100644 index 3b02fe8a..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientPreprocessorIntegrationTests.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.eureka; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.commons.util.UtilAutoConfiguration; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration; -import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.ServerIntrospector; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.ribbon.eureka.EurekaRibbonClientPreprocessorIntegrationTests.TestConfiguration; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAvoidanceRule; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; -import com.netflix.niws.loadbalancer.NIWSDiscoveryPing; - -/** - * @author Dave Syer - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = TestConfiguration.class) -@DirtiesContext -public class EurekaRibbonClientPreprocessorIntegrationTests { - - @Autowired - private SpringClientFactory factory; - - @Test - public void serverListDefaultsToDomainExtracting() throws Exception { - DomainExtractingServerList.class.cast(getLoadBalancer().getServerListImpl()); - } - - @Test - public void ruleDefaultsToZoneAvoidance() throws Exception { - ZoneAvoidanceRule.class.cast(getLoadBalancer().getRule()); - } - - @Test - public void pingDefaultsToDiscoveryPing() throws Exception { - NIWSDiscoveryPing.class.cast(getLoadBalancer().getPing()); - } - - @Test - public void serverIntrospectorDefaultsToEureka() throws Exception { - EurekaServerIntrospector.class.cast(this.factory.getInstance("foo", ServerIntrospector.class)); - } - - @SuppressWarnings("unchecked") - private ZoneAwareLoadBalancer getLoadBalancer() { - return (ZoneAwareLoadBalancer) this.factory - .getLoadBalancer("foo"); - } - - @Configuration - @RibbonClient("foo") - @Import({ UtilAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class, - EurekaDiscoveryClientConfiguration.class, EurekaClientAutoConfiguration.class, - RibbonEurekaAutoConfiguration.class }) - protected static class TestConfiguration { - - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientPropertyOverrideIntegrationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientPropertyOverrideIntegrationTests.java deleted file mode 100644 index faffa845..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientPropertyOverrideIntegrationTests.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.eureka; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.commons.util.UtilAutoConfiguration; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; - -import com.netflix.discovery.EurekaClient; -import com.netflix.loadbalancer.ConfigurationBasedServerList; -import com.netflix.loadbalancer.DummyPing; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; -import com.netflix.niws.loadbalancer.NIWSDiscoveryPing; - -import static org.mockito.Mockito.mock; - -/** - * @author Spencer Gibb - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = EurekaRibbonClientPropertyOverrideIntegrationTests.TestConfiguration.class) -@DirtiesContext -public class EurekaRibbonClientPropertyOverrideIntegrationTests { - - @Autowired - private SpringClientFactory factory; - - @Test - public void pingOverridesToDummy() throws Exception { - DummyPing.class.cast(getLoadBalancer("foo3").getPing()); - NIWSDiscoveryPing.class.cast(getLoadBalancer("bar").getPing()); - } - - @Test - public void serverListOverridesToTest() throws Exception { - ConfigurationBasedServerList.class - .cast(getLoadBalancer("foo3").getServerListImpl()); - DomainExtractingServerList.class.cast(getLoadBalancer("bar").getServerListImpl()); - } - - @SuppressWarnings("unchecked") - private ZoneAwareLoadBalancer getLoadBalancer(String name) { - return (ZoneAwareLoadBalancer) this.factory.getLoadBalancer(name); - } - - @Configuration - @RibbonClients - @ImportAutoConfiguration({ UtilAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class, - RibbonEurekaAutoConfiguration.class }) - protected static class TestConfiguration { - @Bean - public EurekaClient eurekaClient() { - return mock(EurekaClient.class); - } - } -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonClientPreprocessorIntegrationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonClientPreprocessorIntegrationTests.java deleted file mode 100644 index cfc55a1d..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonClientPreprocessorIntegrationTests.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.eureka; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.commons.util.InetUtilsProperties; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; -import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.ribbon.ZonePreferenceServerListFilter; -import org.springframework.cloud.netflix.ribbon.eureka.RibbonClientPreprocessorIntegrationTests.TestConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.netflix.discovery.EurekaClient; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAvoidanceRule; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; - -import static org.junit.Assert.assertEquals; - -/** - * @author Dave Syer - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = TestConfiguration.class) -@DirtiesContext -public class RibbonClientPreprocessorIntegrationTests { - - @Autowired - private SpringClientFactory factory; - - @Test - public void serverListIsWrapped() throws Exception { - @SuppressWarnings("unchecked") - ZoneAwareLoadBalancer loadBalancer = (ZoneAwareLoadBalancer) this.factory - .getLoadBalancer("foo"); - DomainExtractingServerList.class.cast(loadBalancer.getServerListImpl()); - } - - @Test - public void ruleDefaultsToAvoidance() throws Exception { - @SuppressWarnings("unchecked") - ZoneAwareLoadBalancer loadBalancer = (ZoneAwareLoadBalancer) this.factory - .getLoadBalancer("foo"); - ZoneAvoidanceRule.class.cast(loadBalancer.getRule()); - } - - @Test - public void serverListFilterOverride() throws Exception { - @SuppressWarnings("unchecked") - ZoneAwareLoadBalancer loadBalancer = (ZoneAwareLoadBalancer) this.factory - .getLoadBalancer("foo"); - assertEquals("myTestZone", - ZonePreferenceServerListFilter.class.cast(loadBalancer.getFilter()) - .getZone()); - } - - @Configuration - @RibbonClient("foo") - @ImportAutoConfiguration({ PropertyPlaceholderAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class }) - protected static class PlainConfiguration { - } - - @Configuration - @RibbonClient(name = "foo", configuration = FooConfiguration.class) - @ImportAutoConfiguration({ PropertyPlaceholderAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class, - RibbonEurekaAutoConfiguration.class }) - protected static class TestConfiguration { - @Bean - EurekaClient eurekaClient() { - return Mockito.mock(EurekaClient.class); - } - } - - @Configuration - protected static class FooConfiguration { - @Bean - public ZonePreferenceServerListFilter serverListFilter() { - ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter(); - filter.setZone("myTestZone"); - return filter; - } - - @Bean - public EurekaInstanceConfigBean getEurekaInstanceConfigBean() { - EurekaInstanceConfigBean bean = new EurekaInstanceConfigBean(new InetUtils( - new InetUtilsProperties())); - return bean; - } - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonEurekaAutoConfigurationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonEurekaAutoConfigurationTests.java deleted file mode 100644 index d84bdf04..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonEurekaAutoConfigurationTests.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon.eureka; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; -import org.springframework.context.annotation.Bean; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author Spencer Gibb - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = RibbonEurekaAutoConfigurationTests.EurekaClientDisabledApp.class, - properties = { "eureka.client.enabled=false", "spring.application.name=eurekadisabledtest" }, - webEnvironment = RANDOM_PORT) -@DirtiesContext -public class RibbonEurekaAutoConfigurationTests { - - @Autowired - TestLoadbalancerClient testLoadbalancerClient; - - @Test - public void contextLoads() { - assertThat(testLoadbalancerClient.instanceFound).isFalse(); - } - - @SpringBootConfiguration - @EnableAutoConfiguration - public static class EurekaClientDisabledApp { - - @Bean - public TestLoadbalancerClient testLoadbalanceClient(LoadBalancerClient loadBalancerClient) { - return new TestLoadbalancerClient(loadBalancerClient); - } - - @Bean - public CommandLineRunner commandLineRunner(final TestLoadbalancerClient testLoadbalancerClient) { - return new CommandLineRunner() { - @Override - public void run(String... args) throws Exception { - testLoadbalancerClient.doStuff(); - } - }; - } - } - - private static class TestLoadbalancerClient { - - Log log = LogFactory.getLog(this.getClass()); - - private LoadBalancerClient loadBalancerClient; - private boolean instanceFound = false; - - public TestLoadbalancerClient(LoadBalancerClient loadBalancerClient) { - this.loadBalancerClient = loadBalancerClient; - } - - public void doStuff() { - ServiceInstance serviceInstance = loadBalancerClient.choose("http://host/doStuff"); - if (serviceInstance != null) { - log.info("There is a service instance, because Eureka discovery is enabled and the service is registered"); - instanceFound = true; - } - else { - log.warn("No instance found, because Eureka is disabled or there is no service matching."); - } - } - } - -} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/ZoneUtilsTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/ZoneUtilsTests.java deleted file mode 100644 index c5fb44a1..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/ZoneUtilsTests.java +++ /dev/null @@ -1,35 +0,0 @@ -/* Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.cloud.netflix.ribbon.eureka; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -/** - * - * @author Ryan Baxter - * - */ -public class ZoneUtilsTests { - - @Test - public void extractApproximateZoneTest() { - assertTrue("foo".equals(ZoneUtils.extractApproximateZone("foo"))); - assertTrue("bar".equals(ZoneUtils.extractApproximateZone("foo.bar"))); - assertTrue("world.foo.bar".equals(ZoneUtils - .extractApproximateZone("hello.world.foo.bar"))); - } -} diff --git a/spring-cloud-netflix-eureka-client/src/test/resources/application.yml b/spring-cloud-netflix-eureka-client/src/test/resources/application.yml deleted file mode 100644 index 3e83e31a..00000000 --- a/spring-cloud-netflix-eureka-client/src/test/resources/application.yml +++ /dev/null @@ -1,12 +0,0 @@ -# for EurekaRibbonClientPropertyOverrideIntegrationTests -foo3: - ribbon: - NFLoadBalancerPingClassName: com.netflix.loadbalancer.DummyPing - NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList - -security: - basic: - enabled: false - user: - name: test - password: test \ No newline at end of file diff --git a/spring-cloud-netflix-eureka-server/pom.xml b/spring-cloud-netflix-eureka-server/pom.xml deleted file mode 100644 index 02a94e38..00000000 --- a/spring-cloud-netflix-eureka-server/pom.xml +++ /dev/null @@ -1,231 +0,0 @@ - - - 4.0.0 - - org.springframework.cloud - spring-cloud-netflix - 2.0.0.BUILD-SNAPSHOT - .. - - spring-cloud-netflix-eureka-server - Spring Cloud Netflix Eureka Server - https://projects.spring.io/spring-cloud/ - - ${basedir}/.. - 1.7.9 - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-starter-freemarker - - - org.springframework.cloud - spring-cloud-commons - - - org.springframework.cloud - spring-cloud-context - true - - - org.springframework.cloud - spring-cloud-netflix-core - - - org.springframework.cloud - spring-cloud-netflix-eureka-client - - - com.netflix.eureka - eureka-client - - - com.sun.jersey - jersey-servlet - - - com.sun.jersey - jersey-server - - - com.netflix.eureka - eureka-core - - - blitz4j - com.netflix.blitz4j - - - - - com.netflix.archaius - archaius-core - - - - commons-configuration - commons-configuration - true - - - - javax.inject - javax.inject - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - - - com.thoughtworks.xstream - xstream - - - org.projectlombok - lombok - - compile - true - - - org.springframework.restdocs - spring-restdocs-restassured - test - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.cloud - spring-cloud-contract-wiremock - test - - - org.springframework.security - spring-security-rsa - test - - - - - - ${project.basedir}/src/main/resources - - - ${project.build.directory}/generated-resources - - - - - maven-resources-plugin - - - - copy-resources - validate - - copy-resources - - - ${basedir}/target/wro - - - src/main/wro - true - - - - - - copy-docs - prepare-package - - copy-resources - - - - ${project.build.outputDirectory}/static/docs - - - - - ${project.build.directory}/generated-docs - - - - - - - - - ro.isdc.wro4j - wro4j-maven-plugin - ${wro4j.version} - - - generate-resources - - run - - - - - ro.isdc.wro.maven.plugin.manager.factory.ConfigurableWroManagerFactory - ${project.build.directory}/generated-resources/static/eureka/css - ${project.build.directory}/generated-resources/static/eureka/js - ${project.build.directory}/wro/wro.xml - ${basedir}/src/main/wro/wro.properties - ${basedir}/src/main/wro - - - - org.webjars - jquery - 2.1.1 - - - org.webjars - bootstrap - 3.2.0 - - - - - org.asciidoctor - asciidoctor-maven-plugin - - - generate-docs - prepare-package - - process-asciidoc - - - html - book - - - - - - - diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/CloudJacksonJson.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/CloudJacksonJson.java deleted file mode 100644 index 1c2f99e6..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/CloudJacksonJson.java +++ /dev/null @@ -1,166 +0,0 @@ -package org.springframework.cloud.netflix.eureka.server; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.function.Supplier; - -import org.springframework.util.ReflectionUtils; -import org.springframework.util.StringUtils; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.Version; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectReader; -import com.fasterxml.jackson.databind.ObjectWriter; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.module.SimpleModule; -import com.netflix.appinfo.DataCenterInfo; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.appinfo.LeaseInfo; -import com.netflix.discovery.converters.EurekaJacksonCodec; -import com.netflix.discovery.converters.EurekaJacksonCodec.InstanceInfoDeserializer; -import com.netflix.discovery.converters.EurekaJacksonCodec.InstanceInfoSerializer; -import com.netflix.discovery.converters.wrappers.CodecWrappers.LegacyJacksonJson; -import com.netflix.discovery.shared.Application; -import com.netflix.discovery.shared.Applications; - -import static com.netflix.discovery.converters.wrappers.CodecWrappers.getCodecName; - -/** - * @author Spencer Gibb - */ -public 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 String encode(T object) throws IOException { - return this.codec.writeToString(object); - } - - @Override - public void encode(T object, OutputStream outputStream) throws IOException { - this.codec.writeTo(object, outputStream); - } - - @Override - public T decode(String textValue, Class type) throws IOException { - return this.codec.readValue(type, textValue); - } - - @Override - public T decode(InputStream inputStream, Class type) throws IOException { - return this.codec.readValue(type, inputStream); - } - - static class CloudJacksonCodec extends EurekaJacksonCodec { - private static final Version VERSION = new Version(1, 1, 0, null, null, null); - - @SuppressWarnings("deprecation") - public 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, Supplier> 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, 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 InstanceInfo updateIfNeeded(final InstanceInfo info) { - 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; - } - - 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; - } - } -} diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EnableEurekaServer.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EnableEurekaServer.java deleted file mode 100644 index e1cb0238..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EnableEurekaServer.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.springframework.context.annotation.Import; - -/** - * Annotation to activate Eureka Server related configuration {@link EurekaServerAutoConfiguration} - * - * @author Dave Syer - * @author Biju Kunjummen - * - */ - -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Import(EurekaServerMarkerConfiguration.class) -public @interface EnableEurekaServer { - -} diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaController.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaController.java deleted file mode 100644 index 3c068998..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaController.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import com.netflix.eureka.EurekaServerContext; -import com.netflix.eureka.EurekaServerContextHolder; -import com.netflix.eureka.registry.PeerAwareInstanceRegistry; -import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import com.netflix.appinfo.AmazonInfo; -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.DataCenterInfo; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.config.ConfigurationManager; -import com.netflix.discovery.shared.Application; -import com.netflix.discovery.shared.Pair; -import com.netflix.eureka.cluster.PeerEurekaNode; -import com.netflix.eureka.resources.StatusResource; -import com.netflix.eureka.util.StatusInfo; - -/** - * @author Spencer Gibb - * @author Gang Li - */ -@Controller -@RequestMapping("${eureka.dashboard.path:/}") -public class EurekaController { - - @Value("${eureka.dashboard.path:/}") - private String dashboardPath = ""; - private ApplicationInfoManager applicationInfoManager; - - public EurekaController(ApplicationInfoManager applicationInfoManager) { - this.applicationInfoManager = applicationInfoManager; - } - - @RequestMapping(method = RequestMethod.GET) - public String status(HttpServletRequest request, Map model) { - populateBase(request, model); - populateApps(model); - StatusInfo statusInfo; - try { - statusInfo = new StatusResource().getStatusInfo(); - } - catch (Exception e) { - statusInfo = StatusInfo.Builder.newBuilder().isHealthy(false).build(); - } - model.put("statusInfo", statusInfo); - populateInstanceInfo(model, statusInfo); - filterReplicas(model, statusInfo); - return "eureka/status"; - } - - @RequestMapping(value = "/lastn", method = RequestMethod.GET) - public String lastn(HttpServletRequest request, Map model) { - populateBase(request, model); - PeerAwareInstanceRegistryImpl registry = (PeerAwareInstanceRegistryImpl) getRegistry(); - ArrayList> lastNCanceled = new ArrayList<>(); - List> list = registry.getLastNCanceledInstances(); - for (Pair entry : list) { - lastNCanceled.add(registeredInstance(entry.second(), entry.first())); - } - model.put("lastNCanceled", lastNCanceled); - list = registry.getLastNRegisteredInstances(); - ArrayList> lastNRegistered = new ArrayList<>(); - for (Pair entry : list) { - lastNRegistered.add(registeredInstance(entry.second(), entry.first())); - } - model.put("lastNRegistered", lastNRegistered); - return "eureka/lastn"; - } - - private Map registeredInstance(String id, long date) { - HashMap map = new HashMap<>(); - map.put("id", id); - map.put("date", new Date(date)); - return map; - } - - protected void populateBase(HttpServletRequest request, Map model) { - model.put("time", new Date()); - model.put("basePath", "/"); - model.put("dashboardPath", this.dashboardPath.equals("/") ? "" - : this.dashboardPath); - populateHeader(model); - populateNavbar(request, model); - } - - private void populateHeader(Map model) { - model.put("currentTime", StatusResource.getCurrentTimeAsString()); - model.put("upTime", StatusInfo.getUpTime()); - model.put("environment", ConfigurationManager.getDeploymentContext() - .getDeploymentEnvironment()); - model.put("datacenter", ConfigurationManager.getDeploymentContext() - .getDeploymentDatacenter()); - PeerAwareInstanceRegistry registry = getRegistry(); - model.put("registry", registry); - model.put("isBelowRenewThresold", registry.isBelowRenewThresold() == 1); - DataCenterInfo info = applicationInfoManager.getInfo().getDataCenterInfo(); - if (info.getName() == DataCenterInfo.Name.Amazon) { - AmazonInfo amazonInfo = (AmazonInfo) info; - model.put("amazonInfo", amazonInfo); - model.put("amiId", amazonInfo.get(AmazonInfo.MetaDataKey.amiId)); - model.put("availabilityZone", - amazonInfo.get(AmazonInfo.MetaDataKey.availabilityZone)); - model.put("instanceId", amazonInfo.get(AmazonInfo.MetaDataKey.instanceId)); - } - } - - private PeerAwareInstanceRegistry getRegistry() { - return getServerContext().getRegistry(); - } - - private EurekaServerContext getServerContext() { - return EurekaServerContextHolder.getInstance().getServerContext(); - } - - private void populateNavbar(HttpServletRequest request, Map model) { - Map replicas = new LinkedHashMap<>(); - List list = getServerContext().getPeerEurekaNodes().getPeerNodesView(); - for (PeerEurekaNode node : list) { - try { - URI uri = new URI(node.getServiceUrl()); - String href = scrubBasicAuth(node.getServiceUrl()); - replicas.put(uri.getHost(), href); - } - catch (Exception ex) { - // ignore? - } - } - model.put("replicas", replicas.entrySet()); - } - - private void populateApps(Map model) { - List sortedApplications = getRegistry().getSortedApplications(); - ArrayList> apps = new ArrayList<>(); - for (Application app : sortedApplications) { - LinkedHashMap appData = new LinkedHashMap<>(); - apps.add(appData); - appData.put("name", app.getName()); - Map amiCounts = new HashMap<>(); - Map>> instancesByStatus = new HashMap<>(); - Map zoneCounts = new HashMap<>(); - for (InstanceInfo info : app.getInstances()) { - String id = info.getId(); - String url = info.getStatusPageUrl(); - InstanceInfo.InstanceStatus status = info.getStatus(); - String ami = "n/a"; - String zone = ""; - if (info.getDataCenterInfo().getName() == DataCenterInfo.Name.Amazon) { - AmazonInfo dcInfo = (AmazonInfo) info.getDataCenterInfo(); - ami = dcInfo.get(AmazonInfo.MetaDataKey.amiId); - zone = dcInfo.get(AmazonInfo.MetaDataKey.availabilityZone); - } - Integer count = amiCounts.get(ami); - if (count != null) { - amiCounts.put(ami, count + 1); - } - else { - amiCounts.put(ami, 1); - } - count = zoneCounts.get(zone); - if (count != null) { - zoneCounts.put(zone, count + 1); - } - else { - zoneCounts.put(zone, 1); - } - List> 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> instanceInfos = new ArrayList<>(); - appData.put("instanceInfos", instanceInfos); - for (Iterator>>> iter = instancesByStatus - .entrySet().iterator(); iter.hasNext();) { - Map.Entry>> entry = iter - .next(); - List> value = entry.getValue(); - InstanceInfo.InstanceStatus status = entry.getKey(); - LinkedHashMap instanceData = new LinkedHashMap<>(); - instanceInfos.add(instanceData); - instanceData.put("status", entry.getKey()); - ArrayList> instances = new ArrayList<>(); - instanceData.put("instances", instances); - instanceData.put("isNotUp", status != InstanceInfo.InstanceStatus.UP); - - // TODO - - /* - * if(status != InstanceInfo.InstanceStatus.UP){ - * buf.append(""); } - * buf.append("").append(status - * .name()).append(" (").append(value.size()).append(") - "); - * if(status != InstanceInfo.InstanceStatus.UP){ - * buf.append(""); } - */ - - for (Pair p : value) { - LinkedHashMap instance = new LinkedHashMap<>(); - instances.add(instance); - instance.put("id", p.first()); - String url = p.second(); - instance.put("url", url); - boolean isHref = url != null && url.startsWith("http"); - instance.put("isHref", isHref); - /* - * String id = p.first(); String url = p.second(); if(url != null && - * url.startsWith("http")){ - * buf.append(""); }else { url = - * null; } buf.append(id); if(url != null){ buf.append(""); } - * buf.append(", "); - */ - } - } - // out.println("" + buf.toString() + ""); - } - model.put("apps", apps); - } - - private void populateInstanceInfo(Map model, StatusInfo statusInfo) { - InstanceInfo instanceInfo = statusInfo.getInstanceInfo(); - Map instanceMap = new HashMap<>(); - instanceMap.put("ipAddr", instanceInfo.getIPAddr()); - instanceMap.put("status", instanceInfo.getStatus().toString()); - if (instanceInfo.getDataCenterInfo().getName() == DataCenterInfo.Name.Amazon) { - AmazonInfo info = (AmazonInfo) instanceInfo.getDataCenterInfo(); - instanceMap.put("availability-zone", - info.get(AmazonInfo.MetaDataKey.availabilityZone)); - instanceMap.put("public-ipv4", info.get(AmazonInfo.MetaDataKey.publicIpv4)); - instanceMap.put("instance-id", info.get(AmazonInfo.MetaDataKey.instanceId)); - instanceMap.put("public-hostname", - info.get(AmazonInfo.MetaDataKey.publicHostname)); - instanceMap.put("ami-id", info.get(AmazonInfo.MetaDataKey.amiId)); - instanceMap.put("instance-type", - info.get(AmazonInfo.MetaDataKey.instanceType)); - } - model.put("instanceInfo", instanceMap); - } - - protected void filterReplicas(Map model, StatusInfo statusInfo) { - Map applicationStats = statusInfo.getApplicationStats(); - if(applicationStats.get("registered-replicas").contains("@")){ - applicationStats.put("registered-replicas", scrubBasicAuth(applicationStats.get("registered-replicas"))); - } - if(applicationStats.get("unavailable-replicas").contains("@")){ - applicationStats.put("unavailable-replicas",scrubBasicAuth(applicationStats.get("unavailable-replicas"))); - } - if(applicationStats.get("available-replicas").contains("@")){ - applicationStats.put("available-replicas",scrubBasicAuth(applicationStats.get("available-replicas"))); - } - model.put("applicationStats", applicationStats); - } - - private String scrubBasicAuth(String urlList){ - String[] urls=urlList.split(","); - StringBuilder filteredUrls = new StringBuilder(); - for(String u : urls){ - if(u.contains("@")){ - filteredUrls.append(u.substring(0,u.indexOf("//")+2)).append(u.substring(u.indexOf("@")+1,u.length())).append(","); - }else{ - filteredUrls.append(u).append(","); - } - } - return filteredUrls.substring(0,filteredUrls.length()-1); - } -} diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaDashboardProperties.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaDashboardProperties.java deleted file mode 100644 index a6f0b8d6..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaDashboardProperties.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -import java.util.Objects; - -/** - * Configuration properties for the Eureka dashboard (UI). - * - * @author Dave Syer - */ -@ConfigurationProperties("eureka.dashboard") -public 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() { - final StringBuilder sb = new StringBuilder("EurekaDashboardProperties{"); - sb.append("path='").append(path).append('\''); - sb.append(", enabled=").append(enabled); - sb.append('}'); - return sb.toString(); - } -} diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerAutoConfiguration.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerAutoConfiguration.java deleted file mode 100644 index a90cb7e8..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerAutoConfiguration.java +++ /dev/null @@ -1,318 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.servlet.Filter; -import javax.ws.rs.Path; -import javax.ws.rs.ext.Provider; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.cloud.client.actuator.HasFeatures; -import org.springframework.cloud.context.environment.EnvironmentChangeEvent; -import org.springframework.cloud.netflix.eureka.EurekaConstants; -import org.springframework.context.ApplicationListener; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.Ordered; -import org.springframework.core.env.Environment; -import org.springframework.core.io.ResourceLoader; -import org.springframework.core.type.filter.AnnotationTypeFilter; -import org.springframework.util.ClassUtils; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.EurekaClientConfig; -import com.netflix.discovery.converters.EurekaJacksonCodec; -import com.netflix.discovery.converters.wrappers.CodecWrapper; -import com.netflix.discovery.converters.wrappers.CodecWrappers; -import com.netflix.eureka.DefaultEurekaServerContext; -import com.netflix.eureka.EurekaServerConfig; -import com.netflix.eureka.EurekaServerContext; -import com.netflix.eureka.cluster.PeerEurekaNodes; -import com.netflix.eureka.registry.PeerAwareInstanceRegistry; -import com.netflix.eureka.resources.DefaultServerCodecs; -import com.netflix.eureka.resources.ServerCodecs; -import com.sun.jersey.api.core.DefaultResourceConfig; -import com.sun.jersey.spi.container.servlet.ServletContainer; - -/** - * @author Gunnar Hillert - * @author Biju Kunjummen - * @author Fahim Farook - */ -@Configuration -@Import(EurekaServerInitializerConfiguration.class) -@ConditionalOnBean(EurekaServerMarkerConfiguration.Marker.class) -@EnableConfigurationProperties({ EurekaDashboardProperties.class, - InstanceRegistryProperties.class }) -@PropertySource("classpath:/eureka/server.properties") -public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter { - /** - * List of packages containing Jersey resources required by the Eureka server - */ - private static final String[] EUREKA_PACKAGES = new String[] { "com.netflix.discovery", - "com.netflix.eureka" }; - - @Autowired - private ApplicationInfoManager applicationInfoManager; - - @Autowired - private EurekaServerConfig eurekaServerConfig; - - @Autowired - private EurekaClientConfig eurekaClientConfig; - - @Autowired - private EurekaClient eurekaClient; - - @Autowired - private InstanceRegistryProperties instanceRegistryProperties; - - public static final CloudJacksonJson JACKSON_JSON = new CloudJacksonJson(); - - @Bean - public HasFeatures eurekaServerFeature() { - return HasFeatures.namedFeature("Eureka Server", - EurekaServerAutoConfiguration.class); - } - - @Configuration - protected static class EurekaServerConfigBeanConfiguration { - @Bean - @ConditionalOnMissingBean - public EurekaServerConfig eurekaServerConfig(EurekaClientConfig clientConfig) { - EurekaServerConfigBean server = new EurekaServerConfigBean(); - if (clientConfig.shouldRegisterWithEureka()) { - // Set a sensible default if we are supposed to replicate - server.setRegistrySyncRetries(5); - } - return server; - } - } - - @Bean - @ConditionalOnProperty(prefix = "eureka.dashboard", name = "enabled", matchIfMissing = true) - public EurekaController eurekaController() { - return new EurekaController(this.applicationInfoManager); - } - - static { - CodecWrappers.registerWrapper(JACKSON_JSON); - EurekaJacksonCodec.setInstance(JACKSON_JSON.getCodec()); - } - - @Bean - public ServerCodecs serverCodecs() { - return new CloudServerCodecs(this.eurekaServerConfig); - } - - private static CodecWrapper getFullJson(EurekaServerConfig serverConfig) { - CodecWrapper codec = CodecWrappers.getCodec(serverConfig.getJsonCodecName()); - return codec == null ? CodecWrappers.getCodec(JACKSON_JSON.codecName()) : codec; - } - - private static CodecWrapper getFullXml(EurekaServerConfig serverConfig) { - CodecWrapper codec = CodecWrappers.getCodec(serverConfig.getXmlCodecName()); - return codec == null ? CodecWrappers.getCodec(CodecWrappers.XStreamXml.class) - : codec; - } - - class CloudServerCodecs extends DefaultServerCodecs { - - public CloudServerCodecs(EurekaServerConfig serverConfig) { - super(getFullJson(serverConfig), - CodecWrappers.getCodec(CodecWrappers.JacksonJsonMini.class), - getFullXml(serverConfig), - CodecWrappers.getCodec(CodecWrappers.JacksonXmlMini.class)); - } - } - - @Bean - public PeerAwareInstanceRegistry peerAwareInstanceRegistry( - ServerCodecs serverCodecs) { - this.eurekaClient.getApplications(); // force initialization - return new InstanceRegistry(this.eurekaServerConfig, this.eurekaClientConfig, - serverCodecs, this.eurekaClient, - this.instanceRegistryProperties.getExpectedNumberOfRenewsPerMin(), - this.instanceRegistryProperties.getDefaultOpenForTrafficCount()); - } - - @Bean - @ConditionalOnMissingBean - public PeerEurekaNodes peerEurekaNodes(PeerAwareInstanceRegistry registry, - ServerCodecs serverCodecs) { - return new RefreshablePeerEurekaNodes(registry, this.eurekaServerConfig, - this.eurekaClientConfig, serverCodecs, this.applicationInfoManager); - } - - /** - * {@link PeerEurekaNodes} which updates peers when /refresh is invoked. - * Peers are updated only if - * eureka.client.use-dns-for-fetching-service-urls is - * false and one of following properties have changed. - *

- *
    - *
  • eureka.client.availability-zones
  • - *
  • eureka.client.region
  • - *
  • eureka.client.service-url.<zone>
  • - *
- */ - static class RefreshablePeerEurekaNodes extends PeerEurekaNodes - implements ApplicationListener { - - public RefreshablePeerEurekaNodes( - final PeerAwareInstanceRegistry registry, - final EurekaServerConfig serverConfig, - final EurekaClientConfig clientConfig, - final ServerCodecs serverCodecs, - final ApplicationInfoManager applicationInfoManager) { - super(registry, serverConfig, clientConfig, serverCodecs, applicationInfoManager); - } - - @Override - public void onApplicationEvent(final EnvironmentChangeEvent event) { - if (shouldUpdate(event.getKeys())) { - updatePeerEurekaNodes(resolvePeerUrls()); - } - } - - /* - * Check whether specific properties have changed. - */ - protected boolean shouldUpdate(final Set changedKeys) { - assert changedKeys != null; - - // if eureka.client.use-dns-for-fetching-service-urls is true, then - // service-url will not be fetched from environment. - if (clientConfig.shouldUseDnsForFetchingServiceUrls()) { - return false; - } - - if (changedKeys.contains("eureka.client.region")) { - return true; - } - - for (final String key : changedKeys) { - // property keys are not expected to be null. - if (key.startsWith("eureka.client.service-url.") || - key.startsWith("eureka.client.availability-zones.")) { - return true; - } - } - - return false; - } - } - - @Bean - public EurekaServerContext eurekaServerContext(ServerCodecs serverCodecs, - PeerAwareInstanceRegistry registry, PeerEurekaNodes peerEurekaNodes) { - return new DefaultEurekaServerContext(this.eurekaServerConfig, serverCodecs, - registry, peerEurekaNodes, this.applicationInfoManager); - } - - @Bean - public EurekaServerBootstrap eurekaServerBootstrap(PeerAwareInstanceRegistry registry, - EurekaServerContext serverContext) { - return new EurekaServerBootstrap(this.applicationInfoManager, - this.eurekaClientConfig, this.eurekaServerConfig, registry, - serverContext); - } - - /** - * Register the Jersey filter - */ - @Bean - public FilterRegistrationBean jerseyFilterRegistration( - javax.ws.rs.core.Application eurekaJerseyApp) { - FilterRegistrationBean bean = new FilterRegistrationBean(); - bean.setFilter(new ServletContainer(eurekaJerseyApp)); - bean.setOrder(Ordered.LOWEST_PRECEDENCE); - bean.setUrlPatterns( - Collections.singletonList(EurekaConstants.DEFAULT_PREFIX + "/*")); - - return bean; - } - - /** - * Construct a Jersey {@link javax.ws.rs.core.Application} with all the resources - * required by the Eureka server. - */ - @Bean - public javax.ws.rs.core.Application jerseyApplication(Environment environment, - ResourceLoader resourceLoader) { - - ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider( - false, environment); - - // Filter to include only classes that have a particular annotation. - // - provider.addIncludeFilter(new AnnotationTypeFilter(Path.class)); - provider.addIncludeFilter(new AnnotationTypeFilter(Provider.class)); - - // Find classes in Eureka packages (or subpackages) - // - Set> classes = new HashSet<>(); - for (String basePackage : EUREKA_PACKAGES) { - Set beans = provider.findCandidateComponents(basePackage); - for (BeanDefinition bd : beans) { - Class cls = ClassUtils.resolveClassName(bd.getBeanClassName(), - resourceLoader.getClassLoader()); - classes.add(cls); - } - } - - // Construct the Jersey ResourceConfig - // - Map propsAndFeatures = new HashMap<>(); - propsAndFeatures.put( - // Skip static content used by the webapp - ServletContainer.PROPERTY_WEB_PAGE_CONTENT_REGEX, - EurekaConstants.DEFAULT_PREFIX + "/(fonts|images|css|js)/.*"); - - DefaultResourceConfig rc = new DefaultResourceConfig(classes); - rc.setPropertiesAndFeatures(propsAndFeatures); - - return rc; - } - - @Bean - public FilterRegistrationBean traceFilterRegistration( - @Qualifier("httpTraceFilter") Filter filter) { - FilterRegistrationBean bean = new FilterRegistrationBean(); - bean.setFilter(filter); - bean.setOrder(Ordered.LOWEST_PRECEDENCE - 10); - return bean; - } -} diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerBootstrap.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerBootstrap.java deleted file mode 100644 index c689a2ea..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerBootstrap.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server; - -import javax.servlet.ServletContext; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.DataCenterInfo; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.config.ConfigurationManager; -import com.netflix.discovery.EurekaClientConfig; -import com.netflix.discovery.converters.JsonXStream; -import com.netflix.discovery.converters.XmlXStream; -import com.netflix.eureka.EurekaServerConfig; -import com.netflix.eureka.EurekaServerContext; -import com.netflix.eureka.EurekaServerContextHolder; -import com.netflix.eureka.V1AwareInstanceInfoConverter; -import com.netflix.eureka.aws.AwsBinder; -import com.netflix.eureka.aws.AwsBinderDelegate; -import com.netflix.eureka.registry.PeerAwareInstanceRegistry; -import com.netflix.eureka.util.EurekaMonitors; -import com.thoughtworks.xstream.XStream; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * @author Spencer Gibb - */ -public class EurekaServerBootstrap { - - private static final Log log = LogFactory.getLog(EurekaServerBootstrap.class); - - private static final String TEST = "test"; - - private static final String ARCHAIUS_DEPLOYMENT_ENVIRONMENT = "archaius.deployment.environment"; - - private static final String EUREKA_ENVIRONMENT = "eureka.environment"; - - private static final String DEFAULT = "default"; - - private static final String ARCHAIUS_DEPLOYMENT_DATACENTER = "archaius.deployment.datacenter"; - - private static final String EUREKA_DATACENTER = "eureka.datacenter"; - - 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 { - initEurekaEnvironment(); - 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 initEurekaEnvironment() throws Exception { - log.info("Setting the eureka configuration.."); - - String dataCenter = ConfigurationManager.getConfigInstance() - .getString(EUREKA_DATACENTER); - if (dataCenter == null) { - log.info( - "Eureka data center value eureka.datacenter is not set, defaulting to default"); - ConfigurationManager.getConfigInstance() - .setProperty(ARCHAIUS_DEPLOYMENT_DATACENTER, DEFAULT); - } - else { - ConfigurationManager.getConfigInstance() - .setProperty(ARCHAIUS_DEPLOYMENT_DATACENTER, dataCenter); - } - String environment = ConfigurationManager.getConfigInstance() - .getString(EUREKA_ENVIRONMENT); - if (environment == null) { - ConfigurationManager.getConfigInstance() - .setProperty(ARCHAIUS_DEPLOYMENT_ENVIRONMENT, TEST); - log.info( - "Eureka environment value eureka.environment is not set, defaulting to test"); - } - else { - ConfigurationManager.getConfigInstance() - .setProperty(ARCHAIUS_DEPLOYMENT_ENVIRONMENT, environment); - } - } - - protected void initEurekaServerContext() throws Exception { - // 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(); - } - - /** - * Server context shutdown hook. Override for custom logic - */ - 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. - */ - 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; - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerConfigBean.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerConfigBean.java deleted file mode 100644 index 80c785d4..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerConfigBean.java +++ /dev/null @@ -1,1122 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.core.env.PropertyResolver; - -import com.netflix.eureka.EurekaServerConfig; -import com.netflix.eureka.aws.AwsBindingStrategy; -import org.springframework.core.style.ToStringCreator; - -/** - * @author Dave Syer - * @author Gregor Zurowski - */ -@ConfigurationProperties(EurekaServerConfigBean.PREFIX) -public class EurekaServerConfigBean implements EurekaServerConfig { - - public static final String PREFIX = "eureka.server"; - - private static final int MINUTES = 60 * 1000; - - @Autowired(required = false) - PropertyResolver propertyResolver; - - private String aWSAccessId; - - private String aWSSecretKey; - - private int eIPBindRebindRetries = 3; - - private int eIPBindingRetryIntervalMs = 5 * MINUTES; - - private int eIPBindingRetryIntervalMsWhenUnbound = 1 * MINUTES; - - private boolean enableSelfPreservation = true; - - private double renewalPercentThreshold = 0.85; - - private int renewalThresholdUpdateIntervalMs = 15 * MINUTES; - - private int peerEurekaNodesUpdateIntervalMs = 10 * MINUTES; - - private int numberOfReplicationRetries = 5; - - private int peerEurekaStatusRefreshTimeIntervalMs = 30 * 1000; - - private int waitTimeInMsWhenSyncEmpty = 5 * MINUTES; - - private int peerNodeConnectTimeoutMs = 200; - - private int peerNodeReadTimeoutMs = 200; - - private int peerNodeTotalConnections = 1000; - - private int peerNodeTotalConnectionsPerHost = 500; - - private int peerNodeConnectionIdleTimeoutSeconds = 30; - - private long retentionTimeInMSInDeltaQueue = 3 * MINUTES; - - private long deltaRetentionTimerIntervalInMs = 30 * 1000; - - private long evictionIntervalTimerInMs = 60 * 1000; - - private int aSGQueryTimeoutMs = 300; - - private long aSGUpdateIntervalMs = 5 * MINUTES; - - private long aSGCacheExpiryTimeoutMs = 10 * MINUTES; // defaults to longer than the - // asg update interval - - private long responseCacheAutoExpirationInSeconds = 180; - - private long responseCacheUpdateIntervalMs = 30 * 1000; - - private boolean useReadOnlyResponseCache = true; - - private boolean disableDelta; - - private long maxIdleThreadInMinutesAgeForStatusReplication = 10; - - private int minThreadsForStatusReplication = 1; - - private int maxThreadsForStatusReplication = 1; - - private int maxElementsInStatusReplicationPool = 10000; - - private boolean syncWhenTimestampDiffers = true; - - private int registrySyncRetries = 0; - - private long registrySyncRetryWaitMs = 30 * 1000; - - private int maxElementsInPeerReplicationPool = 10000; - - private long maxIdleThreadAgeInMinutesForPeerReplication = 15; - - private int minThreadsForPeerReplication = 5; - - private int maxThreadsForPeerReplication = 20; - - private int maxTimeForReplication = 30000; - - private boolean primeAwsReplicaConnections = true; - - private boolean disableDeltaForRemoteRegions; - - private int remoteRegionConnectTimeoutMs = 1000; - - private int remoteRegionReadTimeoutMs = 1000; - - private int remoteRegionTotalConnections = 1000; - - private int remoteRegionTotalConnectionsPerHost = 500; - - private int remoteRegionConnectionIdleTimeoutSeconds = 30; - - private boolean gZipContentFromRemoteRegion = true; - - private Map remoteRegionUrlsWithName = new HashMap<>(); - - private String[] remoteRegionUrls; - - private Map> remoteRegionAppWhitelist; - - private int remoteRegionRegistryFetchInterval = 30; - - private int remoteRegionFetchThreadPoolSize = 20; - - private String remoteRegionTrustStore = ""; - - private String remoteRegionTrustStorePassword = "changeit"; - - private boolean disableTransparentFallbackToOtherRegion; - - private boolean batchReplication; - - private boolean rateLimiterEnabled = false; - - private boolean rateLimiterThrottleStandardClients = false; - - private Set rateLimiterPrivilegedClients = Collections.emptySet(); - - private int rateLimiterBurstSize = 10; - - private int rateLimiterRegistryFetchAverageRate = 500; - - private int rateLimiterFullFetchAverageRate = 100; - - private boolean logIdentityHeaders = true; - - private String listAutoScalingGroupsRoleName = "ListAutoScalingGroups"; - - private boolean enableReplicatedRequestCompression = false; - - private String jsonCodecName; - - private String xmlCodecName; - - private int route53BindRebindRetries = 3; - - private int route53BindingRetryIntervalMs = 5 * MINUTES; - - private long route53DomainTTL = 30; - - private AwsBindingStrategy bindingStrategy = AwsBindingStrategy.EIP; - - private int minAvailableInstancesForPeerReplication = -1; - - @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 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; - } - - @Override - public String getJsonCodecName() { - return this.jsonCodecName; - } - - @Override - public String getXmlCodecName() { - return this.xmlCodecName; - } - - @Override - public boolean shouldUseReadOnlyResponseCache() { - return this.useReadOnlyResponseCache; - } - - @Override - public boolean shouldEnableReplicatedRequestCompression() { - return this.enableReplicatedRequestCompression; - } - - @Override - public String getExperimental(String name) { - if (this.propertyResolver != null) { - return this.propertyResolver.getProperty(PREFIX + ".experimental." + name, - String.class, null); - } - return null; - } - - @Override - public int getHealthStatusMinNumberOfAvailablePeers() { - return this.minAvailableInstancesForPeerReplication; - } - - public PropertyResolver getPropertyResolver() { - return propertyResolver; - } - - public void setPropertyResolver(PropertyResolver propertyResolver) { - this.propertyResolver = propertyResolver; - } - - public String getAWSAccessId() { - return aWSAccessId; - } - - public void setAWSAccessId(String aWSAccessId) { - this.aWSAccessId = aWSAccessId; - } - - public String getAWSSecretKey() { - return aWSSecretKey; - } - - public void setAWSSecretKey(String aWSSecretKey) { - this.aWSSecretKey = aWSSecretKey; - } - - public int getEIPBindRebindRetries() { - return eIPBindRebindRetries; - } - - public void setEIPBindRebindRetries(int eIPBindRebindRetries) { - this.eIPBindRebindRetries = eIPBindRebindRetries; - } - - public int getEIPBindingRetryIntervalMs() { - return eIPBindingRetryIntervalMs; - } - - public void setEIPBindingRetryIntervalMs(int eIPBindingRetryIntervalMs) { - this.eIPBindingRetryIntervalMs = eIPBindingRetryIntervalMs; - } - - public int getEIPBindingRetryIntervalMsWhenUnbound() { - return eIPBindingRetryIntervalMsWhenUnbound; - } - - public void setEIPBindingRetryIntervalMsWhenUnbound( - int eIPBindingRetryIntervalMsWhenUnbound) { - this.eIPBindingRetryIntervalMsWhenUnbound = eIPBindingRetryIntervalMsWhenUnbound; - } - - public boolean isEnableSelfPreservation() { - return enableSelfPreservation; - } - - public void setEnableSelfPreservation(boolean enableSelfPreservation) { - this.enableSelfPreservation = enableSelfPreservation; - } - - @Override - public double getRenewalPercentThreshold() { - return renewalPercentThreshold; - } - - public void setRenewalPercentThreshold(double renewalPercentThreshold) { - this.renewalPercentThreshold = renewalPercentThreshold; - } - - @Override - public int getRenewalThresholdUpdateIntervalMs() { - return renewalThresholdUpdateIntervalMs; - } - - public void setRenewalThresholdUpdateIntervalMs( - int renewalThresholdUpdateIntervalMs) { - this.renewalThresholdUpdateIntervalMs = renewalThresholdUpdateIntervalMs; - } - - @Override - public int getPeerEurekaNodesUpdateIntervalMs() { - return peerEurekaNodesUpdateIntervalMs; - } - - public void setPeerEurekaNodesUpdateIntervalMs(int peerEurekaNodesUpdateIntervalMs) { - this.peerEurekaNodesUpdateIntervalMs = peerEurekaNodesUpdateIntervalMs; - } - - @Override - public int getNumberOfReplicationRetries() { - return numberOfReplicationRetries; - } - - public void setNumberOfReplicationRetries(int numberOfReplicationRetries) { - this.numberOfReplicationRetries = numberOfReplicationRetries; - } - - @Override - public int getPeerEurekaStatusRefreshTimeIntervalMs() { - return peerEurekaStatusRefreshTimeIntervalMs; - } - - public void setPeerEurekaStatusRefreshTimeIntervalMs( - int peerEurekaStatusRefreshTimeIntervalMs) { - this.peerEurekaStatusRefreshTimeIntervalMs = peerEurekaStatusRefreshTimeIntervalMs; - } - - @Override - public int getWaitTimeInMsWhenSyncEmpty() { - return waitTimeInMsWhenSyncEmpty; - } - - public void setWaitTimeInMsWhenSyncEmpty(int waitTimeInMsWhenSyncEmpty) { - this.waitTimeInMsWhenSyncEmpty = waitTimeInMsWhenSyncEmpty; - } - - @Override - public int getPeerNodeConnectTimeoutMs() { - return peerNodeConnectTimeoutMs; - } - - public void setPeerNodeConnectTimeoutMs(int peerNodeConnectTimeoutMs) { - this.peerNodeConnectTimeoutMs = peerNodeConnectTimeoutMs; - } - - @Override - public int getPeerNodeReadTimeoutMs() { - return peerNodeReadTimeoutMs; - } - - public void setPeerNodeReadTimeoutMs(int peerNodeReadTimeoutMs) { - this.peerNodeReadTimeoutMs = peerNodeReadTimeoutMs; - } - - @Override - public int getPeerNodeTotalConnections() { - return peerNodeTotalConnections; - } - - public void setPeerNodeTotalConnections(int peerNodeTotalConnections) { - this.peerNodeTotalConnections = peerNodeTotalConnections; - } - - @Override - public int getPeerNodeTotalConnectionsPerHost() { - return peerNodeTotalConnectionsPerHost; - } - - public void setPeerNodeTotalConnectionsPerHost(int peerNodeTotalConnectionsPerHost) { - this.peerNodeTotalConnectionsPerHost = peerNodeTotalConnectionsPerHost; - } - - @Override - public int getPeerNodeConnectionIdleTimeoutSeconds() { - return peerNodeConnectionIdleTimeoutSeconds; - } - - public void setPeerNodeConnectionIdleTimeoutSeconds( - int peerNodeConnectionIdleTimeoutSeconds) { - this.peerNodeConnectionIdleTimeoutSeconds = peerNodeConnectionIdleTimeoutSeconds; - } - - @Override - public long getRetentionTimeInMSInDeltaQueue() { - return retentionTimeInMSInDeltaQueue; - } - - public void setRetentionTimeInMSInDeltaQueue(long retentionTimeInMSInDeltaQueue) { - this.retentionTimeInMSInDeltaQueue = retentionTimeInMSInDeltaQueue; - } - - @Override - public long getDeltaRetentionTimerIntervalInMs() { - return deltaRetentionTimerIntervalInMs; - } - - public void setDeltaRetentionTimerIntervalInMs(long deltaRetentionTimerIntervalInMs) { - this.deltaRetentionTimerIntervalInMs = deltaRetentionTimerIntervalInMs; - } - - @Override - public long getEvictionIntervalTimerInMs() { - return evictionIntervalTimerInMs; - } - - public void setEvictionIntervalTimerInMs(long evictionIntervalTimerInMs) { - this.evictionIntervalTimerInMs = evictionIntervalTimerInMs; - } - - public int getASGQueryTimeoutMs() { - return aSGQueryTimeoutMs; - } - - public void setASGQueryTimeoutMs(int aSGQueryTimeoutMs) { - this.aSGQueryTimeoutMs = aSGQueryTimeoutMs; - } - - public long getASGUpdateIntervalMs() { - return aSGUpdateIntervalMs; - } - - public void setASGUpdateIntervalMs(long aSGUpdateIntervalMs) { - this.aSGUpdateIntervalMs = aSGUpdateIntervalMs; - } - - public long getASGCacheExpiryTimeoutMs() { - return aSGCacheExpiryTimeoutMs; - } - - public void setASGCacheExpiryTimeoutMs(long aSGCacheExpiryTimeoutMs) { - this.aSGCacheExpiryTimeoutMs = aSGCacheExpiryTimeoutMs; - } - - @Override - public long getResponseCacheAutoExpirationInSeconds() { - return responseCacheAutoExpirationInSeconds; - } - - public void setResponseCacheAutoExpirationInSeconds( - long responseCacheAutoExpirationInSeconds) { - this.responseCacheAutoExpirationInSeconds = responseCacheAutoExpirationInSeconds; - } - - @Override - public long getResponseCacheUpdateIntervalMs() { - return responseCacheUpdateIntervalMs; - } - - public void setResponseCacheUpdateIntervalMs(long responseCacheUpdateIntervalMs) { - this.responseCacheUpdateIntervalMs = responseCacheUpdateIntervalMs; - } - - public boolean isUseReadOnlyResponseCache() { - return useReadOnlyResponseCache; - } - - public void setUseReadOnlyResponseCache(boolean useReadOnlyResponseCache) { - this.useReadOnlyResponseCache = useReadOnlyResponseCache; - } - - public boolean isDisableDelta() { - return disableDelta; - } - - public void setDisableDelta(boolean disableDelta) { - this.disableDelta = disableDelta; - } - - @Override - public long getMaxIdleThreadInMinutesAgeForStatusReplication() { - return maxIdleThreadInMinutesAgeForStatusReplication; - } - - public void setMaxIdleThreadInMinutesAgeForStatusReplication( - long maxIdleThreadInMinutesAgeForStatusReplication) { - this.maxIdleThreadInMinutesAgeForStatusReplication = maxIdleThreadInMinutesAgeForStatusReplication; - } - - @Override - public int getMinThreadsForStatusReplication() { - return minThreadsForStatusReplication; - } - - public void setMinThreadsForStatusReplication(int minThreadsForStatusReplication) { - this.minThreadsForStatusReplication = minThreadsForStatusReplication; - } - - @Override - public int getMaxThreadsForStatusReplication() { - return maxThreadsForStatusReplication; - } - - public void setMaxThreadsForStatusReplication(int maxThreadsForStatusReplication) { - this.maxThreadsForStatusReplication = maxThreadsForStatusReplication; - } - - @Override - public int getMaxElementsInStatusReplicationPool() { - return maxElementsInStatusReplicationPool; - } - - public void setMaxElementsInStatusReplicationPool( - int maxElementsInStatusReplicationPool) { - this.maxElementsInStatusReplicationPool = maxElementsInStatusReplicationPool; - } - - public boolean isSyncWhenTimestampDiffers() { - return syncWhenTimestampDiffers; - } - - public void setSyncWhenTimestampDiffers(boolean syncWhenTimestampDiffers) { - this.syncWhenTimestampDiffers = syncWhenTimestampDiffers; - } - - @Override - public int getRegistrySyncRetries() { - return registrySyncRetries; - } - - public void setRegistrySyncRetries(int registrySyncRetries) { - this.registrySyncRetries = registrySyncRetries; - } - - @Override - public long getRegistrySyncRetryWaitMs() { - return registrySyncRetryWaitMs; - } - - public void setRegistrySyncRetryWaitMs(long registrySyncRetryWaitMs) { - this.registrySyncRetryWaitMs = registrySyncRetryWaitMs; - } - - @Override - public int getMaxElementsInPeerReplicationPool() { - return maxElementsInPeerReplicationPool; - } - - public void setMaxElementsInPeerReplicationPool( - int maxElementsInPeerReplicationPool) { - this.maxElementsInPeerReplicationPool = maxElementsInPeerReplicationPool; - } - - @Override - public long getMaxIdleThreadAgeInMinutesForPeerReplication() { - return maxIdleThreadAgeInMinutesForPeerReplication; - } - - public void setMaxIdleThreadAgeInMinutesForPeerReplication( - long maxIdleThreadAgeInMinutesForPeerReplication) { - this.maxIdleThreadAgeInMinutesForPeerReplication = maxIdleThreadAgeInMinutesForPeerReplication; - } - - @Override - public int getMinThreadsForPeerReplication() { - return minThreadsForPeerReplication; - } - - public void setMinThreadsForPeerReplication(int minThreadsForPeerReplication) { - this.minThreadsForPeerReplication = minThreadsForPeerReplication; - } - - @Override - public int getMaxThreadsForPeerReplication() { - return maxThreadsForPeerReplication; - } - - public void setMaxThreadsForPeerReplication(int maxThreadsForPeerReplication) { - this.maxThreadsForPeerReplication = maxThreadsForPeerReplication; - } - - @Override - public int getMaxTimeForReplication() { - return maxTimeForReplication; - } - - public void setMaxTimeForReplication(int maxTimeForReplication) { - this.maxTimeForReplication = maxTimeForReplication; - } - - public boolean isPrimeAwsReplicaConnections() { - return primeAwsReplicaConnections; - } - - public void setPrimeAwsReplicaConnections(boolean primeAwsReplicaConnections) { - this.primeAwsReplicaConnections = primeAwsReplicaConnections; - } - - public boolean isDisableDeltaForRemoteRegions() { - return disableDeltaForRemoteRegions; - } - - public void setDisableDeltaForRemoteRegions(boolean disableDeltaForRemoteRegions) { - this.disableDeltaForRemoteRegions = disableDeltaForRemoteRegions; - } - - @Override - public int getRemoteRegionConnectTimeoutMs() { - return remoteRegionConnectTimeoutMs; - } - - public void setRemoteRegionConnectTimeoutMs(int remoteRegionConnectTimeoutMs) { - this.remoteRegionConnectTimeoutMs = remoteRegionConnectTimeoutMs; - } - - @Override - public int getRemoteRegionReadTimeoutMs() { - return remoteRegionReadTimeoutMs; - } - - public void setRemoteRegionReadTimeoutMs(int remoteRegionReadTimeoutMs) { - this.remoteRegionReadTimeoutMs = remoteRegionReadTimeoutMs; - } - - @Override - public int getRemoteRegionTotalConnections() { - return remoteRegionTotalConnections; - } - - public void setRemoteRegionTotalConnections(int remoteRegionTotalConnections) { - this.remoteRegionTotalConnections = remoteRegionTotalConnections; - } - - @Override - public int getRemoteRegionTotalConnectionsPerHost() { - return remoteRegionTotalConnectionsPerHost; - } - - public void setRemoteRegionTotalConnectionsPerHost( - int remoteRegionTotalConnectionsPerHost) { - this.remoteRegionTotalConnectionsPerHost = remoteRegionTotalConnectionsPerHost; - } - - @Override - public int getRemoteRegionConnectionIdleTimeoutSeconds() { - return remoteRegionConnectionIdleTimeoutSeconds; - } - - public void setRemoteRegionConnectionIdleTimeoutSeconds( - int remoteRegionConnectionIdleTimeoutSeconds) { - this.remoteRegionConnectionIdleTimeoutSeconds = remoteRegionConnectionIdleTimeoutSeconds; - } - - public boolean isgZipContentFromRemoteRegion() { - return gZipContentFromRemoteRegion; - } - - public void setgZipContentFromRemoteRegion(boolean gZipContentFromRemoteRegion) { - this.gZipContentFromRemoteRegion = gZipContentFromRemoteRegion; - } - - @Override - public Map getRemoteRegionUrlsWithName() { - return remoteRegionUrlsWithName; - } - - public void setRemoteRegionUrlsWithName( - Map remoteRegionUrlsWithName) { - this.remoteRegionUrlsWithName = remoteRegionUrlsWithName; - } - - @Override - public String[] getRemoteRegionUrls() { - return remoteRegionUrls; - } - - public void setRemoteRegionUrls(String[] remoteRegionUrls) { - this.remoteRegionUrls = remoteRegionUrls; - } - - public Map> getRemoteRegionAppWhitelist() { - return remoteRegionAppWhitelist; - } - - public void setRemoteRegionAppWhitelist( - Map> remoteRegionAppWhitelist) { - this.remoteRegionAppWhitelist = remoteRegionAppWhitelist; - } - - @Override - public int getRemoteRegionRegistryFetchInterval() { - return remoteRegionRegistryFetchInterval; - } - - public void setRemoteRegionRegistryFetchInterval( - int remoteRegionRegistryFetchInterval) { - this.remoteRegionRegistryFetchInterval = remoteRegionRegistryFetchInterval; - } - - @Override - public int getRemoteRegionFetchThreadPoolSize() { - return remoteRegionFetchThreadPoolSize; - } - - public void setRemoteRegionFetchThreadPoolSize(int remoteRegionFetchThreadPoolSize) { - this.remoteRegionFetchThreadPoolSize = remoteRegionFetchThreadPoolSize; - } - - @Override - public String getRemoteRegionTrustStore() { - return remoteRegionTrustStore; - } - - public void setRemoteRegionTrustStore(String remoteRegionTrustStore) { - this.remoteRegionTrustStore = remoteRegionTrustStore; - } - - @Override - public String getRemoteRegionTrustStorePassword() { - return remoteRegionTrustStorePassword; - } - - public void setRemoteRegionTrustStorePassword(String remoteRegionTrustStorePassword) { - this.remoteRegionTrustStorePassword = remoteRegionTrustStorePassword; - } - - public boolean isDisableTransparentFallbackToOtherRegion() { - return disableTransparentFallbackToOtherRegion; - } - - public void setDisableTransparentFallbackToOtherRegion( - boolean disableTransparentFallbackToOtherRegion) { - this.disableTransparentFallbackToOtherRegion = disableTransparentFallbackToOtherRegion; - } - - public boolean isBatchReplication() { - return batchReplication; - } - - public void setBatchReplication(boolean batchReplication) { - this.batchReplication = batchReplication; - } - - @Override - public boolean isRateLimiterEnabled() { - return rateLimiterEnabled; - } - - public void setRateLimiterEnabled(boolean rateLimiterEnabled) { - this.rateLimiterEnabled = rateLimiterEnabled; - } - - @Override - public boolean isRateLimiterThrottleStandardClients() { - return rateLimiterThrottleStandardClients; - } - - public void setRateLimiterThrottleStandardClients( - boolean rateLimiterThrottleStandardClients) { - this.rateLimiterThrottleStandardClients = rateLimiterThrottleStandardClients; - } - - @Override - public Set getRateLimiterPrivilegedClients() { - return rateLimiterPrivilegedClients; - } - - public void setRateLimiterPrivilegedClients( - Set rateLimiterPrivilegedClients) { - this.rateLimiterPrivilegedClients = rateLimiterPrivilegedClients; - } - - @Override - public int getRateLimiterBurstSize() { - return rateLimiterBurstSize; - } - - public void setRateLimiterBurstSize(int rateLimiterBurstSize) { - this.rateLimiterBurstSize = rateLimiterBurstSize; - } - - @Override - public int getRateLimiterRegistryFetchAverageRate() { - return rateLimiterRegistryFetchAverageRate; - } - - public void setRateLimiterRegistryFetchAverageRate( - int rateLimiterRegistryFetchAverageRate) { - this.rateLimiterRegistryFetchAverageRate = rateLimiterRegistryFetchAverageRate; - } - - @Override - public int getRateLimiterFullFetchAverageRate() { - return rateLimiterFullFetchAverageRate; - } - - public void setRateLimiterFullFetchAverageRate(int rateLimiterFullFetchAverageRate) { - this.rateLimiterFullFetchAverageRate = rateLimiterFullFetchAverageRate; - } - - public boolean isLogIdentityHeaders() { - return logIdentityHeaders; - } - - public void setLogIdentityHeaders(boolean logIdentityHeaders) { - this.logIdentityHeaders = logIdentityHeaders; - } - - @Override - public String getListAutoScalingGroupsRoleName() { - return listAutoScalingGroupsRoleName; - } - - public void setListAutoScalingGroupsRoleName(String listAutoScalingGroupsRoleName) { - this.listAutoScalingGroupsRoleName = listAutoScalingGroupsRoleName; - } - - public boolean isEnableReplicatedRequestCompression() { - return enableReplicatedRequestCompression; - } - - public void setEnableReplicatedRequestCompression( - boolean enableReplicatedRequestCompression) { - this.enableReplicatedRequestCompression = enableReplicatedRequestCompression; - } - - public void setJsonCodecName(String jsonCodecName) { - this.jsonCodecName = jsonCodecName; - } - - public void setXmlCodecName(String xmlCodecName) { - this.xmlCodecName = xmlCodecName; - } - - @Override - public int getRoute53BindRebindRetries() { - return route53BindRebindRetries; - } - - public void setRoute53BindRebindRetries(int route53BindRebindRetries) { - this.route53BindRebindRetries = route53BindRebindRetries; - } - - @Override - public int getRoute53BindingRetryIntervalMs() { - return route53BindingRetryIntervalMs; - } - - public void setRoute53BindingRetryIntervalMs(int route53BindingRetryIntervalMs) { - this.route53BindingRetryIntervalMs = route53BindingRetryIntervalMs; - } - - @Override - public long getRoute53DomainTTL() { - return route53DomainTTL; - } - - public void setRoute53DomainTTL(long route53DomainTTL) { - this.route53DomainTTL = route53DomainTTL; - } - - @Override - public AwsBindingStrategy getBindingStrategy() { - return bindingStrategy; - } - - public void setBindingStrategy(AwsBindingStrategy bindingStrategy) { - this.bindingStrategy = bindingStrategy; - } - - public int getMinAvailableInstancesForPeerReplication() { - return minAvailableInstancesForPeerReplication; - } - - public void setMinAvailableInstancesForPeerReplication( - int minAvailableInstancesForPeerReplication) { - this.minAvailableInstancesForPeerReplication = minAvailableInstancesForPeerReplication; - } - - @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - EurekaServerConfigBean that = (EurekaServerConfigBean) o; - return aSGCacheExpiryTimeoutMs == that.aSGCacheExpiryTimeoutMs && - aSGQueryTimeoutMs == that.aSGQueryTimeoutMs && - aSGUpdateIntervalMs == that.aSGUpdateIntervalMs && - Objects.equals(aWSAccessId, that.aWSAccessId) && - Objects.equals(aWSSecretKey, that.aWSSecretKey) && - batchReplication == that.batchReplication && - bindingStrategy == that.bindingStrategy && - deltaRetentionTimerIntervalInMs == that.deltaRetentionTimerIntervalInMs && - disableDelta == that.disableDelta && - disableDeltaForRemoteRegions == that.disableDeltaForRemoteRegions && - disableTransparentFallbackToOtherRegion == that.disableTransparentFallbackToOtherRegion && - eIPBindingRetryIntervalMs == that.eIPBindingRetryIntervalMs && - eIPBindingRetryIntervalMsWhenUnbound == that.eIPBindingRetryIntervalMsWhenUnbound && - eIPBindRebindRetries == that.eIPBindRebindRetries && - enableReplicatedRequestCompression == that.enableReplicatedRequestCompression && - enableSelfPreservation == that.enableSelfPreservation && - evictionIntervalTimerInMs == that.evictionIntervalTimerInMs && - gZipContentFromRemoteRegion == that.gZipContentFromRemoteRegion && - Objects.equals(jsonCodecName, that.jsonCodecName) && - Objects.equals(listAutoScalingGroupsRoleName, that.listAutoScalingGroupsRoleName) && - logIdentityHeaders == that.logIdentityHeaders && - maxElementsInPeerReplicationPool == that.maxElementsInPeerReplicationPool && - maxElementsInStatusReplicationPool == that.maxElementsInStatusReplicationPool && - maxIdleThreadAgeInMinutesForPeerReplication == that.maxIdleThreadAgeInMinutesForPeerReplication && - maxIdleThreadInMinutesAgeForStatusReplication == that.maxIdleThreadInMinutesAgeForStatusReplication && - maxThreadsForPeerReplication == that.maxThreadsForPeerReplication && - maxThreadsForStatusReplication == that.maxThreadsForStatusReplication && - maxTimeForReplication == that.maxTimeForReplication && - minAvailableInstancesForPeerReplication == that.minAvailableInstancesForPeerReplication && - minThreadsForPeerReplication == that.minThreadsForPeerReplication && - minThreadsForStatusReplication == that.minThreadsForStatusReplication && - numberOfReplicationRetries == that.numberOfReplicationRetries && - peerEurekaNodesUpdateIntervalMs == that.peerEurekaNodesUpdateIntervalMs && - peerEurekaStatusRefreshTimeIntervalMs == that.peerEurekaStatusRefreshTimeIntervalMs && - peerNodeConnectionIdleTimeoutSeconds == that.peerNodeConnectionIdleTimeoutSeconds && - peerNodeConnectTimeoutMs == that.peerNodeConnectTimeoutMs && - peerNodeReadTimeoutMs == that.peerNodeReadTimeoutMs && - peerNodeTotalConnections == that.peerNodeTotalConnections && - peerNodeTotalConnectionsPerHost == that.peerNodeTotalConnectionsPerHost && - primeAwsReplicaConnections == that.primeAwsReplicaConnections && - Objects.equals(propertyResolver, that.propertyResolver) && - rateLimiterBurstSize == that.rateLimiterBurstSize && - rateLimiterEnabled == that.rateLimiterEnabled && - rateLimiterFullFetchAverageRate == that.rateLimiterFullFetchAverageRate && - Objects.equals(rateLimiterPrivilegedClients, that.rateLimiterPrivilegedClients) && - rateLimiterRegistryFetchAverageRate == that.rateLimiterRegistryFetchAverageRate && - rateLimiterThrottleStandardClients == that.rateLimiterThrottleStandardClients && - registrySyncRetries == that.registrySyncRetries && - registrySyncRetryWaitMs == that.registrySyncRetryWaitMs && - Objects.equals(remoteRegionAppWhitelist, that.remoteRegionAppWhitelist) && - remoteRegionConnectionIdleTimeoutSeconds == that.remoteRegionConnectionIdleTimeoutSeconds && - remoteRegionConnectTimeoutMs == that.remoteRegionConnectTimeoutMs && - remoteRegionFetchThreadPoolSize == that.remoteRegionFetchThreadPoolSize && - remoteRegionReadTimeoutMs == that.remoteRegionReadTimeoutMs && - remoteRegionRegistryFetchInterval == that.remoteRegionRegistryFetchInterval && - remoteRegionTotalConnections == that.remoteRegionTotalConnections && - remoteRegionTotalConnectionsPerHost == that.remoteRegionTotalConnectionsPerHost && - Objects.equals(remoteRegionTrustStore, that.remoteRegionTrustStore) && - Objects.equals(remoteRegionTrustStorePassword, that.remoteRegionTrustStorePassword) && - Arrays.equals(remoteRegionUrls, that.remoteRegionUrls) && - Objects.equals(remoteRegionUrlsWithName, that.remoteRegionUrlsWithName) && - Double.compare(that.renewalPercentThreshold, renewalPercentThreshold) == 0 && - renewalThresholdUpdateIntervalMs == that.renewalThresholdUpdateIntervalMs && - responseCacheAutoExpirationInSeconds == that.responseCacheAutoExpirationInSeconds && - responseCacheUpdateIntervalMs == that.responseCacheUpdateIntervalMs && - retentionTimeInMSInDeltaQueue == that.retentionTimeInMSInDeltaQueue && - route53BindingRetryIntervalMs == that.route53BindingRetryIntervalMs && - route53BindRebindRetries == that.route53BindRebindRetries && - route53DomainTTL == that.route53DomainTTL && - syncWhenTimestampDiffers == that.syncWhenTimestampDiffers && - useReadOnlyResponseCache == that.useReadOnlyResponseCache && - waitTimeInMsWhenSyncEmpty == that.waitTimeInMsWhenSyncEmpty && - Objects.equals(xmlCodecName, that.xmlCodecName); - } - - @Override - public int hashCode() { - return Objects.hash(aSGCacheExpiryTimeoutMs, aSGQueryTimeoutMs, - aSGUpdateIntervalMs, aWSAccessId, aWSSecretKey, batchReplication, - bindingStrategy, deltaRetentionTimerIntervalInMs, disableDelta, - disableDeltaForRemoteRegions, - disableTransparentFallbackToOtherRegion, eIPBindRebindRetries, - eIPBindingRetryIntervalMs, eIPBindingRetryIntervalMsWhenUnbound, - enableReplicatedRequestCompression, enableSelfPreservation, - evictionIntervalTimerInMs, gZipContentFromRemoteRegion, - jsonCodecName, listAutoScalingGroupsRoleName, logIdentityHeaders, - maxElementsInPeerReplicationPool, maxElementsInStatusReplicationPool, - maxIdleThreadAgeInMinutesForPeerReplication, - maxIdleThreadInMinutesAgeForStatusReplication, - maxThreadsForPeerReplication, maxThreadsForStatusReplication, - maxTimeForReplication, minAvailableInstancesForPeerReplication, - minThreadsForPeerReplication, minThreadsForStatusReplication, - numberOfReplicationRetries, peerEurekaNodesUpdateIntervalMs, - peerEurekaStatusRefreshTimeIntervalMs, peerNodeConnectTimeoutMs, - peerNodeConnectionIdleTimeoutSeconds, peerNodeReadTimeoutMs, - peerNodeTotalConnections, peerNodeTotalConnectionsPerHost, - primeAwsReplicaConnections, propertyResolver, rateLimiterBurstSize, - rateLimiterEnabled, rateLimiterFullFetchAverageRate, - rateLimiterPrivilegedClients, rateLimiterRegistryFetchAverageRate, - rateLimiterThrottleStandardClients, registrySyncRetries, - registrySyncRetryWaitMs, remoteRegionAppWhitelist, - remoteRegionConnectTimeoutMs, - remoteRegionConnectionIdleTimeoutSeconds, - remoteRegionFetchThreadPoolSize, remoteRegionReadTimeoutMs, - remoteRegionRegistryFetchInterval, remoteRegionTotalConnections, - remoteRegionTotalConnectionsPerHost, remoteRegionTrustStore, - remoteRegionTrustStorePassword, remoteRegionUrls, - remoteRegionUrlsWithName, renewalPercentThreshold, - renewalThresholdUpdateIntervalMs, - responseCacheAutoExpirationInSeconds, - responseCacheUpdateIntervalMs, retentionTimeInMSInDeltaQueue, - route53BindRebindRetries, route53BindingRetryIntervalMs, - route53DomainTTL, syncWhenTimestampDiffers, - useReadOnlyResponseCache, waitTimeInMsWhenSyncEmpty, xmlCodecName); - } - - @Override - public String toString() { - return new ToStringCreator(this) - .append("aSGCacheExpiryTimeoutMs", this.aSGCacheExpiryTimeoutMs) - .append("aSGQueryTimeoutMs", this.aSGQueryTimeoutMs) - .append("aSGUpdateIntervalMs", this.aSGUpdateIntervalMs) - .append("aWSAccessId", this.aWSAccessId) - .append("aWSSecretKey", this.aWSSecretKey) - .append("batchReplication", this.batchReplication) - .append("bindingStrategy", this.bindingStrategy) - .append("deltaRetentionTimerIntervalInMs", this.deltaRetentionTimerIntervalInMs) - .append("disableDelta", this.disableDelta) - .append("disableDeltaForRemoteRegions", this.disableDeltaForRemoteRegions) - .append("disableTransparentFallbackToOtherRegion", this.disableTransparentFallbackToOtherRegion) - .append("eIPBindRebindRetries", this.eIPBindRebindRetries) - .append("eIPBindingRetryIntervalMs", this.eIPBindingRetryIntervalMs) - .append("eIPBindingRetryIntervalMsWhenUnbound", this.eIPBindingRetryIntervalMsWhenUnbound) - .append("enableReplicatedRequestCompression", this.enableReplicatedRequestCompression) - .append("enableSelfPreservation", this.enableSelfPreservation) - .append("evictionIntervalTimerInMs", this.evictionIntervalTimerInMs) - .append("gZipContentFromRemoteRegion", this.gZipContentFromRemoteRegion) - .append("jsonCodecName", this.jsonCodecName) - .append("listAutoScalingGroupsRoleName", this.listAutoScalingGroupsRoleName) - .append("logIdentityHeaders", this.logIdentityHeaders) - .append("maxElementsInPeerReplicationPool", this.maxElementsInPeerReplicationPool) - .append("maxElementsInStatusReplicationPool", this.maxElementsInStatusReplicationPool) - .append("maxIdleThreadAgeInMinutesForPeerReplication", this.maxIdleThreadAgeInMinutesForPeerReplication) - .append("maxIdleThreadInMinutesAgeForStatusReplication", this.maxIdleThreadInMinutesAgeForStatusReplication) - .append("maxThreadsForPeerReplication", this.maxThreadsForPeerReplication) - .append("maxThreadsForStatusReplication", this.maxThreadsForStatusReplication) - .append("maxTimeForReplication", this.maxTimeForReplication) - .append("minAvailableInstancesForPeerReplication", this.minAvailableInstancesForPeerReplication) - .append("minThreadsForPeerReplication", this.minThreadsForPeerReplication) - .append("minThreadsForStatusReplication", this.minThreadsForStatusReplication) - .append("numberOfReplicationRetries", this.numberOfReplicationRetries) - .append("peerEurekaNodesUpdateIntervalMs", this.peerEurekaNodesUpdateIntervalMs) - .append("peerEurekaStatusRefreshTimeIntervalMs", this.peerEurekaStatusRefreshTimeIntervalMs) - .append("peerNodeConnectTimeoutMs", this.peerNodeConnectTimeoutMs) - .append("peerNodeConnectionIdleTimeoutSeconds", this.peerNodeConnectionIdleTimeoutSeconds) - .append("peerNodeReadTimeoutMs", this.peerNodeReadTimeoutMs) - .append("peerNodeTotalConnections", this.peerNodeTotalConnections) - .append("peerNodeTotalConnectionsPerHost", this.peerNodeTotalConnectionsPerHost) - .append("primeAwsReplicaConnections", this.primeAwsReplicaConnections) - .append("propertyResolver", this.propertyResolver) - .append("rateLimiterBurstSize", this.rateLimiterBurstSize) - .append("rateLimiterEnabled", this.rateLimiterEnabled) - .append("rateLimiterFullFetchAverageRate", this.rateLimiterFullFetchAverageRate) - .append("rateLimiterPrivilegedClients", this.rateLimiterPrivilegedClients) - .append("rateLimiterRegistryFetchAverageRate", this.rateLimiterRegistryFetchAverageRate) - .append("rateLimiterThrottleStandardClients", this.rateLimiterThrottleStandardClients) - .append("registrySyncRetries", this.registrySyncRetries) - .append("registrySyncRetryWaitMs", this.registrySyncRetryWaitMs) - .append("remoteRegionAppWhitelist", this.remoteRegionAppWhitelist) - .append("remoteRegionConnectTimeoutMs", this.remoteRegionConnectTimeoutMs) - .append("remoteRegionConnectionIdleTimeoutSeconds", this.remoteRegionConnectionIdleTimeoutSeconds) - .append("remoteRegionFetchThreadPoolSize", this.remoteRegionFetchThreadPoolSize) - .append("remoteRegionReadTimeoutMs", this.remoteRegionReadTimeoutMs) - .append("remoteRegionRegistryFetchInterval", this.remoteRegionRegistryFetchInterval) - .append("remoteRegionTotalConnections", this.remoteRegionTotalConnections) - .append("remoteRegionTotalConnectionsPerHost", this.remoteRegionTotalConnectionsPerHost) - .append("remoteRegionTrustStore", this.remoteRegionTrustStore) - .append("remoteRegionTrustStorePassword", this.remoteRegionTrustStorePassword) - .append("remoteRegionUrls", this.remoteRegionUrls) - .append("remoteRegionUrlsWithName", this.remoteRegionUrlsWithName) - .append("renewalPercentThreshold", this.renewalPercentThreshold) - .append("renewalThresholdUpdateIntervalMs", this.renewalThresholdUpdateIntervalMs) - .append("responseCacheAutoExpirationInSeconds", this.responseCacheAutoExpirationInSeconds) - .append("responseCacheUpdateIntervalMs", this.responseCacheUpdateIntervalMs) - .append("retentionTimeInMSInDeltaQueue", this.retentionTimeInMSInDeltaQueue) - .append("route53BindRebindRetries", this.route53BindRebindRetries) - .append("route53BindingRetryIntervalMs", this.route53BindingRetryIntervalMs) - .append("route53DomainTTL", this.route53DomainTTL) - .append("syncWhenTimestampDiffers", this.syncWhenTimestampDiffers) - .append("useReadOnlyResponseCache", this.useReadOnlyResponseCache) - .append("waitTimeInMsWhenSyncEmpty", this.waitTimeInMsWhenSyncEmpty) - .append("xmlCodecName", this.xmlCodecName) - .toString(); - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerInitializerConfiguration.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerInitializerConfiguration.java deleted file mode 100644 index 5a8d5ca1..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerInitializerConfiguration.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server; - -import javax.servlet.ServletContext; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.netflix.eureka.server.event.EurekaRegistryAvailableEvent; -import org.springframework.cloud.netflix.eureka.server.event.EurekaServerStartedEvent; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationEvent; -import org.springframework.context.SmartLifecycle; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.Ordered; -import org.springframework.web.context.ServletContextAware; - -import com.netflix.eureka.EurekaServerConfig; - -/** - * @author Dave Syer - */ -@Configuration -public 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 int order = 1; - - @Override - public void setServletContext(ServletContext servletContext) { - this.servletContext = servletContext; - } - - @Override - public void start() { - new Thread(new Runnable() { - @Override - public void run() { - 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(); - } - - 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 void stop(Runnable callback) { - callback.run(); - } - - @Override - public int getOrder() { - return this.order; - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerMarkerConfiguration.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerMarkerConfiguration.java deleted file mode 100644 index 20ab2b4a..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerMarkerConfiguration.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Responsible for adding in a marker bean to activate - * {@link EurekaServerAutoConfiguration} - * - * @author Biju Kunjummen - */ -@Configuration -public class EurekaServerMarkerConfiguration { - - @Bean - public Marker eurekaServerMarkerBean() { - return new Marker(); - } - - class Marker { - } -} diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistry.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistry.java deleted file mode 100644 index 4ef2568f..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistry.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server; - -import java.util.List; - -import com.netflix.eureka.lease.Lease; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.BeansException; -import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceCanceledEvent; -import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRegisteredEvent; -import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRenewedEvent; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.EurekaClientConfig; -import com.netflix.discovery.shared.Application; -import com.netflix.eureka.EurekaServerConfig; -import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl; -import com.netflix.eureka.resources.ServerCodecs; - -import org.springframework.context.ApplicationEvent; - -/** - * @author Spencer Gibb - */ -public class InstanceRegistry extends PeerAwareInstanceRegistryImpl - implements ApplicationContextAware { - - private static final Log log = LogFactory.getLog(InstanceRegistry.class); - - private ApplicationContext ctxt; - private int defaultOpenForTrafficCount; - - public InstanceRegistry(EurekaServerConfig serverConfig, - EurekaClientConfig clientConfig, ServerCodecs serverCodecs, - EurekaClient eurekaClient, int expectedNumberOfRenewsPerMin, - int defaultOpenForTrafficCount) { - super(serverConfig, clientConfig, serverCodecs, eurekaClient); - - this.expectedNumberOfRenewsPerMin = expectedNumberOfRenewsPerMin; - 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) { - handleRegistration(info, leaseDuration, isReplication); - super.register(info, leaseDuration, isReplication); - } - - @Override - public void register(final InstanceInfo info, final boolean isReplication) { - handleRegistration(info, resolveInstanceLeaseDuration(info), isReplication); - super.register(info, isReplication); - } - - @Override - public boolean cancel(String appName, String serverId, boolean isReplication) { - handleCancelation(appName, serverId, isReplication); - return super.cancel(appName, serverId, isReplication); - } - - @Override - public boolean renew(final String appName, final String serverId, - boolean isReplication) { - log("renew " + appName + " serverId " + serverId + ", isReplication {}" - + isReplication); - List applications = getSortedApplications(); - for (Application input : applications) { - if (input.getName().equals(appName)) { - InstanceInfo instance = null; - for (InstanceInfo info : input.getInstances()) { - if (info.getId().equals(serverId)) { - instance = info; - break; - } - } - publishEvent(new EurekaInstanceRenewedEvent(this, appName, serverId, - instance, isReplication)); - break; - } - } - return super.renew(appName, serverId, isReplication); - } - - @Override - protected boolean internalCancel(String appName, String id, boolean isReplication) { - handleCancelation(appName, id, isReplication); - return super.internalCancel(appName, id, isReplication); - } - - private void handleCancelation(String appName, String id, boolean isReplication) { - log("cancel " + appName + ", serverId " + id + ", isReplication " + isReplication); - publishEvent(new EurekaInstanceCanceledEvent(this, appName, id, isReplication)); - } - - private void handleRegistration(InstanceInfo info, int leaseDuration, - boolean isReplication) { - log("register " + info.getAppName() + ", vip " + info.getVIPAddress() - + ", leaseDuration " + leaseDuration + ", isReplication " - + isReplication); - publishEvent(new EurekaInstanceRegisteredEvent(this, info, leaseDuration, - isReplication)); - } - - 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; - } -} diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistryProperties.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistryProperties.java deleted file mode 100644 index 87a0ebac..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistryProperties.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.eureka.server; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.properties.ConfigurationProperties; - -import static org.springframework.cloud.netflix.eureka.server.InstanceRegistryProperties.PREFIX; - -/** - * @author Spencer Gibb - */ -@ConfigurationProperties(PREFIX) -public class InstanceRegistryProperties { - - public static final String PREFIX = "eureka.instance.registry"; - - - /* Default number of expected renews per minute, defaults to 1. - * Setting expectedNumberOfRenewsPerMin to non-zero to ensure that even an isolated - * server can adjust its eviction policy to the number of registrations (when it's - * zero, even a successful registration won't reset the rate threshold in - * InstanceRegistry.register()). - */ - @Value("${eureka.server.expectedNumberOfRenewsPerMin:1}") // for backwards compatibility - private int expectedNumberOfRenewsPerMin = 1; - - /** Value used in determining when leases are cancelled, default to 1 for standalone. - * Should be set to 0 for peer replicated eurekas */ - @Value("${eureka.server.defaultOpenForTrafficCount:1}") // for backwards compatibility - private int defaultOpenForTrafficCount = 1; - - public int getExpectedNumberOfRenewsPerMin() { - return expectedNumberOfRenewsPerMin; - } - - public void setExpectedNumberOfRenewsPerMin(int expectedNumberOfRenewsPerMin) { - this.expectedNumberOfRenewsPerMin = expectedNumberOfRenewsPerMin; - } - - public int getDefaultOpenForTrafficCount() { - return defaultOpenForTrafficCount; - } - - public void setDefaultOpenForTrafficCount(int defaultOpenForTrafficCount) { - this.defaultOpenForTrafficCount = defaultOpenForTrafficCount; - } -} diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceCanceledEvent.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceCanceledEvent.java deleted file mode 100644 index 9db92f1f..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceCanceledEvent.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server.event; - -import org.springframework.context.ApplicationEvent; - -import java.util.Objects; - -/** - * @author Spencer Gibb - * @author Gregor Zurowski - */ -@SuppressWarnings("serial") -public 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) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - EurekaInstanceCanceledEvent that = (EurekaInstanceCanceledEvent) o; - return Objects.equals(appName, that.appName) && - Objects.equals(serverId, that.serverId) && - replication == replication; - } - - @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(); - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceRegisteredEvent.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceRegisteredEvent.java deleted file mode 100644 index 87c91dce..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceRegisteredEvent.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server.event; - -import org.springframework.context.ApplicationEvent; - -import com.netflix.appinfo.InstanceInfo; - -import java.util.Objects; - -/** - * @author Spencer Gibb - * @author Gregor Zurowski - */ -@SuppressWarnings("serial") -public 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) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - EurekaInstanceRegisteredEvent that = (EurekaInstanceRegisteredEvent) o; - return Objects.equals(instanceInfo, that.instanceInfo) && - leaseDuration == leaseDuration && - replication == replication; - } - - @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(); - } -} diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceRenewedEvent.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceRenewedEvent.java deleted file mode 100644 index e04b95a2..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceRenewedEvent.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server.event; - -import org.springframework.context.ApplicationEvent; - -import com.netflix.appinfo.InstanceInfo; - -import java.util.Objects; - -/** - * @author Spencer Gibb - * @author Gregor Zurowski - */ -@SuppressWarnings("serial") -public 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) { - 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; - } - - @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(); - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaRegistryAvailableEvent.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaRegistryAvailableEvent.java deleted file mode 100644 index 588dca22..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaRegistryAvailableEvent.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server.event; - -import org.springframework.context.ApplicationEvent; - -import com.netflix.eureka.EurekaServerConfig; - -/** - * @author Dave Syer - */ -@SuppressWarnings("serial") -public class EurekaRegistryAvailableEvent extends ApplicationEvent { - - /** - * @param eurekaServerConfig - */ - public EurekaRegistryAvailableEvent(EurekaServerConfig eurekaServerConfig) { - super(eurekaServerConfig); - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaServerStartedEvent.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaServerStartedEvent.java deleted file mode 100644 index 4b9f7ced..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaServerStartedEvent.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server.event; - -import org.springframework.context.ApplicationEvent; - -import com.netflix.eureka.EurekaServerConfig; - -/** - * @author Dave Syer - */ -@SuppressWarnings("serial") -public class EurekaServerStartedEvent extends ApplicationEvent { - - /** - * @param eurekaServerConfig - */ - public EurekaServerStartedEvent(EurekaServerConfig eurekaServerConfig) { - super(eurekaServerConfig); - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/META-INF/spring.factories b/spring-cloud-netflix-eureka-server/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 1ce4b307..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - org.springframework.cloud.netflix.eureka.server.EurekaServerAutoConfiguration \ No newline at end of file diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/eureka/server.properties b/spring-cloud-netflix-eureka-server/src/main/resources/eureka/server.properties deleted file mode 100644 index 02c4c287..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/resources/eureka/server.properties +++ /dev/null @@ -1 +0,0 @@ -spring.http.encoding.force=false \ No newline at end of file diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/montserrat-webfont.eot b/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/montserrat-webfont.eot deleted file mode 100644 index 0caea916..00000000 Binary files a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/montserrat-webfont.eot and /dev/null differ diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/montserrat-webfont.svg b/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/montserrat-webfont.svg deleted file mode 100644 index 7bd96bdf..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/montserrat-webfont.svg +++ /dev/null @@ -1,1283 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/montserrat-webfont.ttf b/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/montserrat-webfont.ttf deleted file mode 100644 index 9953fe62..00000000 Binary files a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/montserrat-webfont.ttf and /dev/null differ diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/montserrat-webfont.woff b/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/montserrat-webfont.woff deleted file mode 100644 index eb49333f..00000000 Binary files a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/montserrat-webfont.woff and /dev/null differ diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/varela_round-webfont.eot b/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/varela_round-webfont.eot deleted file mode 100644 index dfee0c26..00000000 Binary files a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/varela_round-webfont.eot and /dev/null differ diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/varela_round-webfont.svg b/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/varela_round-webfont.svg deleted file mode 100644 index 3280e2c4..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/varela_round-webfont.svg +++ /dev/null @@ -1,7875 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/varela_round-webfont.ttf b/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/varela_round-webfont.ttf deleted file mode 100644 index 3ca06669..00000000 Binary files a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/varela_round-webfont.ttf and /dev/null differ diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/varela_round-webfont.woff b/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/varela_round-webfont.woff deleted file mode 100644 index 77ba1661..00000000 Binary files a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/fonts/varela_round-webfont.woff and /dev/null differ diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/404-icon.png b/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/404-icon.png deleted file mode 100644 index 912f456b..00000000 Binary files a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/404-icon.png and /dev/null differ diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/homepage-bg.jpg b/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/homepage-bg.jpg deleted file mode 100644 index 03184376..00000000 Binary files a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/homepage-bg.jpg and /dev/null differ diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/platform-bg.png b/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/platform-bg.png deleted file mode 100644 index 51218583..00000000 Binary files a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/platform-bg.png and /dev/null differ diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/platform-spring-xd.png b/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/platform-spring-xd.png deleted file mode 100644 index 0cb2662d..00000000 Binary files a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/platform-spring-xd.png and /dev/null differ diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/spring-logo-eureka-mobile.png b/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/spring-logo-eureka-mobile.png deleted file mode 100644 index fc59a236..00000000 Binary files a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/spring-logo-eureka-mobile.png and /dev/null differ diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/spring-logo-eureka.png b/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/spring-logo-eureka.png deleted file mode 100644 index b22de1f2..00000000 Binary files a/spring-cloud-netflix-eureka-server/src/main/resources/static/eureka/images/spring-logo-eureka.png and /dev/null differ diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/templates/eureka/header.ftl b/spring-cloud-netflix-eureka-server/src/main/resources/templates/eureka/header.ftl deleted file mode 100644 index b1be17c2..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/resources/templates/eureka/header.ftl +++ /dev/null @@ -1,26 +0,0 @@ -<#import "/spring.ftl" as spring /> - - - diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/templates/eureka/lastn.ftl b/spring-cloud-netflix-eureka-server/src/main/resources/templates/eureka/lastn.ftl deleted file mode 100644 index 94e02017..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/resources/templates/eureka/lastn.ftl +++ /dev/null @@ -1,71 +0,0 @@ -<#import "/spring.ftl" as spring /> - - - - - - - - Eureka - Last N events - - - - - - - <#include "header.ftl"> - -
- <#include "navbar.ftl"> - -
- -
-
- - - - - - <#if lastNCanceled?has_content> - <#list lastNCanceled as entry> - - - <#else> - - - -
TimestampLease
${entry.date?datetime}${entry.id}
No results available
-
-
- - - - - - <#if lastNRegistered?has_content> - <#list lastNRegistered as entry> - - - <#else> - - - -
TimestampLease
${entry.date?datetime}${entry.id}
No results available
-
-
-
-
- - - - diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/templates/eureka/navbar.ftl b/spring-cloud-netflix-eureka-server/src/main/resources/templates/eureka/navbar.ftl deleted file mode 100644 index 7bf5e7df..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/resources/templates/eureka/navbar.ftl +++ /dev/null @@ -1,71 +0,0 @@ -

System Status

-
-
- - <#if amazonInfo??> - - - - - - - - - - - - - - - - - - - - - -
EUREKA SERVERAMI: ${amiId!}
Zone${availabilityZone!}
instance-id${instanceId!}
Environment${environment!}
Data center${datacenter!}
-
-
- - - - - - - - - - - - - - - - - - - - - -
Current time${currentTime}
Uptime${upTime}
Lease expiration enabled${registry.leaseExpirationEnabled?c}
Renews threshold${registry.numOfRenewsPerMinThreshold}
Renews (last min)${registry.numOfRenewsInLastMin}
-
-
- -<#if isBelowRenewThresold> - <#if !registry.selfPreservationModeEnabled> -

RENEWALS ARE LESSER THAN THE THRESHOLD. THE SELF PRESERVATION MODE IS TURNED OFF.THIS MAY NOT PROTECT INSTANCE EXPIRY IN CASE OF NETWORK/OTHER PROBLEMS.

- <#else> -

EMERGENCY! EUREKA MAY BE INCORRECTLY CLAIMING INSTANCES ARE UP WHEN THEY'RE NOT. RENEWALS ARE LESSER THAN THRESHOLD AND HENCE THE INSTANCES ARE NOT BEING EXPIRED JUST TO BE SAFE.

- -<#elseif !registry.selfPreservationModeEnabled> -

THE SELF PRESERVATION MODE IS TURNED OFF.THIS MAY NOT PROTECT INSTANCE EXPIRY IN CASE OF NETWORK/OTHER PROBLEMS.

- - -

DS Replicas

- - diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/templates/eureka/status.ftl b/spring-cloud-netflix-eureka-server/src/main/resources/templates/eureka/status.ftl deleted file mode 100755 index de6e660c..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/resources/templates/eureka/status.ftl +++ /dev/null @@ -1,113 +0,0 @@ -<#import "/spring.ftl" as spring /> - - - - - - - - - - Eureka - - - - - - - - - <#include "header.ftl"> -
- <#include "navbar.ftl"> -

Instances currently registered with Eureka

- - - - - - <#if apps?has_content> - <#list apps as app> - - - - - - - - <#else> - - - - -
ApplicationAMIsAvailability ZonesStatus
${app.name} - <#list app.amiCounts as amiCount> - ${amiCount.key} (${amiCount.value})<#if amiCount_has_next>, - - - <#list app.zoneCounts as zoneCount> - ${zoneCount.key} (${zoneCount.value})<#if zoneCount_has_next>, - - - <#list app.instanceInfos as instanceInfo> - <#if instanceInfo.isNotUp> - - - ${instanceInfo.status} (${instanceInfo.instances?size}) - - <#if instanceInfo.isNotUp> - - - <#list instanceInfo.instances as instance> - <#if instance.isHref> - ${instance.id} - <#else> - ${instance.id} - <#if instance_has_next>, - - -
No instances available
- -

General Info

- - - - - - - <#list statusInfo.generalStats?keys as stat> - - - - - <#list statusInfo.applicationStats?keys as stat> - - - - - -
NameValue
${stat}${statusInfo.generalStats[stat]!""}
${stat}${statusInfo.applicationStats[stat]!""}
- -

Instance Info

- - - - - - - <#list instanceInfo?keys as key> - - - - - -
NameValue
${key}${instanceInfo[key]!""}
-
- - - - diff --git a/spring-cloud-netflix-eureka-server/src/main/wro/header.less b/spring-cloud-netflix-eureka-server/src/main/wro/header.less deleted file mode 100644 index 7c08593c..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/wro/header.less +++ /dev/null @@ -1,73 +0,0 @@ -.navbar { - border-top: 4px solid #6db33f; - background-color: #34302d; - margin-bottom: 0px; - border-bottom: 0; - border-left: 0; - border-right: 0; -} - -.navbar a.navbar-brand { - background: url("../images/spring-logo-eureka.png") -1px -1px no-repeat; - margin: 12px 0 6px; - width: 300px; - height: 46px; - display: inline-block; - text-decoration: none; - padding: 0; -} - -.navbar a.navbar-brand span { - display: block; - width: 300px; - height: 46px; - background: url("../images/spring-logo-eureka.png") -1px -48px no-repeat; - opacity: 0; - -moz-transition: opacity 0.12s ease-in-out; - -webkit-transition: opacity 0.12s ease-in-out; - -o-transition: opacity 0.12s ease-in-out; -} - -.navbar a:hover.navbar-brand span { - opacity: 1; -} - -.navbar li > a, .navbar-text { - font-family: "montserratregular", sans-serif; - text-shadow: none; - font-size: 14px; - -/* line-height: 14px; */ - padding: 28px 20px; - transition: all 0.15s; - -webkit-transition: all 0.15s; - -moz-transition: all 0.15s; - -o-transition: all 0.15s; - -ms-transition: all 0.15s; -} - -.navbar li > a { - text-transform: uppercase; -} - -.navbar .navbar-text { - margin-top: 0; - margin-bottom: 0; -} -.navbar li:hover > a { - color: #eeeeee; - background-color: #6db33f; -} - -.navbar-toggle { - border-width: 0; - - .icon-bar + .icon-bar { - margin-top: 3px; - } - .icon-bar { - width: 19px; - height: 3px; - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/main/wro/main.less b/spring-cloud-netflix-eureka-server/src/main/wro/main.less deleted file mode 100644 index 648a37ce..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/wro/main.less +++ /dev/null @@ -1,143 +0,0 @@ -@spring-green: #6db33f; -@spring-dark-green: #5fa134; -@spring-brown: #34302D; -@spring-grey: #838789; -@spring-light-grey: #f1f1f1; - -@body-bg: @spring-light-grey; -@text-color: @spring-light-grey; -@link-color: @spring-dark-green; -@link-hover-color: @spring-dark-green; - -@navbar-default-link-color: @spring-light-grey; -@navbar-default-link-active-color: @spring-light-grey; -@navbar-default-link-hover-color: @spring-light-grey; -@navbar-default-link-hover-bg: @spring-green; -@navbar-default-toggle-icon-bar-bg: @spring-light-grey; -@navbar-default-toggle-hover-bg: transparent; -@navbar-default-link-active-bg: @spring-green; - -@border-radius-base: 0; -@border-radius-large: 0; -@border-radius-small: 0; - -@btn-default-color: @spring-light-grey; -@btn-default-bg: @spring-brown; -@btn-default-border: @spring-green; - -@nav-tabs-active-link-hover-color: @spring-light-grey; -@nav-tabs-active-link-hover-bg: @spring-brown; -@nav-tabs-active-link-hover-border-color: @spring-brown; -@nav-tabs-border-color: @spring-brown; -@table-border-color: @spring-brown; - -@import "typography.less"; -@import "header.less"; - -.table > thead > tr > th { - background-color: lighten(@spring-brown, 3%); - color: @spring-light-grey; -} - -.table-filter { - background-color: @spring-brown; - padding: 9px 12px; -} - -.nav > li > a { - color: @spring-grey; -} - -.btn-default { - border-width: 2px; - transition: border 0.15s; - -webkit-transition: border 0.15s; - -moz-transition: border 0.15s; - -o-transition: border 0.15s; - -ms-transition: border 0.15s; - - &:hover, - &:focus, - &:active, - &.active, - .open .dropdown-toggle& { - background-color: @spring-brown; - border-color: @spring-brown; - } -} - - -.container .text-muted { - margin: 20px 0; -} - -code { - font-size: 80%; -} - -.xd-container { - margin-top: 40px; - margin-bottom: 100px; -} - -h1 { - margin-bottom: 15px -} - -.index-page--subtitle { - font-size: 16px; - line-height: 24px; - margin: 0 0 30px; -} - -.form-horizontal button.btn-inverse { - margin-left: 32px; -} - -#job-params-modal .modal-dialog { - width: 90%; - margin-left:auto; - margin-right:auto; -} - -[ng-cloak].splash { - display: block !important; -} -[ng-cloak] { - display: none; -} - -.splash { - background: @spring-green; - color: @spring-brown; - display: none; -} - -.error-page { - margin-top: 100px; - text-align: center; -} - -.error-page .error-title { - font-size: 24px; - line-height: 24px; - margin: 30px 0 0; -} - -table td { - vertical-align: middle !important; -} - -table td .progress { - margin-bottom: 0; -} - -table td.action-column { - width: 1px; -} - -.help-block { - color: lighten(@text-color, 0%); // lighten the text some for contrast -} - -@import "responsive.less"; \ No newline at end of file diff --git a/spring-cloud-netflix-eureka-server/src/main/wro/responsive.less b/spring-cloud-netflix-eureka-server/src/main/wro/responsive.less deleted file mode 100644 index 8a59e9c6..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/wro/responsive.less +++ /dev/null @@ -1,41 +0,0 @@ -@media (max-width: 768px) { - .navbar-toggle { - position:absolute; - z-index: 9999; - left:0px; - top:0px; - } - - .navbar a.navbar-brand { - display: block; - margin: 0 auto 0 auto; - width: 200px; - height: 50px; - float: none; - background: url("../images/spring-logo-eureka-mobile.png") 0 center no-repeat; - } - - .homepage-billboard .homepage-subtitle { - font-size: 21px; - line-height: 21px; - } - - .navbar a.navbar-brand span { - display: none; - } - - .navbar { - border-top-width: 0; - } - - .xd-container { - margin-top: 20px; - margin-bottom: 30px; - } - - .index-page--subtitle { - margin-top: 10px; - margin-bottom: 30px; - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/main/wro/typography.less b/spring-cloud-netflix-eureka-server/src/main/wro/typography.less deleted file mode 100644 index 3fd13406..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/wro/typography.less +++ /dev/null @@ -1,59 +0,0 @@ -@font-face { - font-family: 'varela_roundregular'; - src: url('../fonts/varela_round-webfont.eot'); - src: url('../fonts/varela_round-webfont.eot?#iefix') format('embedded-opentype'), - url('../fonts/varela_round-webfont.woff') format('woff'), - url('../fonts/varela_round-webfont.ttf') format('truetype'), - url('../fonts/varela_round-webfont.svg#varela_roundregular') format('svg'); - font-weight: normal; - font-style: normal; -} - -@font-face { - font-family: 'montserratregular'; - src: url('../fonts/montserrat-webfont.eot'); - src: url('../fonts/montserrat-webfont.eot?#iefix') format('embedded-opentype'), - url('../fonts/montserrat-webfont.woff') format('woff'), - url('../fonts/montserrat-webfont.ttf') format('truetype'), - url('../fonts/montserrat-webfont.svg#montserratregular') format('svg'); - font-weight: normal; - font-style: normal; -} - -body, h1, h2, h3, p, input { - margin: 0; - font-weight: 400; - font-family: "varela_roundregular", sans-serif; - color: #34302d; -} - -h1 { - font-size: 24px; - line-height: 30px; - font-family: "montserratregular", sans-serif; -} - -h2 { - font-size: 18px; - font-weight: 700; - line-height: 24px; - margin-bottom: 10px; - font-family: "montserratregular", sans-serif; -} - -h3 { - font-size: 16px; - line-height: 24px; - margin-bottom: 10px; - font-weight: 700; -} - -p { - //font-size: 15px; - //line-height: 24px; -} - -strong { - font-weight: 700; - font-family: "montserratregular", sans-serif; -} diff --git a/spring-cloud-netflix-eureka-server/src/main/wro/wro.properties b/spring-cloud-netflix-eureka-server/src/main/wro/wro.properties deleted file mode 100644 index 7b3312a4..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/wro/wro.properties +++ /dev/null @@ -1,4 +0,0 @@ -#List of preProcessors -preProcessors=cssImport -#List of postProcessors -postProcessors=less4j,jsMin \ No newline at end of file diff --git a/spring-cloud-netflix-eureka-server/src/main/wro/wro.xml b/spring-cloud-netflix-eureka-server/src/main/wro/wro.xml deleted file mode 100644 index 47f1a5f3..00000000 --- a/spring-cloud-netflix-eureka-server/src/main/wro/wro.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - webjar:bootstrap/3.2.0/less/bootstrap.less - file:@.project.basedir.@/src/main/wro/main.less - webjar:jquery/2.1.1/jquery.min.js - webjar:bootstrap/3.2.0/js/bootstrap.min.js - - \ No newline at end of file diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationContextTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationContextTests.java deleted file mode 100644 index 50a5a9ee..00000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationContextTests.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.eureka.server; - -import java.util.Collections; -import java.util.Map; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.netflix.eureka.server.ApplicationContextTests.Application; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, - properties = {"spring.application.name=eureka", "server.servlet.context-path=/context", - "management.security.enabled=false", "management.endpoints.web.expose=*" }) -public class ApplicationContextTests { - private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); - - @LocalServerPort - private int port = 0; - - @Test - public void catalogLoads() { - @SuppressWarnings("rawtypes") - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/context/eureka/apps", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Test - public void dashboardLoads() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/context/", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - String body = entity.getBody(); - // System.err.println(body); - assertTrue(body.contains("eureka/js")); - assertTrue(body.contains("eureka/css")); - // The "DS Replicas" - assertTrue( - body.contains("localhost")); - } - - @Test - public void cssAvailable() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/context/eureka/css/wro.css", - String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Test - public void jsAvailable() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/context/eureka/js/wro.js", - String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Test - public void adminLoads() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); - - @SuppressWarnings("rawtypes") - ResponseEntity entity = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/context" + BASE_PATH + "/env", HttpMethod.GET, - new HttpEntity<>("parameters", headers), Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Configuration - @EnableAutoConfiguration - @EnableEurekaServer - protected static class Application { - } -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationDashboardDisabledTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationDashboardDisabledTests.java deleted file mode 100644 index 69b9abaa..00000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationDashboardDisabledTests.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server; - -import static org.junit.Assert.assertEquals; - -import java.util.Map; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.cloud.netflix.eureka.server.ApplicationContextTests.Application; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { "spring.application.name=eureka", - "eureka.dashboard.enabled=false" }) -public class ApplicationDashboardDisabledTests { - - @Value("${local.server.port}") - private int port = 0; - - @Test - public void catalogLoads() { - @SuppressWarnings("rawtypes") - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/eureka/apps", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Test - public void dashboardLoads() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/", String.class); - assertEquals(HttpStatus.NOT_FOUND, entity.getStatusCode()); - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationDashboardPathTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationDashboardPathTests.java deleted file mode 100644 index d3fd0004..00000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationDashboardPathTests.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Map; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.cloud.netflix.eureka.server.ApplicationContextTests.Application; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { - "spring.application.name=eureka", "eureka.dashboard.path=/dashboard" }) -public class ApplicationDashboardPathTests { - - @Value("${local.server.port}") - private int port = 0; - - @Test - public void catalogLoads() { - @SuppressWarnings("rawtypes") - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/eureka/apps", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Test - public void dashboardLoads() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/dashboard", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - String body = entity.getBody(); - // System.err.println(body); - assertTrue(body.contains("eureka/js")); - assertTrue(body.contains("eureka/css")); - // The "DS Replicas" - assertTrue( - body.contains("localhost")); - // The Home - assertTrue(body.contains("Home")); - // The Lastn - assertTrue(body.contains("Last")); - } - - @Test - public void cssAvailable() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/eureka/css/wro.css", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Test - public void jsAvailable() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/eureka/js/wro.js", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationServletPathTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationServletPathTests.java deleted file mode 100644 index 5cca9faf..00000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationServletPathTests.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server; - -import java.util.Collections; -import java.util.Map; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.netflix.eureka.server.ApplicationServletPathTests.Application; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = RANDOM_PORT, properties = { - "spring.application.name=eureka", "server.servlet.path=/servlet", - "management.security.enabled=false", "management.endpoints.web.expose=*" }) -public class ApplicationServletPathTests { - private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); - - @LocalServerPort - private int port = 0; - - @Configuration - @EnableAutoConfiguration - @EnableEurekaServer - protected static class Application { - } - - @Test - public void catalogLoads() { - @SuppressWarnings("rawtypes") - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/eureka/apps", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Test - public void dashboardLoads() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/servlet/", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - String body = entity.getBody(); - // System.err.println(body); - assertTrue(body.contains("eureka/js")); - assertTrue(body.contains("eureka/css")); - // The "DS Replicas" - assertTrue( - body.contains("localhost")); - } - - @Test - public void cssAvailable() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/servlet/eureka/css/wro.css", - String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Test - public void jsAvailable() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/servlet/eureka/js/wro.js", - String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Test - public void adminLoads() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); - - @SuppressWarnings("rawtypes") - ResponseEntity entity = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/servlet" + BASE_PATH + "/env", HttpMethod.GET, - new HttpEntity<>("parameters", headers), Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationTests.java deleted file mode 100644 index 8f6ff698..00000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationTests.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server; - -import java.util.Collections; -import java.util.Map; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.netflix.eureka.server.ApplicationTests.Application; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; - -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.converters.wrappers.CodecWrapper; -import com.netflix.eureka.resources.ServerCodecs; - -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = RANDOM_PORT, properties = { - "spring.jmx.enabled=true", "management.security.enabled=false", "management.endpoints.web.expose=*" }) -public class ApplicationTests { - private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); - - @LocalServerPort - private int port = 0; - - @Autowired - private ServerCodecs serverCodecs; - - @Test - public void catalogLoads() { - @SuppressWarnings("rawtypes") - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/eureka/apps", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Test - public void adminLoads() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); - - @SuppressWarnings("rawtypes") - ResponseEntity entity = new TestRestTemplate().exchange( - "http://localhost:" + this.port + BASE_PATH + "/env", HttpMethod.GET, - new HttpEntity<>("parameters", headers), Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Test - public void noDoubleSlashes() { - String basePath = "http://localhost:" + this.port + "/"; - ResponseEntity entity = new TestRestTemplate().getForEntity(basePath, - String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - String body = entity.getBody(); - assertNotNull(body); - assertFalse("basePath contains double slashes", body.contains(basePath + "/")); - } - - @Test - public void cssParsedByLess() { - String basePath = "http://localhost:" + this.port + "/eureka/css/wro.css"; - ResponseEntity entity = new TestRestTemplate().getForEntity(basePath, - String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - String body = entity.getBody(); - assertNotNull(body); - assertTrue("css wasn't preprocessed", body.contains("spring-logo")); - } - - @Test - public void customCodecWorks() throws Exception { - assertThat("serverCodecs is wrong type", this.serverCodecs, - is(instanceOf(EurekaServerAutoConfiguration.CloudServerCodecs.class))); - CodecWrapper codec = this.serverCodecs.getFullJsonCodec(); - assertThat("codec is wrong type", codec, is(instanceOf(CloudJacksonJson.class))); - - InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("fooapp") - .add("instanceId", "foo").build(); - String encoded = codec.encode(instanceInfo); - InstanceInfo decoded = codec.decode(encoded, InstanceInfo.class); - assertThat("instanceId was wrong", decoded.getInstanceId(), is("foo")); - } - - @Configuration - @EnableAutoConfiguration - @EnableEurekaServer - protected static class Application { - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerReplicasTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerReplicasTests.java deleted file mode 100644 index 4ce33e4f..00000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerReplicasTests.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.springframework.cloud.netflix.eureka.server; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; -import static org.springframework.cloud.netflix.eureka.server.EurekaControllerTests.setInstance; - -import java.util.HashMap; -import java.util.Map; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.InstanceInfo; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.netflix.eureka.util.StatusInfo; - -public class EurekaControllerReplicasTests { - - String noAuthList1 = "http://test1.com"; - String noAuthList2 = noAuthList1 + ",http://test2.com"; - - String authList1 = "http://user:pwd@test1.com"; - String authList2 = authList1 + ",http://user2:pwd2@test2.com"; - - String combinationAuthList1 = "http://test1.com,http://user2:pwd2@test2.com"; - String combinationAuthList2 = "http://test3.com,http://user4:pwd4@test4.com"; - - String combinationNoAuthList1 = "http://test1.com,http://test2.com"; - String combinationNoAuthList2 = "http://test3.com,http://test4.com"; - - String totalAutoList = combinationAuthList1 + "," + combinationAuthList2; - String totalNoAutoList = combinationNoAuthList1 + "," + combinationNoAuthList2; - - String empty = new String(); - - private ApplicationInfoManager original; - private InstanceInfo instanceInfo; - - @Before - public void setup() throws Exception { - this.original = ApplicationInfoManager.getInstance(); - setInstance(mock(ApplicationInfoManager.class)); - instanceInfo = mock(InstanceInfo.class); - } - - @After - public void teardown() throws Exception { - setInstance(this.original); - instanceInfo = null; - } - - @Test - public void testFilterReplicasNoAuth() throws Exception { - Map model = new HashMap<>(); - StatusInfo statusInfo = StatusInfo.Builder.newBuilder() - .add("registered-replicas", empty) - .add("available-replicas", noAuthList1) - .add("unavailable-replicas", noAuthList2) - .withInstanceInfo(this.instanceInfo).build(); - EurekaController controller = new EurekaController(null); - - controller.filterReplicas(model, statusInfo); - - @SuppressWarnings("unchecked") - Map results = (Map) model.get("applicationStats"); - assertEquals(empty, results.get("registered-replicas")); - assertEquals(noAuthList1, results.get("available-replicas")); - assertEquals(noAuthList2, results.get("unavailable-replicas")); - - } - - @Test - public void testFilterReplicasAuth() throws Exception { - Map model = new HashMap<>(); - StatusInfo statusInfo = StatusInfo.Builder.newBuilder() - .add("registered-replicas", authList2) - .add("available-replicas", authList1) - .add("unavailable-replicas", empty) - .withInstanceInfo(instanceInfo).build(); - EurekaController controller = new EurekaController(null); - - controller.filterReplicas(model, statusInfo); - - @SuppressWarnings("unchecked") - Map results = (Map) model.get("applicationStats"); - assertEquals(empty, results.get("unavailable-replicas")); - assertEquals(noAuthList1, results.get("available-replicas")); - assertEquals(noAuthList2, results.get("registered-replicas")); - - } - - @Test - public void testFilterReplicasAuthWithCombinationList() throws Exception { - Map model = new HashMap<>(); - StatusInfo statusInfo = StatusInfo.Builder.newBuilder() - .add("registered-replicas", totalAutoList) - .add("available-replicas", combinationAuthList1) - .add("unavailable-replicas", combinationAuthList2) - .withInstanceInfo(instanceInfo).build(); - EurekaController controller = new EurekaController(null); - - controller.filterReplicas(model, statusInfo); - - @SuppressWarnings("unchecked") - Map results = (Map) model.get("applicationStats"); - assertEquals(totalNoAutoList, results.get("registered-replicas")); - assertEquals(combinationNoAuthList1, results.get("available-replicas")); - assertEquals(combinationNoAuthList2, results.get("unavailable-replicas")); - - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerTests.java deleted file mode 100644 index 62e74022..00000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerTests.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.eureka.server; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.util.ReflectionUtils; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.DataCenterInfo; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.appinfo.MyDataCenterInfo; -import com.netflix.discovery.shared.Application; -import com.netflix.eureka.EurekaServerContext; -import com.netflix.eureka.EurekaServerContextHolder; -import com.netflix.eureka.cluster.PeerEurekaNode; -import com.netflix.eureka.cluster.PeerEurekaNodes; -import com.netflix.eureka.registry.PeerAwareInstanceRegistry; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class EurekaControllerTests { - - private ApplicationInfoManager infoManager; - private ApplicationInfoManager original; - - @Before - public void setup() throws Exception { - PeerEurekaNodes peerEurekaNodes = mock(PeerEurekaNodes.class); - when(peerEurekaNodes.getPeerNodesView()).thenReturn(Collections.emptyList()); - - InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() - .setAppName("test") - .setDataCenterInfo(new MyDataCenterInfo(DataCenterInfo.Name.MyOwn)) - .build(); - - this.infoManager = mock(ApplicationInfoManager.class); - this.original = ApplicationInfoManager.getInstance(); - setInstance(this.infoManager); - when(this.infoManager.getInfo()).thenReturn(instanceInfo); - - Application myapp = new Application("myapp"); - myapp.addInstance(InstanceInfo.Builder.newBuilder() - .setAppName("myapp") - .setDataCenterInfo(new MyDataCenterInfo(DataCenterInfo.Name.MyOwn)) - .setInstanceId("myapp:1") - .build()); - - ArrayList applications = new ArrayList<>(); - applications.add(myapp); - - PeerAwareInstanceRegistry registry = mock(PeerAwareInstanceRegistry.class); - when(registry.getSortedApplications()).thenReturn(applications); - - EurekaServerContext serverContext = mock(EurekaServerContext.class); - EurekaServerContextHolder.initialize(serverContext); - when(serverContext.getRegistry()).thenReturn(registry); - when(serverContext.getPeerEurekaNodes()).thenReturn(peerEurekaNodes); - when(serverContext.getApplicationInfoManager()).thenReturn(this.infoManager); - - } - - @After - public void teardown() throws Exception { - setInstance(this.original); - } - - static void setInstance(ApplicationInfoManager infoManager) throws IllegalAccessException { - Field instance = ReflectionUtils.findField(ApplicationInfoManager.class, "instance"); - ReflectionUtils.makeAccessible(instance); - instance.set(null, infoManager); - } - - @Test - public void testStatus() throws Exception { - Map model = new HashMap<>(); - - EurekaController controller = new EurekaController(infoManager); - - controller.status(new MockHttpServletRequest("GET", "/"), model); - - Map app = getFirst(model, "apps"); - Map instanceInfo = getFirst(app, "instanceInfos"); - Map instance = getFirst(instanceInfo, "instances"); - - assertThat("id was wrong", (String)instance.get("id"), is(equalTo("myapp:1"))); - assertThat("url was not null", instance.get("url"), is(nullValue())); - assertThat("isHref was wrong", (Boolean)instance.get("isHref"), is(false)); - } - - @SuppressWarnings("unchecked") - Map getFirst(Map model, String key) { - List> apps = (List>) model.get(key); - assertThat(key +" was wrong size", apps, is(hasSize(1))); - return apps.get(0); - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaCustomPeerNodesTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaCustomPeerNodesTests.java deleted file mode 100644 index dc69ead8..00000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaCustomPeerNodesTests.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.eureka.server; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.discovery.EurekaClientConfig; -import com.netflix.eureka.EurekaServerConfig; -import com.netflix.eureka.cluster.PeerEurekaNodes; -import com.netflix.eureka.registry.PeerAwareInstanceRegistry; -import com.netflix.eureka.resources.ServerCodecs; - -import static org.junit.Assert.assertTrue; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = EurekaCustomPeerNodesTests.Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, value = { - "spring.application.name=eureka", "server.contextPath=/context", - "management.security.enabled=false" }) -public class EurekaCustomPeerNodesTests { - - @Autowired - private PeerEurekaNodes peerEurekaNodes; - - @Test - public void testCustomPeerNodesShouldTakePrecedenceOverDefault() { - assertTrue("PeerEurekaNodes should be the user created one", - peerEurekaNodes instanceof CustomEurekaPeerNodes); - } - - @Configuration - @EnableAutoConfiguration - @EnableEurekaServer - protected static class Application { - - @Bean - public PeerEurekaNodes myPeerEurekaNodes(PeerAwareInstanceRegistry registry, - EurekaServerConfig eurekaServerConfig, - EurekaClientConfig eurekaClientConfig, ServerCodecs serverCodecs, - ApplicationInfoManager applicationInfoManager) { - return new CustomEurekaPeerNodes(registry, eurekaServerConfig, - eurekaClientConfig, serverCodecs, applicationInfoManager); - } - - } - - private static class CustomEurekaPeerNodes extends PeerEurekaNodes { - - public CustomEurekaPeerNodes(PeerAwareInstanceRegistry registry, - EurekaServerConfig serverConfig, EurekaClientConfig clientConfig, - ServerCodecs serverCodecs, - ApplicationInfoManager applicationInfoManager) { - super(registry, serverConfig, clientConfig, serverCodecs, - applicationInfoManager); - } - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistryTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistryTests.java deleted file mode 100644 index 4b2867e2..00000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistryTests.java +++ /dev/null @@ -1,188 +0,0 @@ -package org.springframework.cloud.netflix.eureka.server; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.SpyBean; -import org.springframework.cloud.netflix.eureka.server.InstanceRegistryTests.TestApplication; -import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceCanceledEvent; -import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRegisteredEvent; -import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRenewedEvent; -import org.springframework.context.ApplicationEvent; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.event.EventListener; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.netflix.appinfo.InstanceInfo; -import com.netflix.appinfo.LeaseInfo; -import com.netflix.discovery.shared.Application; -import com.netflix.eureka.registry.PeerAwareInstanceRegistry; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doReturn; - -/** - * @author Bartlomiej Slota - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = TestApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - value = {"spring.application.name=eureka", "logging.level.org.springframework." - + "cloud.netflix.eureka.server.InstanceRegistry=DEBUG"}) -public class InstanceRegistryTests { - - private static final String APP_NAME = "MY-APP-NAME"; - private static final String HOST_NAME = "my-host-name"; - private static final String INSTANCE_ID = "my-host-name:8008"; - private static final int PORT = 8008; - - @SpyBean(PeerAwareInstanceRegistry.class) - private InstanceRegistry instanceRegistry; - - @Before - public void setup() { - this.testEvents.applicationEvents.clear(); - } - - @Autowired - private TestEvents testEvents; - - @Test - public void testRegister() throws Exception { - // creating instance info - final LeaseInfo leaseInfo = getLeaseInfo(); - final InstanceInfo instanceInfo = getInstanceInfo(APP_NAME, HOST_NAME, INSTANCE_ID, PORT, leaseInfo); - // calling tested method - instanceRegistry.register(instanceInfo, false); - // event of proper type is registered - assertEquals(1, this.testEvents.applicationEvents.size()); - assertTrue(this.testEvents.applicationEvents.get(0) instanceof EurekaInstanceRegisteredEvent); - // event details are correct - final EurekaInstanceRegisteredEvent registeredEvent = - (EurekaInstanceRegisteredEvent) (this.testEvents.applicationEvents.get(0)); - assertEquals(instanceInfo, registeredEvent.getInstanceInfo()); - assertEquals(leaseInfo.getDurationInSecs(), registeredEvent.getLeaseDuration()); - assertEquals(instanceRegistry, registeredEvent.getSource()); - assertFalse(registeredEvent.isReplication()); - } - - @Test - public void testDefaultLeaseDurationRegisterEvent() throws Exception { - // creating instance info - final InstanceInfo instanceInfo = getInstanceInfo(APP_NAME, HOST_NAME, INSTANCE_ID, PORT, null); - // calling tested method - instanceRegistry.register(instanceInfo, false); - // instance info duration is set to default - final EurekaInstanceRegisteredEvent registeredEvent = - (EurekaInstanceRegisteredEvent) (this.testEvents.applicationEvents.get(0)); - assertEquals(LeaseInfo.DEFAULT_LEASE_DURATION, - registeredEvent.getLeaseDuration()); - } - - @Test - public void testInternalCancel() throws Exception { - // calling tested method - instanceRegistry.internalCancel(APP_NAME, HOST_NAME, false); - // event of proper type is registered - assertEquals(1, this.testEvents.applicationEvents.size()); - assertTrue(this.testEvents.applicationEvents.get(0) instanceof EurekaInstanceCanceledEvent); - // event details are correct - final EurekaInstanceCanceledEvent registeredEvent = - (EurekaInstanceCanceledEvent) (this.testEvents.applicationEvents.get(0)); - assertEquals(APP_NAME, registeredEvent.getAppName()); - assertEquals(HOST_NAME, registeredEvent.getServerId()); - assertEquals(instanceRegistry, registeredEvent.getSource()); - assertFalse(registeredEvent.isReplication()); - } - - @Test - public void testRenew() throws Exception { - //Creating two instances of the app - final InstanceInfo instanceInfo1 = getInstanceInfo(APP_NAME, HOST_NAME, INSTANCE_ID, PORT, null); - final InstanceInfo instanceInfo2 = getInstanceInfo(APP_NAME, HOST_NAME, "my-host-name:8009", 8009, null); - // creating application list with an app having two instances - final Application application = new Application(APP_NAME, Arrays.asList(instanceInfo1, instanceInfo2)); - final List applications = new ArrayList<>(); - applications.add(application); - // stubbing applications list - doReturn(applications).when(instanceRegistry).getSortedApplications(); - // calling tested method - instanceRegistry.renew(APP_NAME, INSTANCE_ID, false); - instanceRegistry.renew(APP_NAME, "my-host-name:8009", false); - // event of proper type is registered - assertEquals(2, this.testEvents.applicationEvents.size()); - assertTrue(this.testEvents.applicationEvents.get(0) instanceof EurekaInstanceRenewedEvent); - assertTrue(this.testEvents.applicationEvents.get(1) instanceof EurekaInstanceRenewedEvent); - // event details are correct - final EurekaInstanceRenewedEvent event1 = (EurekaInstanceRenewedEvent) - (this.testEvents.applicationEvents.get(0)); - assertEquals(APP_NAME, event1.getAppName()); - assertEquals(INSTANCE_ID, event1.getServerId()); - assertEquals(instanceRegistry, event1.getSource()); - assertEquals(instanceInfo1, event1.getInstanceInfo()); - assertFalse(event1.isReplication()); - - final EurekaInstanceRenewedEvent event2 = (EurekaInstanceRenewedEvent) - (this.testEvents.applicationEvents.get(1)); - assertEquals(instanceInfo2, event2.getInstanceInfo()); - } - - @Configuration - @EnableAutoConfiguration - @EnableEurekaServer - protected static class TestApplication { - @Bean - public TestEvents testEvents() { - return new TestEvents(); - } - } - - protected static class TestEvents { - public final List applicationEvents = new LinkedList<>(); - - @EventListener(EurekaInstanceRegisteredEvent.class) - public void onEvent(EurekaInstanceRegisteredEvent event) { - this.applicationEvents.add(event); - } - - @EventListener(EurekaInstanceCanceledEvent.class) - public void onEvent(EurekaInstanceCanceledEvent event) { - this.applicationEvents.add(event); - } - - @EventListener(EurekaInstanceRenewedEvent.class) - public void onEvent(EurekaInstanceRenewedEvent event) { - this.applicationEvents.add(event); - } - - } - - private LeaseInfo getLeaseInfo() { - LeaseInfo.Builder leaseBuilder = LeaseInfo.Builder.newBuilder(); - leaseBuilder.setRenewalIntervalInSecs(10); - leaseBuilder.setDurationInSecs(15); - return leaseBuilder.build(); - } - - private InstanceInfo getInstanceInfo(String appName, String hostName, - String instanceId, int port, LeaseInfo leaseInfo) { - InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder(); - builder.setAppName(appName); - builder.setHostName(hostName); - builder.setInstanceId(instanceId); - builder.setPort(port); - builder.setLeaseInfo(leaseInfo); - return builder.build(); - } -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/RefreshablePeerEurekaNodesTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/RefreshablePeerEurekaNodesTests.java deleted file mode 100644 index ba1b9b56..00000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/RefreshablePeerEurekaNodesTests.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.eureka.server; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; - -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.cloud.context.environment.EnvironmentChangeEvent; -import org.springframework.cloud.netflix.eureka.EurekaClientConfigBean; -import org.springframework.cloud.netflix.eureka.server.EurekaServerAutoConfiguration.RefreshablePeerEurekaNodes; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.discovery.EurekaClientConfig; -import com.netflix.eureka.EurekaServerConfig; -import com.netflix.eureka.cluster.PeerEurekaNodes; -import com.netflix.eureka.registry.PeerAwareInstanceRegistry; -import com.netflix.eureka.resources.ServerCodecs; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.anyListOf; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * @author Fahim Farook - */ -@RunWith(SpringRunner.class) -@SpringBootTest( - classes = RefreshablePeerEurekaNodesTests.Application.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - value = { - "spring.application.name=eureka-server", - "eureka.client.service-url.defaultZone=http://localhost:8678/eureka/" - }) -public class RefreshablePeerEurekaNodesTests { - - @Autowired - private ConfigurableApplicationContext context; - - @Autowired - private PeerEurekaNodes peerEurekaNodes; - - @Value("${local.server.port}") - private int port = 0; - - private static final String DEFAULT_ZONE = "eureka.client.service-url.defaultZone"; - private static final String REGION = "eureka.client.region"; - private static final String USE_DNS = "eureka.client.use-dns-for-fetching-service-urls"; - - @Test - public void notUpdatedWhenDnsIsTrue() { - changeProperty( - "eureka.client.use-dns-for-fetching-service-urls=true", - "eureka.client.region=unavailable-region", // to force defaultZone - "eureka.client.service-url.defaultZone=http://default-host1:8678/eureka/"); - this.context.publishEvent(new EnvironmentChangeEvent(new HashSet(Arrays.asList(USE_DNS, DEFAULT_ZONE)))); - - assertFalse("PeerEurekaNodes' are updated when eureka.client.use-dns-for-fetching-service-urls is true", - serviceUrlMatches("http://default-host1:8678/eureka/")); - } - - @Test - public void updatedWhenDnsIsFalse() { - changeProperty( - "eureka.client.use-dns-for-fetching-service-urls=false", - "eureka.client.region=unavailable-region", // to force defaultZone - "eureka.client.service-url.defaultZone=http://default-host2:8678/eureka/"); - this.context.publishEvent(new EnvironmentChangeEvent(new HashSet(Arrays.asList(USE_DNS, DEFAULT_ZONE)))); - - assertTrue("PeerEurekaNodes' are not updated when eureka.client.use-dns-for-fetching-service-urls is false", - serviceUrlMatches("http://default-host2:8678/eureka/")); - } - - - @Test - @Ignore //FIXME 2.0.0 - public void updatedWhenRegionChanged() { - changeProperty( - "eureka.client.use-dns-for-fetching-service-urls=false", - "eureka.client.region=region1", - "eureka.client.availability-zones.region1=region1-zone", - "eureka.client.availability-zones.region2=region2-zone", - "eureka.client.service-url.region1-zone=http://region1-zone-host:8678/eureka/", - "eureka.client.service-url.region2-zone=http://region2-zone-host:8678/eureka/"); - this.context.publishEvent(new EnvironmentChangeEvent(Collections.singleton(REGION))); - assertTrue("PeerEurekaNodes' are not updated when eureka.client.region is changed", - serviceUrlMatches("http://region1-zone-host:8678/eureka/")); - - changeProperty("eureka.client.region=region2"); - this.context.publishEvent(new EnvironmentChangeEvent(Collections.singleton(REGION))); - assertTrue("PeerEurekaNodes' are not updated when eureka.client.region is changed", - serviceUrlMatches("http://region2-zone-host:8678/eureka/")); - } - - @Test - @Ignore //FIXME 2.0.0 - public void updatedWhenAvailabilityZoneChanged() { - changeProperty( - "eureka.client.use-dns-for-fetching-service-urls=false", - "eureka.client.region=region4", - "eureka.client.availability-zones.region3=region3-zone", - "eureka.client.service-url.region4-zone=http://region4-zone-host:8678/eureka/", - "eureka.client.service-url.defaultZone=http://default-host3:8678/eureka/"); - this.context.publishEvent(new EnvironmentChangeEvent(Collections.singleton("eureka.client.availability-zones.region3"))); - assertTrue(this.peerEurekaNodes.getPeerEurekaNodes().get(0).getServiceUrl().equals("http://default-host3:8678/eureka/")); - - changeProperty("eureka.client.availability-zones.region4=region4-zone"); - this.context.publishEvent(new EnvironmentChangeEvent(Collections.singleton("eureka.client.availability-zones.region4"))); - assertTrue("PeerEurekaNodes' are not updated when eureka.client.availability-zones are changed", - serviceUrlMatches("http://region4-zone-host:8678/eureka/")); - } - - @Test - public void notUpdatedWhenIrrelevantPropertiesChanged() { - // Only way to test this is verifying whether updatePeerEurekaNodes() is invoked. - - // PeerEurekaNodes.updatePeerEurekaNodes() is not public, hence cannot verify with Mockito. - class VerifyablePeerEurekNode extends RefreshablePeerEurekaNodes { - public VerifyablePeerEurekNode(PeerAwareInstanceRegistry registry, EurekaServerConfig serverConfig, - EurekaClientConfig clientConfig, ServerCodecs serverCodecs, - ApplicationInfoManager applicationInfoManager) { - super(registry, serverConfig, clientConfig, serverCodecs, applicationInfoManager); - } - - protected void updatePeerEurekaNodes(List newPeerUrls) { - super.updatePeerEurekaNodes(newPeerUrls); - } - } - - // Create stubs. - final EurekaClientConfigBean configClientBean = mock(EurekaClientConfigBean.class); - when(configClientBean.isUseDnsForFetchingServiceUrls()).thenReturn(false); - final VerifyablePeerEurekNode mock = spy(new VerifyablePeerEurekNode(null, null, configClientBean, null, null)); - - mock.onApplicationEvent(new EnvironmentChangeEvent(Collections.singleton("some.irrelevant.property"))); - verify(mock, never()).updatePeerEurekaNodes(anyListOf(String.class)); - } - - @Test - public void peerEurekaNodesIsRefreshablePeerEurekaNodes() { - assertNotNull(this.peerEurekaNodes); - assertTrue("PeerEurekaNodes should be an instance of RefreshablePeerEurekaNodes", - this.peerEurekaNodes instanceof RefreshablePeerEurekaNodes); - } - - - @Test - public void serviceUrlsCountAsSoonAsRefreshed() { - changeProperty("eureka.client.service-url.defaultZone=http://defaul-host3:8678/eureka/,http://defaul-host4:8678/eureka/"); - forceUpdate(); - assertThat("PeerEurekaNodes' peer count is incorrect.", - this.peerEurekaNodes.getPeerEurekaNodes().size(), is(2)); - } - - - @Test - public void serviceUrlsValueAsSoonAsRefreshed() { - changeProperty("eureka.client.service-url.defaultZone=http://defaul-host4:8678/eureka/"); - forceUpdate(); - assertTrue("PeerEurekaNodes' new peer[0] is incorrect", - serviceUrlMatches("http://defaul-host4:8678/eureka/")); - } - - @Test - public void dashboardUpdatedAsSoonAsRefreshed() { - changeProperty("eureka.client.service-url.defaultZone=http://defaul-host5:8678/eureka/"); - forceUpdate(); - final ResponseEntity entity = new TestRestTemplate() - .getForEntity("http://localhost:" + this.port + "/", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - final String body = entity.getBody(); - assertNotNull(body); - assertTrue("DS Replicas not updated in the Eureka Server dashboard", - body.contains("http://defaul-host5:8678/eureka/")); - } - - @Test - public void notUpdatedForRelaxedKeys() { - changeProperty( - "eureka.client.use-dns-for-fetching-service-urls=false", - "eureka.client.region=unavailable-region", // to force defaultZone - "eureka.client.service-url.defaultZone=http://defaul-host6:8678/eureka/"); - this.context.publishEvent(new EnvironmentChangeEvent(Collections.singleton("eureka.client.serviceUrl.defaultZone"))); - assertFalse("PeerEurekaNodes' are updated for keys with relaxed binding", - serviceUrlMatches("http://defaul-host6:8678/eureka/")); - } - - @EnableEurekaServer - @Configuration - @EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class - }) - protected static class Application { - } - - /* - * Changes the value of given key in the environment. - */ - private void changeProperty(final String... pairs) { - TestPropertyValues.of(pairs).applyTo(this.context); - } - - /* - * Refreshes the context with properties satisfying to invoke update. - */ - private void forceUpdate() { - changeProperty( - "eureka.client.use-dns-for-fetching-service-urls=false", - "eureka.client.region=unavailable-region"); // to force defaultZone - this.context.publishEvent( - new EnvironmentChangeEvent(Collections.singleton("eureka.client.service-url.defaultZone"))); - } - - /* - * Whether the first element in PeerEurekaNodes matches the given url. - */ - private boolean serviceUrlMatches(final String serviceUrl) { - return this.peerEurekaNodes.getPeerEurekaNodes().get(0).getServiceUrl().equals(serviceUrl); - } -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AbstractDocumentationTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AbstractDocumentationTests.java deleted file mode 100644 index b666ac09..00000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AbstractDocumentationTests.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server.doc; - -import java.util.UUID; - -import org.junit.After; -import org.junit.Rule; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.contract.wiremock.restdocs.WireMockSnippet; -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; -import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; -import org.springframework.cloud.netflix.eureka.server.doc.AbstractDocumentationTests.Application; -import org.springframework.context.annotation.Configuration; -import org.springframework.restdocs.JUnitRestDocumentation; -import org.springframework.restdocs.restassured3.RestAssuredRestDocumentation; -import org.springframework.restdocs.restassured3.RestDocumentationFilter; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.util.ReflectionTestUtils; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl; - -import io.restassured.RestAssured; -import io.restassured.builder.RequestSpecBuilder; -import io.restassured.filter.Filter; -import io.restassured.specification.RequestSpecification; - -import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.restassured3.operation.preprocess.RestAssuredPreprocessors.modifyUris; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { - "spring.jmx.enabled=false", "management.security.enabled=false" }) -@DirtiesContext -public abstract class AbstractDocumentationTests { - - @LocalServerPort - private int port = 0; - - @Autowired - private PeerAwareInstanceRegistryImpl registry; - - @Autowired - private EurekaInstanceConfigBean instanceConfig; - - @Autowired - private ApplicationInfoManager applicationInfoManager; - - @Rule - public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation( - "target/generated-snippets"); - - @After - public void init() { - registry.clearRegistry(); - ReflectionTestUtils.setField(registry, "responseCache", null); - registry.initializedResponseCache(); - } - - protected InstanceInfo register(String name) { - return register(name, UUID.randomUUID().toString()); - } - - protected InstanceInfo register(String name, String id) { - registry.register(instance(name, id), false); - return instance(); - } - - protected InstanceInfo instance(String name) { - return instance(name, UUID.randomUUID().toString()); - } - - protected InstanceInfo instance(String name, String id) { - instanceConfig.setAppname(name); - instanceConfig.setInstanceId(id); - instanceConfig.setHostname("foo.example.com"); - applicationInfoManager.initComponent(instanceConfig); - return applicationInfoManager.getInfo(); - } - - protected InstanceInfo instance() { - return applicationInfoManager.getInfo(); - } - - private RestDocumentationFilter filter(String name) { - return RestAssuredRestDocumentation.document(name, - preprocessRequest(modifyUris().host("eureka.example.com").removePort(), - prettyPrint()), - preprocessResponse(prettyPrint())); - } - - private RequestSpecification spec(Filter... filters) { - return spec(null, filters); - } - - private RequestSpecification spec(Object body, Filter... filters) { - RequestSpecBuilder builder = new RequestSpecBuilder() - .addFilter(documentationConfiguration(this.restDocumentation).snippets() - .withAdditionalDefaults(new WireMockSnippet())); - for (Filter filter : filters) { - builder = builder.addFilter(filter); - } - RequestSpecification spec = builder.setPort(this.port).build(); - if (body != null) { - spec.contentType("application/json").body(body, new EurekaObjectMapper()); - } - return spec; - } - - protected RequestSpecification document() { - return document("{method-name}"); - } - - protected RequestSpecification document(Object body) { - RestDocumentationFilter filter = filter("{method-name}"); - RequestSpecification assured = RestAssured.given(spec(body, filter)); - return assured.filter(filter); - } - - protected RequestSpecification document(String name, Object body) { - RestDocumentationFilter filter = filter(name); - RequestSpecification assured = RestAssured.given(spec(body, filter)); - return assured.filter(filter); - } - - protected RequestSpecification document(String name) { - RestDocumentationFilter filter = filter(name); - return RestAssured.given(spec(filter)).filter(filter); - } - - @Configuration - @EnableAutoConfiguration - @EnableEurekaServer - protected static class Application { - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AppRegistrationTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AppRegistrationTests.java deleted file mode 100644 index a7160d32..00000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AppRegistrationTests.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server.doc; - -import java.util.UUID; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static com.github.tomakehurst.wiremock.client.WireMock.delete; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.matching; -import static com.github.tomakehurst.wiremock.client.WireMock.put; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.emptyIterable; -import static org.hamcrest.Matchers.hasSize; -import static org.springframework.cloud.netflix.eureka.server.doc.RequestVerifierFilter.verify; - -@RunWith(SpringJUnit4ClassRunner.class) -public class AppRegistrationTests extends AbstractDocumentationTests { - - @Test - public void startingApp() throws Exception { - register("foo"); - document().accept("application/json").when().get("/eureka/apps").then() - .assertThat() - .body("applications.application", hasSize(1), - "applications.application[0].instance[0].status", - equalTo("STARTING")) - .statusCode(is(200)); - } - - @Test - public void addInstance() throws Exception { - document(instance("foo")) - .filter(verify("$.instance.app").json("$.instance.hostName") - .json("$.instance[?(@.status=='STARTING')]") - .json("$.instance.instanceId") - .json("$.instance.dataCenterInfo.name")) - .when().post("/eureka/apps/FOO").then().assertThat().statusCode(is(204)); - } - - @Test - public void setStatus() throws Exception { - String id = register("foo").getInstanceId(); - document() - .filter(verify(put(urlPathMatching("/eureka/apps/FOO/.*/status")) - .withQueryParam("value", matching("UP")))) - .when().put("/eureka/apps/FOO/{id}/status?value={value}", id, "UP").then() - .assertThat().statusCode(is(200)); - } - - @Test - public void allApps() throws Exception { - register("foo"); - document().accept("application/json").when().get("/eureka/apps").then() - .assertThat().body("applications.application", hasSize(1)) - .statusCode(is(200)); - } - - @Test - public void delta() throws Exception { - register("foo"); - document().accept("application/json").when().get("/eureka/apps/delta").then() - .assertThat().body("applications.application", hasSize(1)) - .statusCode(is(200)); - } - - @Test - public void oneInstance() throws Exception { - String id = UUID.randomUUID().toString(); - register("foo", id); - document().filter(verify(get(urlPathMatching("/eureka/apps/FOO/.*")))) - .accept("application/json").when().get("/eureka/apps/FOO/{id}", id).then() - .assertThat().body("instance.app", equalTo("FOO")).statusCode(is(200)); - } - - @Test - public void lookupInstance() throws Exception { - String id = register("foo").getInstanceId(); - document().filter(verify(get(urlPathMatching("/eureka/instances/.*")))) - .accept("application/json").when().get("/eureka/instances/{id}", id) - .then().assertThat().body("instance.app", equalTo("FOO")) - .statusCode(is(200)); - } - - @Test - public void renew() throws Exception { - String id = register("foo").getInstanceId(); - document().filter(verify(put(urlPathMatching("/eureka/apps/FOO/.*")))) - .accept("application/json").when().put("/eureka/apps/FOO/{id}", id).then() - .assertThat().statusCode(is(200)); - } - - @Test - public void updateMetadata() throws Exception { - String id = register("foo").getInstanceId(); - document() - .filter(verify(put(urlPathMatching("/eureka/apps/FOO/.*/metadata")) - .withQueryParam("key", matching(".*")))) - .accept("application/json").when() - .put("/eureka/apps/FOO/{id}/metadata?key=value", id).then().assertThat() - .statusCode(is(200)); - assertThat(instance().getMetadata()).containsEntry("key", "value"); - } - - @Test - public void deleteInstance() throws Exception { - String id = register("foo").getInstanceId(); - document().filter(verify(delete(urlPathMatching("/eureka/apps/FOO/.*")))).when() - .delete("/eureka/apps/FOO/{id}", id).then().assertThat() - .statusCode(is(200)); - } - - @Test - public void emptyApps() { - document().when().accept("application/json").get("/eureka/apps").then() - .assertThat().body("applications.application", emptyIterable()) - .statusCode(is(200)); - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaObjectMapper.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaObjectMapper.java deleted file mode 100644 index 3d10e3c3..00000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaObjectMapper.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2016-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.cloud.netflix.eureka.server.doc; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import javax.ws.rs.core.MediaType; - -import com.netflix.discovery.converters.EntityBodyConverter; -import io.restassured.mapper.ObjectMapperDeserializationContext; -import io.restassured.mapper.ObjectMapperSerializationContext; - -final class EurekaObjectMapper - implements io.restassured.mapper.ObjectMapper { - private EntityBodyConverter converter = new EntityBodyConverter(); - - @Override - public Object serialize(ObjectMapperSerializationContext context) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - converter.write(context.getObjectToSerialize(), out, - MediaType.APPLICATION_JSON_TYPE); - } - catch (IOException e) { - throw new IllegalStateException("Cannot serialize", e); - } - return out.toByteArray(); - } - - @Override - public Object deserialize( - ObjectMapperDeserializationContext context) { - try { - return converter.read( - context.getDataToDeserialize().asInputStream(), - context.getType(), MediaType.APPLICATION_JSON_TYPE); - } - catch (IOException e) { - throw new IllegalStateException("Cannot deserialize", e); - } - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaServerTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaServerTests.java deleted file mode 100644 index 91d3e44f..00000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaServerTests.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.eureka.server.doc; - -import java.util.UUID; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.notNullValue; - -@RunWith(SpringJUnit4ClassRunner.class) -// TODO: maybe this should be the default (the test fails without it because the JSON is -// invalid) -@TestPropertySource(properties = {"eureka.server.minAvailableInstancesForPeerReplication=0", "spring.jmx.enabled=false"}) -public class EurekaServerTests extends AbstractDocumentationTests { - - @Test - public void serverStatus() throws Exception { - register("foo", UUID.randomUUID().toString()); - document().accept("application/json").when().get("/eureka/status").then() - .assertThat().body("generalStats", notNullValue(), "applicationStats", - notNullValue(), "instanceInfo", notNullValue()) - .statusCode(is(200)); - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/RequestVerifierFilter.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/RequestVerifierFilter.java deleted file mode 100644 index 1f210ded..00000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/RequestVerifierFilter.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2016-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.cloud.netflix.eureka.server.doc; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.github.tomakehurst.wiremock.client.MappingBuilder; -import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; -import com.github.tomakehurst.wiremock.http.ContentTypeHeader; -import com.github.tomakehurst.wiremock.http.Cookie; -import com.github.tomakehurst.wiremock.http.HttpHeader; -import com.github.tomakehurst.wiremock.http.HttpHeaders; -import com.github.tomakehurst.wiremock.http.QueryParameter; -import com.github.tomakehurst.wiremock.http.Request; -import com.github.tomakehurst.wiremock.http.RequestMethod; -import com.github.tomakehurst.wiremock.matching.MatchResult; -import com.github.tomakehurst.wiremock.stubbing.StubMapping; -import com.jayway.jsonpath.JsonPath; - -import io.restassured.filter.Filter; -import io.restassured.filter.FilterContext; -import io.restassured.http.Header; -import io.restassured.response.Response; -import io.restassured.specification.FilterableRequestSpecification; -import io.restassured.specification.FilterableResponseSpecification; -import org.springframework.util.Base64Utils; -import org.springframework.util.ObjectUtils; -import org.springframework.util.StringUtils; -import wiremock.com.google.common.base.Optional; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Dave Syer - * - */ -public class RequestVerifierFilter implements Filter { - - static final String CONTEXT_KEY_CONFIGURATION = "org.springframework.restdocs.configuration"; - private Map jsonPaths = new LinkedHashMap<>(); - private MappingBuilder builder; - - public static RequestVerifierFilter verify(String path) { - return new RequestVerifierFilter(path); - } - - public static RequestVerifierFilter verify(MappingBuilder builder) { - return new RequestVerifierFilter().wiremock(builder); - } - - private RequestVerifierFilter(String expression, Object... args) { - expression = String.format(expression, args); - this.jsonPaths.put(expression, JsonPath.compile(expression)); - } - - private RequestVerifierFilter() { - } - - public RequestVerifierFilter json(String expression, Object... args) { - expression = String.format(expression, args); - this.jsonPaths.put(expression, JsonPath.compile(expression)); - return this; - } - - public RequestVerifierFilter wiremock(MappingBuilder builder) { - this.builder = builder; - return this; - } - - @Override - public Response filter(FilterableRequestSpecification requestSpec, - FilterableResponseSpecification responseSpec, FilterContext context) { - Map configuration = getConfiguration(requestSpec, context); - configuration.put("contract.jsonPaths", this.jsonPaths.keySet()); - Response response = context.next(requestSpec, responseSpec); - if (requestSpec.getBody() != null && !this.jsonPaths.isEmpty()) { - String actual = new String((byte[]) requestSpec.getBody()); - for (JsonPath jsonPath : this.jsonPaths.values()) { - new JsonPathValue(jsonPath, actual).assertHasValue(Object.class, - "an object"); - } - } - if (this.builder != null) { - this.builder.willReturn(getResponseDefinition(response)); - StubMapping stubMapping = this.builder.build(); - MatchResult match = stubMapping.getRequest() - .match(new WireMockRestAssuredRequestAdapter(requestSpec)); - assertThat(match.isExactMatch()).as("wiremock did not match request") - .isTrue(); - configuration.put("contract.stubMapping", stubMapping); - } - return response; - } - - private ResponseDefinitionBuilder getResponseDefinition(Response response) { - ResponseDefinitionBuilder definition = ResponseDefinitionBuilder - .responseDefinition().withBody(response.getBody().asString()) - .withStatus(response.getStatusCode()); - addResponseHeaders(definition, response); - return definition; - } - - private void addResponseHeaders(ResponseDefinitionBuilder definition, - Response input) { - for (Header header : input.getHeaders().asList()) { - String name = header.getName(); - definition.withHeader(name, input.getHeader(name)); - } - } - - protected Map getConfiguration( - FilterableRequestSpecification requestSpec, FilterContext context) { - Map configuration = context - .>getValue(CONTEXT_KEY_CONFIGURATION); - return configuration; - } -} - -class JsonPathValue { - - private final JsonPath jsonPath; - private final String expression; - private final CharSequence actual; - - JsonPathValue(JsonPath jsonPath, CharSequence actual) { - this.jsonPath = jsonPath; - this.actual = actual; - this.expression = jsonPath.getPath(); - } - - public void assertHasValue(Class type, String expectedDescription) { - Object value = getValue(true); - if (value == null || isIndefiniteAndEmpty()) { - throw new AssertionError(getNoValueMessage()); - } - if (type != null && !type.isInstance(value)) { - throw new AssertionError(getExpectedValueMessage(expectedDescription)); - } - } - - private boolean isIndefiniteAndEmpty() { - return !isDefinite() && isEmpty(); - } - - private boolean isDefinite() { - return this.jsonPath.isDefinite(); - } - - private boolean isEmpty() { - return ObjectUtils.isEmpty(getValue(false)); - } - - public Object getValue(boolean required) { - try { - CharSequence json = this.actual; - return this.jsonPath.read(json == null ? null : json.toString()); - } - catch (Exception ex) { - if (!required) { - return null; - } - throw new AssertionError(getNoValueMessage() + ". " + ex.getMessage()); - } - } - - private String getNoValueMessage() { - return "No value at JSON path \"" + this.expression + "\""; - } - - private String getExpectedValueMessage(String expectedDescription) { - return String.format("Expected %s at JSON path \"%s\" but found: %s", - expectedDescription, this.expression, - ObjectUtils.nullSafeToString(StringUtils.quoteIfString(getValue(false)))); - } - -} - -class WireMockRestAssuredRequestAdapter implements Request { - - private FilterableRequestSpecification request; - - public WireMockRestAssuredRequestAdapter(FilterableRequestSpecification request) { - this.request = request; - } - - @Override - public Optional getOriginalRequest() { - return Optional.of(this); - } - - @Override - public String getUrl() { - return request.getDerivedPath(); - } - - @Override - public String getAbsoluteUrl() { - return request.getURI(); - } - - @Override - public RequestMethod getMethod() { - return RequestMethod.fromString(request.getMethod()); - } - - @Override - public String getClientIp() { - return "127.0.0.1"; - } - - @Override - public String getHeader(String key) { - String value = request.getHeaders().getValue(key); - if ("accept".equals(key.toLowerCase()) && "*/*".equals(value)) { - return null; - } - return value; - } - - @Override - public HttpHeader header(String key) { - String value = request.getHeaders().getValue(key); - if ("accept".equals(key.toLowerCase()) && "*/*".equals(value)) { - return null; - } - return new HttpHeader(key, value); - } - - @Override - public ContentTypeHeader contentTypeHeader() { - return new ContentTypeHeader(request.getContentType()); - } - - @Override - public HttpHeaders getHeaders() { - List headers = new ArrayList<>(); - for (Header header : request.getHeaders()) { - String value = header.getValue(); - if ("accept".equals(header.getName().toLowerCase()) && "*/*".equals(value)) { - continue; - } - headers.add(new HttpHeader(header.getName(), header.getValue())); - } - return new HttpHeaders(headers); - } - - @Override - public boolean containsHeader(String key) { - String value = request.getHeaders().getValue(key); - if ("accept".equals(key.toLowerCase()) && "*/*".equals(value)) { - return false; - } - return request.getHeaders().hasHeaderWithName(key); - } - - @Override - public Set getAllHeaderKeys() { - Set headers = new LinkedHashSet<>(); - for (Header header : request.getHeaders()) { - String value = header.getValue(); - if ("accept".equals(header.getName().toLowerCase()) && "*/*".equals(value)) { - continue; - } - headers.add(header.getName()); - } - return headers; - } - - @Override - public Map getCookies() { - Map map = new LinkedHashMap<>(); - for (io.restassured.http.Cookie cookie : request.getCookies()) { - Cookie value = new Cookie(cookie.getValue()); - map.put(cookie.getName(), value); - } - return map; - } - - @Override - public QueryParameter queryParameter(String key) { - Map params = request.getQueryParams(); - if (params.containsKey(key)) { - return new QueryParameter(key, Arrays.asList(params.get(key))); - } - return null; - } - - @Override - public byte[] getBody() { - return request.getBody(); - } - - @Override - public String getBodyAsString() { - return new String(getBody()); - } - - @Override - public String getBodyAsBase64() { - return Base64Utils.encodeToString(getBody()); - } - - @Override - public boolean isBrowserProxyRequest() { - return false; - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/test/resources/application.properties b/spring-cloud-netflix-eureka-server/src/test/resources/application.properties deleted file mode 100644 index 52c10d89..00000000 --- a/spring-cloud-netflix-eureka-server/src/test/resources/application.properties +++ /dev/null @@ -1,6 +0,0 @@ -server.port=8761 -spring.application.name=eureka -eureka.client.registerWithEureka=false -eureka.client.fetchRegistry=false -logging.level.org.springframework.web.client=DEBUG -logging.level.com.netflix.discovery=DEBUG \ No newline at end of file diff --git a/spring-cloud-netflix-hystrix-contract/pom.xml b/spring-cloud-netflix-hystrix-contract/pom.xml deleted file mode 100644 index 893aba80..00000000 --- a/spring-cloud-netflix-hystrix-contract/pom.xml +++ /dev/null @@ -1,99 +0,0 @@ - - - 4.0.0 - - org.springframework.cloud - spring-cloud-build - 2.0.0.BUILD-SNAPSHOT - - - spring-cloud-netflix-hystrix-contract - 2.0.0.BUILD-SNAPSHOT - jar - spring-cloud-netflix-hystrix-contract - Spring Cloud Netflix Hystrix Contract - - ${basedir}/.. - 1.1.2.RELEASE - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework.boot - spring-boot-starter-test - - - org.springframework.cloud - spring-cloud-contract-verifier - ${donotreplacespring-cloud-contract.version} - - - - - spring - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/libs-snapshot-local - - true - - - false - - - - spring-milestones - Spring Milestones - https://repo.spring.io/libs-milestone-local - - false - - - - spring-releases - Spring Releases - https://repo.spring.io/release - - false - - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/libs-snapshot-local - - true - - - false - - - - spring-milestones - Spring Milestones - https://repo.spring.io/libs-milestone-local - - false - - - - spring-releases - Spring Releases - https://repo.spring.io/libs-release-local - - false - - - - - - diff --git a/spring-cloud-netflix-hystrix-contract/src/main/java/org/springframework/cloud/netflix/hystrix/contract/HystrixContractUtils.java b/spring-cloud-netflix-hystrix-contract/src/main/java/org/springframework/cloud/netflix/hystrix/contract/HystrixContractUtils.java deleted file mode 100644 index 156750dd..00000000 --- a/spring-cloud-netflix-hystrix-contract/src/main/java/org/springframework/cloud/netflix/hystrix/contract/HystrixContractUtils.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2016-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.cloud.netflix.hystrix.contract; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Map; - -import org.springframework.core.io.DefaultResourceLoader; -import org.springframework.util.StreamUtils; - -/** - * @author Dave Syer - * @author Daniel Lavoie - * - */ -public class HystrixContractUtils { - - public static String simpleBody() { - try { - return StreamUtils.copyToString(new DefaultResourceLoader() - .getResource("classpath:/stubs/simpleBody.json").getInputStream(), - StandardCharsets.UTF_8); - } - catch (IOException e) { - throw new IllegalStateException("Cannot read stub", e); - } - } - - public static void checkEvent(String event) { - assertThat(event).isNotNull(); - assertThat(event).isEqualTo("message"); - } - - public static void checkOrigin(Map origin) { - assertThat(origin.get("host")).isNotNull(); - assertThat(origin.get("port")).isNotNull(); - assertThat(origin.get("serviceId")).isEqualTo("application"); - // TODO: boot 2 changed application context id generation - assertThat(origin.get("id")).asString().startsWith("application"); - } - - public static void checkData(Map data, String group, String name) { - if (!data.get("type").equals("HystrixCommand")) { - assertThat(data.get("type")).isEqualTo("HystrixThreadPool"); - return; - } - assertThat(data.get("type")).isEqualTo("HystrixCommand"); - if (!data.get("name").equals(name)) { - return; - } - assertThat(data.get("name")).asString().isEqualTo(name); - assertThat(data.get("group")).isNotNull(); - assertThat(data.get("group")).isEqualTo(group); - assertThat(data.get("errorCount")).isEqualTo(0); - assertThat(data.get("errorPercentage")).isEqualTo(0); - assertThat(data.get("requestCount")).isInstanceOf(java.lang.Integer.class); - assertThat(data.get("currentConcurrentExecutionCount")) - .isInstanceOf(java.lang.Integer.class); - assertThat(data.get("rollingCountFailure")).isEqualTo(0); - assertThat(data.get("rollingCountSuccess")).isInstanceOf(java.lang.Integer.class); - assertThat(data.get("rollingCountShortCircuited")).isEqualTo(0); - assertThat(data.get("rollingCountFallbackSuccess")).isEqualTo(0); - assertThat(data.get("isCircuitBreakerOpen")).isEqualTo(false); - } - -} diff --git a/spring-cloud-netflix-hystrix-contract/src/main/resources/stubs/simpleBody.json b/spring-cloud-netflix-hystrix-contract/src/main/resources/stubs/simpleBody.json deleted file mode 100644 index 7e1bcfef..00000000 --- a/spring-cloud-netflix-hystrix-contract/src/main/resources/stubs/simpleBody.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "origin":{ - "host":"192.168.1.192", - "port":0, - "serviceId":"application", - "id":"application:0" - }, - "event" : "message", - "data":{ - "type":"HystrixCommand", - "name":"application.hello", - "group":"Application", - "currentTime":1494840901153, - "isCircuitBreakerOpen":false, - "errorPercentage":0, - "errorCount":0, - "requestCount":1, - "rollingCountCollapsedRequests":0, - "rollingCountExceptionsThrown":0, - "rollingCountFailure":0, - "rollingCountFallbackFailure":0, - "rollingCountFallbackRejection":0, - "rollingCountFallbackSuccess":0, - "rollingCountResponsesFromCache":0, - "rollingCountSemaphoreRejected":0, - "rollingCountShortCircuited":0, - "rollingCountSuccess":0, - "rollingCountThreadPoolRejected":0, - "rollingCountTimeout":0, - "currentConcurrentExecutionCount":0, - "latencyExecute_mean":0, - "latencyExecute":{ - "0":0, - "25":0, - "50":0, - "75":0, - "90":0, - "95":0, - "99":0, - "99.5":0, - "100":0 - }, - "latencyTotal_mean":0, - "latencyTotal":{ - "0":0, - "25":0, - "50":0, - "75":0, - "90":0, - "95":0, - "99":0, - "99.5":0, - "100":0 - }, - "propertyValue_circuitBreakerRequestVolumeThreshold":20, - "propertyValue_circuitBreakerSleepWindowInMilliseconds":5000, - "propertyValue_circuitBreakerErrorThresholdPercentage":50, - "propertyValue_circuitBreakerForceOpen":false, - "propertyValue_circuitBreakerForceClosed":false, - "propertyValue_circuitBreakerEnabled":true, - "propertyValue_executionIsolationStrategy":"THREAD", - "propertyValue_executionIsolationThreadTimeoutInMilliseconds":1000, - "propertyValue_executionIsolationThreadInterruptOnTimeout":true, - "propertyValue_executionIsolationThreadPoolKeyOverride":null, - "propertyValue_executionIsolationSemaphoreMaxConcurrentRequests":10, - "propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests":10, - "propertyValue_metricsRollingStatisticalWindowInMilliseconds":10000, - "propertyValue_requestCacheEnabled":true, - "propertyValue_requestLogEnabled":true, - "reportingHosts":1 - } -} diff --git a/spring-cloud-netflix-hystrix-dashboard/pom.xml b/spring-cloud-netflix-hystrix-dashboard/pom.xml deleted file mode 100644 index 7543eb35..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - 4.0.0 - spring-cloud-netflix-hystrix-dashboard - Spring Cloud Netflix Hystrix - https://projects.spring.io/spring-cloud/ - - org.springframework.cloud - spring-cloud-netflix - 2.0.0.BUILD-SNAPSHOT - .. - - - ${basedir}/.. - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-freemarker - - - org.springframework.cloud - spring-cloud-commons - - - org.springframework.cloud - spring-cloud-netflix-core - - - org.apache.httpcomponents - httpclient - - - com.netflix.hystrix - hystrix-core - - - com.netflix.hystrix - hystrix-metrics-event-stream - - - org.webjars - jquery - - - org.webjars - d3js - - - org.springframework.boot - spring-boot-starter-test - test - - - diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/EnableHystrixDashboard.java b/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/EnableHystrixDashboard.java deleted file mode 100644 index d65f57f8..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/EnableHystrixDashboard.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.dashboard; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.springframework.context.annotation.Import; - -/** - * @author Spencer Gibb - */ -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Import(HystrixDashboardConfiguration.class) -public @interface EnableHystrixDashboard { - -} diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardConfiguration.java b/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardConfiguration.java deleted file mode 100644 index 75dc7551..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardConfiguration.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.dashboard; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.Header; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.PoolingClientConnectionManager; -import org.apache.http.params.HttpConnectionParams; -import org.apache.http.params.HttpParams; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.web.servlet.ServletRegistrationBean; -import org.springframework.cloud.client.actuator.HasFeatures; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpHeaders; -import org.springframework.ui.freemarker.SpringTemplateLoader; -import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; - -/** - * @author Dave Syer - * @author Roy Clarkson - * @author Fahim Farook - */ -@Configuration -@EnableConfigurationProperties(HystrixDashboardProperties.class) -public class HystrixDashboardConfiguration { - - private static final String DEFAULT_TEMPLATE_LOADER_PATH = "classpath:/templates/"; - - private static final String DEFAULT_CHARSET = "UTF-8"; - - @Autowired - private HystrixDashboardProperties dashboardProperties; - - @Bean - public HasFeatures hystrixDashboardFeature() { - return HasFeatures.namedFeature("Hystrix Dashboard", HystrixDashboardConfiguration.class); - } - - /** - * Overrides Spring Boot's {@link FreeMarkerAutoConfiguration} to prefer using a - * {@link SpringTemplateLoader} instead of the file system. This corrects an issue - * where Spring Boot may use an empty 'templates' file resource to resolve templates - * instead of the packaged Hystrix classpath templates. - * @return FreeMarker configuration - */ - @Bean - public FreeMarkerConfigurer freeMarkerConfigurer() { - FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); - configurer.setTemplateLoaderPaths(DEFAULT_TEMPLATE_LOADER_PATH); - configurer.setDefaultEncoding(DEFAULT_CHARSET); - configurer.setPreferFileSystemAccess(false); - return configurer; - } - - @Bean - public ServletRegistrationBean proxyStreamServlet() { - final ProxyStreamServlet proxyStreamServlet = new ProxyStreamServlet(); - proxyStreamServlet.setEnableIgnoreConnectionCloseHeader( - this.dashboardProperties.isEnableIgnoreConnectionCloseHeader()); - final ServletRegistrationBean registration = new ServletRegistrationBean( - proxyStreamServlet, "/proxy.stream"); - registration.setInitParameters(this.dashboardProperties.getInitParameters()); - return registration; - } - - @Bean - public HystrixDashboardController hsytrixDashboardController() { - return new HystrixDashboardController(); - } - - /** - * Proxy an EventStream request (data.stream via proxy.stream) since EventStream does - * not yet support CORS (https://bugs.webkit.org/show_bug.cgi?id=61862) so that a UI - * can request a stream from a different server. - */ - public static class ProxyStreamServlet extends HttpServlet { - - private static final Log log = LogFactory.getLog(ProxyStreamServlet.class); - - private static final long serialVersionUID = 1L; - - private static final String CONNECTION_CLOSE_VALUE = "close"; - - private boolean enableIgnoreConnectionCloseHeader = false; - - public void setEnableIgnoreConnectionCloseHeader( - boolean enableIgnoreConnectionCloseHeader) { - this.enableIgnoreConnectionCloseHeader = enableIgnoreConnectionCloseHeader; - } - - public ProxyStreamServlet() { - super(); - } - - /** - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest - * request, javax.servlet.http.HttpServletResponse response) - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - String origin = request.getParameter("origin"); - if (origin == null) { - response.setStatus(500); - response.getWriter() - .println( - "Required parameter 'origin' missing. Example: 107.20.175.135:7001"); - return; - } - origin = origin.trim(); - - HttpGet httpget = null; - InputStream is = null; - boolean hasFirstParameter = false; - StringBuilder url = new StringBuilder(); - if (!origin.startsWith("http")) { - url.append("http://"); - } - url.append(origin); - if (origin.contains("?")) { - hasFirstParameter = true; - } - Map params = request.getParameterMap(); - for (String key : params.keySet()) { - if (!key.equals("origin")) { - String[] values = params.get(key); - String value = values[0].trim(); - if (hasFirstParameter) { - url.append("&"); - } - else { - url.append("?"); - hasFirstParameter = true; - } - url.append(key).append("=").append(value); - } - } - String proxyUrl = url.toString(); - log.info("\n\nProxy opening connection to: " + proxyUrl + "\n\n"); - try { - httpget = new HttpGet(proxyUrl); - HttpClient client = ProxyConnectionManager.httpClient; - HttpResponse httpResponse = client.execute(httpget); - int statusCode = httpResponse.getStatusLine().getStatusCode(); - if (statusCode == HttpStatus.SC_OK) { - // writeTo swallows exceptions and never quits even if outputstream is - // throwing IOExceptions (such as broken pipe) ... since the - // inputstream is infinite - // httpResponse.getEntity().writeTo(new - // OutputStreamWrapper(response.getOutputStream())); - // so I copy it manually ... - is = httpResponse.getEntity().getContent(); - - // set headers - copyHeadersToServletResponse(httpResponse.getAllHeaders(), response); - - // copy data from source to response - OutputStream os = response.getOutputStream(); - int b = -1; - while ((b = is.read()) != -1) { - try { - os.write(b); - if (b == 10 /** flush buffer on line feed */ - ) { - os.flush(); - } - } - catch (Exception ex) { - if (ex.getClass().getSimpleName() - .equalsIgnoreCase("ClientAbortException")) { - // don't throw an exception as this means the user closed - // the connection - log.debug("Connection closed by client. Will stop proxying ..."); - // break out of the while loop - break; - } - else { - // received unknown error while writing so throw an - // exception - throw new RuntimeException(ex); - } - } - } - } - else { - log.warn("Failed opening connection to " + proxyUrl + " : " - + statusCode + " : " + httpResponse.getStatusLine()); - } - } - catch (Exception ex) { - log.error("Error proxying request: " + url, ex); - } - finally { - if (httpget != null) { - try { - httpget.abort(); - } - catch (Exception ex) { - log.error("failed aborting proxy connection.", ex); - } - } - - // httpget.abort() MUST be called first otherwise is.close() hangs - // (because data is still streaming?) - if (is != null) { - // this should already be closed by httpget.abort() above - try { - is.close(); - } - catch (Exception ex) { - // ignore errors on close - } - } - } - - } - - private void copyHeadersToServletResponse(Header[] headers, - HttpServletResponse response) { - for (Header header : headers) { - // Some versions of Cloud Foundry (HAProxy) are - // incorrectly setting a "Connection: close" header - // causing the Hystrix dashboard to close the connection - // to the stream - // https://github.com/cloudfoundry/gorouter/issues/71 - if (this.enableIgnoreConnectionCloseHeader - && HttpHeaders.CONNECTION.equalsIgnoreCase(header.getName()) - && CONNECTION_CLOSE_VALUE.equalsIgnoreCase(header.getValue())) { - log.warn("Ignoring 'Connection: close' header from stream response"); - } - else if (!HttpHeaders.TRANSFER_ENCODING.equalsIgnoreCase(header.getName())) { - response.addHeader(header.getName(), header.getValue()); - } - } - } - - @SuppressWarnings("deprecation") - private static class ProxyConnectionManager { - - private final static PoolingClientConnectionManager threadSafeConnectionManager = new PoolingClientConnectionManager(); - - private final static HttpClient httpClient = new DefaultHttpClient( - threadSafeConnectionManager); - - static { - log.debug("Initialize ProxyConnectionManager"); - /* common settings */ - HttpParams httpParams = httpClient.getParams(); - HttpConnectionParams.setConnectionTimeout(httpParams, 5000); - HttpConnectionParams.setSoTimeout(httpParams, 10000); - - /* number of connections to allow */ - threadSafeConnectionManager.setDefaultMaxPerRoute(400); - threadSafeConnectionManager.setMaxTotal(400); - } - - } - - } -} diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardController.java b/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardController.java deleted file mode 100644 index 9c4ca316..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardController.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.dashboard; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.context.request.WebRequest; - -/** - * @author Dave Syer - */ -@Controller -public class HystrixDashboardController { - - @RequestMapping("/hystrix") - public String home(Model model, WebRequest request) { - model.addAttribute("basePath", extractPath(request)); - return "hystrix/index"; - } - - @RequestMapping("/hystrix/{path}") - public String monitor(@PathVariable String path, Model model, WebRequest request) { - model.addAttribute("basePath", extractPath(request)); - model.addAttribute("contextPath", request.getContextPath()); - return "hystrix/" + path; - } - - private String extractPath(WebRequest request) { - String path = request.getContextPath() - + request.getAttribute("org.springframework." - + "web.servlet.HandlerMapping.pathWithinHandlerMapping", - RequestAttributes.SCOPE_REQUEST); - return path; - } - -} diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardProperties.java b/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardProperties.java deleted file mode 100644 index 4223204d..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardProperties.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.cloud.netflix.hystrix.dashboard; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * @author Roy Clarkson - * @author Fahim Farook - */ -@ConfigurationProperties("hystrix.dashboard") -public class HystrixDashboardProperties { - - /** - * Directs the Hystrix dashboard to ignore 'Connection:close' headers if present in - * the Hystrix response stream - */ - private boolean enableIgnoreConnectionCloseHeader = false; - - /** - * Initialization parameters for {@link ProxyStreamServlet}. ProxyStreamServlet itself - * is not dependent on any initialization parameters, but could be used for adding web - * container specific configurations. i.e. wl-dispatch-policy for WebLogic. - */ - private Map initParameters = new HashMap<>(); - - public boolean isEnableIgnoreConnectionCloseHeader() { - return enableIgnoreConnectionCloseHeader; - } - - public void setEnableIgnoreConnectionCloseHeader( - boolean enableIgnoreConnectionCloseHeader) { - this.enableIgnoreConnectionCloseHeader = enableIgnoreConnectionCloseHeader; - } - - public Map getInitParameters() { - return this.initParameters; - } -} diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/hystrixCommand.css b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/hystrixCommand.css deleted file mode 100644 index c3111743..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/hystrixCommand.css +++ /dev/null @@ -1,200 +0,0 @@ -.dependencies .spacer { - width: 100%; - margin: 0 auto; - padding-top:4px; - clear:both; -} - - -.dependencies .last { - margin-right: 0px; -} - -.dependencies span.loading { - display: block; - padding-top: 6%; - padding-bottom: 6%; - color: gray; - text-align: center; -} - -.dependencies span.loading.failed { - color: red; -} - - -.dependencies div.monitor { - float: left; - margin-right:5px; - margin-top:5px; -} - -.dependencies div.monitor p.name { - font-weight:bold; - font-size: 10pt; - text-align: right; - padding-bottom: 5px; -} - -.dependencies div.monitor_data { - margin: 0 auto; -} - -/* override the HREF when we have specified it as a tooltip to not act like a link */ -.dependencies div.monitor_data a.tooltip { - text-decoration: none; - cursor: default; -} - -.dependencies div.monitor_data div.counters { - text-align: right; - padding-bottom: 10px; - font-size: 10pt; - clear: both; - -} - -.dependencies div.monitor_data div.counters div.cell { - display: inline; - float: right; -} - -.dependencies .borderRight { - border-right: 1px solid grey; - padding-right: 6px; - padding-left: 8px; -} - -.dependencies div.cell .line { - display: block; -} - -.dependencies div.monitor_data a, -.dependencies span.rate_value { - font-weight:bold; -} - - -.dependencies span.smaller { - font-size: 8pt; - color: grey; -} - - - -.dependencies div.tableRow { - width:100%; - white-space: nowrap; - font-size: 8pt; - margin: 0 auto; - clear:both; - padding-left:26%; -} - -.dependencies div.tableRow .cell { - float:left; -} - -.dependencies div.tableRow .header { - width:18%; - text-align:right; - padding-right:2%; -} - -.dependencies div.tableRow .data { - width:17%; - font-weight: bold; - text-align:right; -} - - -.dependencies div.monitor { - width: 245px; /* we want a fixed width instead of percentage as I want the boxes to be a set size and then fill in as many as can fit in each row ... this allows 3 columns on an iPad */ - height: 155px; -} - -.dependencies .success { - color: green; -} -.dependencies .shortCircuited { - color: blue; -} -.dependencies .timeout { - color: #FF9900; /* shade of orange */ -} -.dependencies .failure { - color: red; -} - -.badRequest { - color: #00CC99; -} - -.dependencies .rejected { - color: purple; -} - -.dependencies .exceptionsThrown { - color: brown; -} - -.dependencies div.monitor_data a.rate { - color: black; - font-size: 11pt; -} - -.dependencies div.rate { - padding-top: 1px; - clear:both; - text-align:right; -} - -.dependencies .errorPercentage { - color: grey; -} - -.dependencies div.cell .errorPercentage { - padding-left:5px; - font-size: 12pt !important; -} - - -.dependencies div.monitor div.chart { -} - -.dependencies div.monitor div.chart svg { -} - -.dependencies div.monitor div.chart svg text { - fill: white; -} - - -.dependencies div.circuitStatus { - width:100%; - white-space: nowrap; - font-size: 9pt; - margin: 0 auto; - clear:both; - text-align:right; - padding-top: 4px; -} - -.dependencies #hidden { - width:1px; - height:1px; - background: lightgrey; - display: none; -} - - - -/* sparkline */ -.dependencies path { - stroke: steelblue; - stroke-width: 1; - fill: none; -} - - -} diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/hystrixCommand.js b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/hystrixCommand.js deleted file mode 100644 index 9d5724d2..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/hystrixCommand.js +++ /dev/null @@ -1,542 +0,0 @@ - -(function(window) { - - // cache the templates we use on this page as global variables (asynchronously) - jQuery.get(getRelativePath("components/hystrixCommand/templates/hystrixCircuit.html"), function(data) { - hystrixTemplateCircuit = data; - }); - jQuery.get(getRelativePath("components/hystrixCommand/templates/hystrixCircuitContainer.html"), function(data) { - hystrixTemplateCircuitContainer = data; - }); - - function getRelativePath(path) { - var p = location.pathname.slice(0, location.pathname.lastIndexOf("/")+1); - return p + path; - } - - /** - * Object containing functions for displaying and updating the UI with streaming data. - * - * Publish this externally as "HystrixCommandMonitor" - */ - window.HystrixCommandMonitor = function(containerId, args) { - - var self = this; // keep scope under control - self.args = args; - if(self.args == undefined) { - self.args = {}; - } - - this.containerId = containerId; - - /** - * Initialization on construction - */ - // intialize various variables we use for visualization - var maxXaxisForCircle="40%"; - var maxYaxisForCircle="40%"; - var maxRadiusForCircle="125"; - - // CIRCUIT_BREAKER circle visualization settings - self.circuitCircleRadius = d3.scale.pow().exponent(0.5).domain([0, 400]).range(["5", maxRadiusForCircle]); // requests per second per host - self.circuitCircleYaxis = d3.scale.linear().domain([0, 400]).range(["30%", maxXaxisForCircle]); - self.circuitCircleXaxis = d3.scale.linear().domain([0, 400]).range(["30%", maxYaxisForCircle]); - self.circuitColorRange = d3.scale.linear().domain([10, 25, 40, 50]).range(["green", "#FFCC00", "#FF9900", "red"]); - self.circuitErrorPercentageColorRange = d3.scale.linear().domain([0, 10, 35, 50]).range(["grey", "black", "#FF9900", "red"]); - - /** - * We want to keep sorting in the background since data values are always changing, so this will re-sort every X milliseconds - * to maintain whatever sort the user (or default) has chosen. - * - * In other words, sorting only for adds/deletes is not sufficient as all but alphabetical sort are dynamically changing. - */ - setInterval(function() { - // sort since we have added a new one - self.sortSameAsLast(); - }, 10000); - - - /** - * END of Initialization on construction - */ - - /** - * Event listener to handle new messages from EventSource as streamed from the server. - */ - /* public */ self.eventSourceMessageListener = function(e) { - var data = JSON.parse(e.data); - if(data) { - // check for reportingHosts (if not there, set it to 1 for singleHost vs cluster) - if(!data.reportingHosts) { - data.reportingHosts = 1; - } - - if(data && data.type == 'HystrixCommand') { - if (data.deleteData == 'true') { - deleteCircuit(data.escapedName); - } else { - displayCircuit(data); - } - } - } - }; - - /** - * Pre process the data before displying in the UI. - * e.g Get Averages from sums, do rate calculation etc. - */ - function preProcessData(data) { - // set defaults for values that may be missing from older streams - setIfMissing(data, "rollingCountBadRequests", 0); - // assert all the values we need - validateData(data); - // escape string used in jQuery & d3 selectors - data.escapedName = data.name.replace(/([ !"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g,'\\$1'); - // do math - convertAllAvg(data); - calcRatePerSecond(data); - } - - function setIfMissing(data, key, defaultValue) { - if(data[key] == undefined) { - data[key] = defaultValue; - } - } - - /** - * Since the stream of data can be aggregated from multiple hosts in a tiered manner - * the aggregation just sums everything together and provides us the denominator (reportingHosts) - * so we must divide by it to get an average per instance value. - * - * We want to do this on any numerical values where we want per instance rather than cluster-wide sum. - */ - function convertAllAvg(data) { - convertAvg(data, "errorPercentage", true); - convertAvg(data, "latencyExecute_mean", false); - convertAvg(data, "latencyTotal_mean", false); - } - - function convertAvg(data, key, decimal) { - if (decimal) { - data[key] = getInstanceAverage(data[key], data["reportingHosts"], decimal); - } else { - data[key] = getInstanceAverage(data[key], data["reportingHosts"], decimal); - } - } - - function getInstanceAverage(value, reportingHosts, decimal) { - if (decimal) { - return roundNumber(value/reportingHosts); - } else { - return Math.floor(value/reportingHosts); - } - } - - function calcRatePerSecond(data) { - var numberSeconds = data["propertyValue_metricsRollingStatisticalWindowInMilliseconds"] / 1000; - - var totalRequests = data["requestCount"]; - if (totalRequests < 0) { - totalRequests = 0; - } - data["ratePerSecond"] = roundNumber(totalRequests / numberSeconds); - data["ratePerSecondPerHost"] = roundNumber(totalRequests / numberSeconds / data["reportingHosts"]) ; - } - - function validateData(data) { - assertNotNull(data,"reportingHosts"); - assertNotNull(data,"type"); - assertNotNull(data,"name"); - assertNotNull(data,"group"); - // assertNotNull(data,"currentTime"); - assertNotNull(data,"isCircuitBreakerOpen"); - assertNotNull(data,"errorPercentage"); - assertNotNull(data,"errorCount"); - assertNotNull(data,"requestCount"); - assertNotNull(data,"rollingCountCollapsedRequests"); - assertNotNull(data,"rollingCountExceptionsThrown"); - assertNotNull(data,"rollingCountFailure"); - assertNotNull(data,"rollingCountFallbackFailure"); - assertNotNull(data,"rollingCountFallbackRejection"); - assertNotNull(data,"rollingCountFallbackSuccess"); - assertNotNull(data,"rollingCountResponsesFromCache"); - assertNotNull(data,"rollingCountSemaphoreRejected"); - assertNotNull(data,"rollingCountShortCircuited"); - assertNotNull(data,"rollingCountSuccess"); - assertNotNull(data,"rollingCountThreadPoolRejected"); - assertNotNull(data,"rollingCountTimeout"); - assertNotNull(data,"rollingCountBadRequests"); - assertNotNull(data,"currentConcurrentExecutionCount"); - assertNotNull(data,"latencyExecute_mean"); - assertNotNull(data,"latencyExecute"); - assertNotNull(data,"latencyTotal_mean"); - assertNotNull(data,"latencyTotal"); - assertNotNull(data,"propertyValue_circuitBreakerRequestVolumeThreshold"); - assertNotNull(data,"propertyValue_circuitBreakerSleepWindowInMilliseconds"); - assertNotNull(data,"propertyValue_circuitBreakerErrorThresholdPercentage"); - assertNotNull(data,"propertyValue_circuitBreakerForceOpen"); - assertNotNull(data,"propertyValue_circuitBreakerForceClosed"); - assertNotNull(data,"propertyValue_executionIsolationStrategy"); - assertNotNull(data,"propertyValue_executionIsolationThreadTimeoutInMilliseconds"); - assertNotNull(data,"propertyValue_executionIsolationThreadInterruptOnTimeout"); - // assertNotNull(data,"propertyValue_executionIsolationThreadPoolKeyOverride"); - assertNotNull(data,"propertyValue_executionIsolationSemaphoreMaxConcurrentRequests"); - assertNotNull(data,"propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests"); - assertNotNull(data,"propertyValue_requestCacheEnabled"); - assertNotNull(data,"propertyValue_requestLogEnabled"); - assertNotNull(data,"propertyValue_metricsRollingStatisticalWindowInMilliseconds"); - } - - function assertNotNull(data, key) { - if(data[key] == undefined) { - throw new Error("Key Missing: " + key + " for " + data.name); - } - } - - /** - * Method to display the CIRCUIT data - * - * @param data - */ - /* private */ function displayCircuit(data) { - - try { - preProcessData(data); - } catch (err) { - log("Failed preProcessData: " + err.message); - return; - } - - // add the 'addCommas' function to the 'data' object so the HTML templates can use it - data.addCommas = addCommas; - // add the 'roundNumber' function to the 'data' object so the HTML templates can use it - data.roundNumber = roundNumber; - // add the 'getInstanceAverage' function to the 'data' object so the HTML templates can use it - data.getInstanceAverage = getInstanceAverage; - - var addNew = false; - // check if we need to create the container - if(!$('#CIRCUIT_' + data.escapedName).length) { - // args for display - if(self.args.includeDetailIcon != undefined && self.args.includeDetailIcon) { - data.includeDetailIcon = true; - }else { - data.includeDetailIcon = false; - } - - // it doesn't exist so add it - var html = tmpl(hystrixTemplateCircuitContainer, data); - // remove the loading thing first - $('#' + containerId + ' span.loading').remove(); - // now create the new data and add it - $('#' + containerId + '').append(html); - - // add the default sparkline graph - d3.selectAll('#graph_CIRCUIT_' + data.escapedName + ' svg').append("svg:path"); - - // remember this is new so we can trigger a sort after setting data - addNew = true; - } - - - // now update/insert the data - $('#CIRCUIT_' + data.escapedName + ' div.monitor_data').html(tmpl(hystrixTemplateCircuit, data)); - - var ratePerSecond = data.ratePerSecond; - var ratePerSecondPerHost = data.ratePerSecondPerHost; - var ratePerSecondPerHostDisplay = ratePerSecondPerHost; - var errorThenVolume = (data.errorPercentage * 100000000) + ratePerSecond; - - // set the rates on the div element so it's available for sorting - $('#CIRCUIT_' + data.escapedName).attr('rate_value', ratePerSecond); - $('#CIRCUIT_' + data.escapedName).attr('error_then_volume', errorThenVolume); - - // update errorPercentage color on page - $('#CIRCUIT_' + data.escapedName + ' a.errorPercentage').css('color', self.circuitErrorPercentageColorRange(data.errorPercentage)); - - updateCircle('circuit', '#CIRCUIT_' + data.escapedName + ' circle', ratePerSecondPerHostDisplay, data.errorPercentage); - - if(data.graphValues) { - // we have a set of values to initialize with - updateSparkline('circuit', '#CIRCUIT_' + data.escapedName + ' path', data.graphValues); - } else { - updateSparkline('circuit', '#CIRCUIT_' + data.escapedName + ' path', ratePerSecond); - } - - if(addNew) { - // sort since we added a new circuit - self.sortSameAsLast(); - } - } - - /* round a number to X digits: num => the number to round, dec => the number of decimals */ - /* private */ function roundNumber(num) { - var dec=1; - var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); - var resultAsString = result.toString(); - if(resultAsString.indexOf('.') == -1) { - resultAsString = resultAsString + '.0'; - } - return resultAsString; - }; - - - - - /* private */ function updateCircle(variablePrefix, cssTarget, rate, errorPercentage) { - var newXaxisForCircle = self[variablePrefix + 'CircleXaxis'](rate); - if(parseInt(newXaxisForCircle) > parseInt(maxXaxisForCircle)) { - newXaxisForCircle = maxXaxisForCircle; - } - var newYaxisForCircle = self[variablePrefix + 'CircleYaxis'](rate); - if(parseInt(newYaxisForCircle) > parseInt(maxYaxisForCircle)) { - newYaxisForCircle = maxYaxisForCircle; - } - var newRadiusForCircle = self[variablePrefix + 'CircleRadius'](rate); - if(parseInt(newRadiusForCircle) > parseInt(maxRadiusForCircle)) { - newRadiusForCircle = maxRadiusForCircle; - } - - d3.selectAll(cssTarget) - .transition() - .duration(400) - .attr("cy", newYaxisForCircle) - .attr("cx", newXaxisForCircle) - .attr("r", newRadiusForCircle) - .style("fill", self[variablePrefix + 'ColorRange'](errorPercentage)); - } - - /* private */ function updateSparkline(variablePrefix, cssTarget, newDataPoint) { - var currentTimeMilliseconds = new Date().getTime(); - var data = self[variablePrefix + cssTarget + '_data']; - if(typeof data == 'undefined') { - // else it's new - if(typeof newDataPoint == 'object') { - // we received an array of values, so initialize with it - data = newDataPoint; - } else { - // v: VALUE, t: TIME_IN_MILLISECONDS - data = [{"v":parseFloat(newDataPoint),"t":currentTimeMilliseconds}]; - } - self[variablePrefix + cssTarget + '_data'] = data; - } else { - if(typeof newDataPoint == 'object') { - /* if an array is passed in we'll replace the cached one */ - data = newDataPoint; - } else { - // else we just add to the existing one - data.push({"v":parseFloat(newDataPoint),"t":currentTimeMilliseconds}); - } - } - - while(data.length > 200) { // 400 should be plenty for the 2 minutes we have the scale set to below even with a very low update latency - // remove data so we don't keep increasing forever - data.shift(); - } - - if(data.length == 1 && data[0].v == 0) { - //console.log("we have a single 0 so skipping"); - // don't show if we have a single 0 - return; - } - - if(data.length > 1 && data[0].v == 0 && data[1].v != 0) { - //console.log("we have a leading 0 so removing it"); - // get rid of a leading 0 if the following number is not a 0 - data.shift(); - } - - var xScale = d3.time.scale().domain([new Date(currentTimeMilliseconds-(60*1000*2)), new Date(currentTimeMilliseconds)]).range([0, 140]); - - var yMin = d3.min(data, function(d) { return d.v; }); - var yMax = d3.max(data, function(d) { return d.v; }); - var yScale = d3.scale.linear().domain([yMin, yMax]).nice().range([60, 0]); // y goes DOWN, so 60 is the "lowest" - - sparkline = d3.svg.line() - // assign the X function to plot our line as we wish - .x(function(d,i) { - // return the X coordinate where we want to plot this datapoint based on the time - return xScale(new Date(d.t)); - }) - .y(function(d) { - return yScale(d.v); - }) - .interpolate("basis"); - - d3.selectAll(cssTarget).attr("d", sparkline(data)); - } - - /* private */ function deleteCircuit(circuitName) { - $('#CIRCUIT_' + circuitName).remove(); - } - - }; - - // public methods for sorting - HystrixCommandMonitor.prototype.sortByVolume = function() { - var direction = "desc"; - if(this.sortedBy == 'rate_desc') { - direction = 'asc'; - } - this.sortByVolumeInDirection(direction); - }; - - HystrixCommandMonitor.prototype.sortByVolumeInDirection = function(direction) { - this.sortedBy = 'rate_' + direction; - $('#' + this.containerId + ' div.monitor').tsort({order: direction, attr: 'rate_value'}); - }; - - HystrixCommandMonitor.prototype.sortAlphabetically = function() { - var direction = "asc"; - if(this.sortedBy == 'alph_asc') { - direction = 'desc'; - } - this.sortAlphabeticalInDirection(direction); - }; - - HystrixCommandMonitor.prototype.sortAlphabeticalInDirection = function(direction) { - this.sortedBy = 'alph_' + direction; - $('#' + this.containerId + ' div.monitor').tsort("p.name", {order: direction}); - }; - - - HystrixCommandMonitor.prototype.sortByError = function() { - var direction = "desc"; - if(this.sortedBy == 'error_desc') { - direction = 'asc'; - } - this.sortByErrorInDirection(direction); - }; - - HystrixCommandMonitor.prototype.sortByErrorInDirection = function(direction) { - this.sortedBy = 'error_' + direction; - $('#' + this.containerId + ' div.monitor').tsort(".errorPercentage .value", {order: direction}); - }; - - HystrixCommandMonitor.prototype.sortByErrorThenVolume = function() { - var direction = "desc"; - if(this.sortedBy == 'error_then_volume_desc') { - direction = 'asc'; - } - this.sortByErrorThenVolumeInDirection(direction); - }; - - HystrixCommandMonitor.prototype.sortByErrorThenVolumeInDirection = function(direction) { - this.sortedBy = 'error_then_volume_' + direction; - $('#' + this.containerId + ' div.monitor').tsort({order: direction, attr: 'error_then_volume'}); - }; - - HystrixCommandMonitor.prototype.sortByLatency90 = function() { - var direction = "desc"; - if(this.sortedBy == 'lat90_desc') { - direction = 'asc'; - } - this.sortedBy = 'lat90_' + direction; - this.sortByMetricInDirection(direction, ".latency90 .value"); - }; - - HystrixCommandMonitor.prototype.sortByLatency99 = function() { - var direction = "desc"; - if(this.sortedBy == 'lat99_desc') { - direction = 'asc'; - } - this.sortedBy = 'lat99_' + direction; - this.sortByMetricInDirection(direction, ".latency99 .value"); - }; - - HystrixCommandMonitor.prototype.sortByLatency995 = function() { - var direction = "desc"; - if(this.sortedBy == 'lat995_desc') { - direction = 'asc'; - } - this.sortedBy = 'lat995_' + direction; - this.sortByMetricInDirection(direction, ".latency995 .value"); - }; - - HystrixCommandMonitor.prototype.sortByLatencyMean = function() { - var direction = "desc"; - if(this.sortedBy == 'latMean_desc') { - direction = 'asc'; - } - this.sortedBy = 'latMean_' + direction; - this.sortByMetricInDirection(direction, ".latencyMean .value"); - }; - - HystrixCommandMonitor.prototype.sortByLatencyMedian = function() { - var direction = "desc"; - if(this.sortedBy == 'latMedian_desc') { - direction = 'asc'; - } - this.sortedBy = 'latMedian_' + direction; - this.sortByMetricInDirection(direction, ".latencyMedian .value"); - }; - - HystrixCommandMonitor.prototype.sortByMetricInDirection = function(direction, metric) { - $('#' + this.containerId + ' div.monitor').tsort(metric, {order: direction}); - }; - - // this method is for when new divs are added to cause the elements to be sorted to whatever the user last chose - HystrixCommandMonitor.prototype.sortSameAsLast = function() { - if(this.sortedBy == 'alph_asc') { - this.sortAlphabeticalInDirection('asc'); - } else if(this.sortedBy == 'alph_desc') { - this.sortAlphabeticalInDirection('desc'); - } else if(this.sortedBy == 'rate_asc') { - this.sortByVolumeInDirection('asc'); - } else if(this.sortedBy == 'rate_desc') { - this.sortByVolumeInDirection('desc'); - } else if(this.sortedBy == 'error_asc') { - this.sortByErrorInDirection('asc'); - } else if(this.sortedBy == 'error_desc') { - this.sortByErrorInDirection('desc'); - } else if(this.sortedBy == 'error_then_volume_asc') { - this.sortByErrorThenVolumeInDirection('asc'); - } else if(this.sortedBy == 'error_then_volume_desc') { - this.sortByErrorThenVolumeInDirection('desc'); - } else if(this.sortedBy == 'lat90_asc') { - this.sortByMetricInDirection('asc', '.latency90 .value'); - } else if(this.sortedBy == 'lat90_desc') { - this.sortByMetricInDirection('desc', '.latency90 .value'); - } else if(this.sortedBy == 'lat99_asc') { - this.sortByMetricInDirection('asc', '.latency99 .value'); - } else if(this.sortedBy == 'lat99_desc') { - this.sortByMetricInDirection('desc', '.latency99 .value'); - } else if(this.sortedBy == 'lat995_asc') { - this.sortByMetricInDirection('asc', '.latency995 .value'); - } else if(this.sortedBy == 'lat995_desc') { - this.sortByMetricInDirection('desc', '.latency995 .value'); - } else if(this.sortedBy == 'latMean_asc') { - this.sortByMetricInDirection('asc', '.latencyMean .value'); - } else if(this.sortedBy == 'latMean_desc') { - this.sortByMetricInDirection('desc', '.latencyMean .value'); - } else if(this.sortedBy == 'latMedian_asc') { - this.sortByMetricInDirection('asc', '.latencyMedian .value'); - } else if(this.sortedBy == 'latMedian_desc') { - this.sortByMetricInDirection('desc', '.latencyMedian .value'); - } - }; - - // default sort type and direction - this.sortedBy = 'alph_asc'; - - - // a temporary home for the logger until we become more sophisticated - function log(message) { - console.log(message); - }; - - function addCommas(nStr){ - nStr += ''; - if(nStr.length <=3) { - return nStr; //shortcut if we don't need commas - } - x = nStr.split('.'); - x1 = x[0]; - x2 = x.length > 1 ? '.' + x[1] : ''; - var rgx = /(\d+)(\d{3})/; - while (rgx.test(x1)) { - x1 = x1.replace(rgx, '$1' + ',' + '$2'); - } - return x1 + x2; - } -})(window); diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/magnifying-glass-icon-20.png b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/magnifying-glass-icon-20.png deleted file mode 100644 index 4898b485..00000000 Binary files a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/magnifying-glass-icon-20.png and /dev/null differ diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/magnifying-glass-icon.png b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/magnifying-glass-icon.png deleted file mode 100644 index 04feae91..00000000 Binary files a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/magnifying-glass-icon.png and /dev/null differ diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/templates/hystrixCircuit.html b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/templates/hystrixCircuit.html deleted file mode 100644 index e9328ab8..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/templates/hystrixCircuit.html +++ /dev/null @@ -1,77 +0,0 @@ - - - - - -
- <% if(propertyValue_circuitBreakerForceClosed) { %> - [ Forced Closed ] - <% } %> - <% if(propertyValue_circuitBreakerForceOpen) { %> - Circuit Forced Open - <% } else { %> - <% if(isCircuitBreakerOpen == reportingHosts) { %> - Circuit Open - <% } else if(isCircuitBreakerOpen == 0) { %> - Circuit Closed - <% } else { - /* We have some circuits that are open */ - %> - Circuit <%= isCircuitBreakerOpen.toString().replace("true", "Open").replace("false", "Closed") %>) - <% } %> - <% } %> -
- -
- -
- <% if(typeof reportingHosts != 'undefined') { %> -
Hosts
-
<%= reportingHosts %>
- <% } else { %> -
Host
-
Single
- <% } %> -
90th
-
<%= getInstanceAverage(latencyExecute['90'], reportingHosts, false) %>ms
-
-
-
Median
-
<%= getInstanceAverage(latencyExecute['50'], reportingHosts, false) %>ms
-
99th
-
<%= getInstanceAverage(latencyExecute['99'], reportingHosts, false) %>ms
-
-
-
Mean
-
<%= latencyExecute_mean %>ms
-
99.5th
-
<%= getInstanceAverage(latencyExecute['99.5'], reportingHosts, false) %>ms
-
- - diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/templates/hystrixCircuitContainer.html b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/templates/hystrixCircuitContainer.html deleted file mode 100644 index 1a47ef7b..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/templates/hystrixCircuitContainer.html +++ /dev/null @@ -1,40 +0,0 @@ -
- <% - var displayName = name; - var toolTip = ""; - if(displayName.length > 32) { - displayName = displayName.substring(0,4) + "..." + displayName.substring(displayName.length-20, displayName.length); - toolTip = "title=\"" + name + "\""; - } - %> - -
-
- <% if(includeDetailIcon) { %> -

style="padding-right:16px"> - <%= displayName %> - -

- <% } else { %> -

><%= displayName %>

- <% } %> -
-
-
-
-
- - -
diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/templates/hystrixCircuitProperties.html b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/templates/hystrixCircuitProperties.html deleted file mode 100644 index 5b8c0fae..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixCommand/templates/hystrixCircuitProperties.html +++ /dev/null @@ -1,6 +0,0 @@ -
-
Median
-
<%= sla_medianLastMinute %>ms
-
99th
-
<%= sla_percentile99LastMinute %>ms
-
diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixThreadPool/hystrixThreadPool.css b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixThreadPool/hystrixThreadPool.css deleted file mode 100644 index e82ea5cc..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixThreadPool/hystrixThreadPool.css +++ /dev/null @@ -1,141 +0,0 @@ -.dependencyThreadPools .spacer { - width: 100%; - margin: 0 auto; - padding-top:4px; - clear:both; -} - - -.dependencyThreadPools .last { - margin-right: 0px; -} - -.dependencyThreadPools span.loading { - display: block; - padding-top: 6%; - padding-bottom: 6%; - color: gray; - text-align: center; -} - -.dependencyThreadPools span.loading.failed { - color: red; -} - - -.dependencyThreadPools div.monitor { - float: left; - margin-right:5px; /* these are tweaked to look good on desktop and iPad portrait, and fit things densely */ - margin-top:5px; -} - -.dependencyThreadPools div.monitor p.name { - font-weight:bold; - font-size: 10pt; - text-align: right; - padding-bottom: 5px; -} - -.dependencyThreadPools div.monitor_data { - margin: 0 auto; -} - -.dependencyThreadPools span.smaller { - font-size: 8pt; - color: grey; -} - - -.dependencyThreadPools div.tableRow { - width:100%; - white-space: nowrap; - font-size: 8pt; - margin: 0 auto; - clear:both; -} - -.dependencyThreadPools div.tableRow .cell { - float:left; -} - -.dependencyThreadPools div.tableRow .header { - text-align:right; - padding-right:5px; -} - -.dependencyThreadPools div.tableRow .header.left { - width:85px; -} - -.dependencyThreadPools div.tableRow .header.right { - width:75px; -} - -.dependencyThreadPools div.tableRow .data { - font-weight: bold; - text-align:right; -} - -.dependencyThreadPools div.tableRow .data.left { - width:30px; -} - -.dependencyThreadPools div.tableRow .data.right { - width:45px; -} - -.dependencyThreadPools div.monitor { - width: 245px; /* we want a fixed width instead of percentage as I want the boxes to be a set size and then fill in as many as can fit in each row ... this allows 3 columns on an iPad */ - height: 110px; -} - - - - - -/* override the HREF when we have specified it as a tooltip to not act like a link */ -.dependencyThreadPools div.monitor_data a.tooltip { - text-decoration: none; - cursor: default; -} - -.dependencyThreadPools div.monitor_data a.rate { - font-weight:bold; - color: black; - font-size: 11pt; -} - -.dependencyThreadPools div.rate { - padding-top: 1px; - clear:both; - text-align:right; -} - -.dependencyThreadPools span.rate_value { - font-weight:bold; -} - - - - - - - -.dependencyThreadPools div.monitor div.chart { -} - -.dependencyThreadPools div.monitor div.chart svg { -} - -.dependencyThreadPools div.monitor div.chart svg text { - fill: white; -} - -.dependencyThreadPools #hidden { - width:1px; - height:1px; - background: lightgrey; - display: none; -} - - diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixThreadPool/hystrixThreadPool.js b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixThreadPool/hystrixThreadPool.js deleted file mode 100644 index 851562bf..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixThreadPool/hystrixThreadPool.js +++ /dev/null @@ -1,343 +0,0 @@ - -(function(window) { - - // cache the templates we use on this page as global variables (asynchronously) - jQuery.get(getRelativePath("components/hystrixThreadPool/templates/hystrixThreadPool.html"), function(data) { - htmlTemplate = data; - }); - jQuery.get(getRelativePath("components/hystrixThreadPool/templates/hystrixThreadPoolContainer.html"), function(data) { - htmlTemplateContainer = data; - }); - - function getRelativePath(path) { - var p = location.pathname.slice(0, location.pathname.lastIndexOf("/")+1); - return p + path; - } - - /** - * Object containing functions for displaying and updating the UI with streaming data. - * - * Publish this externally as "HystrixThreadPoolMonitor" - */ - window.HystrixThreadPoolMonitor = function(containerId) { - - var self = this; // keep scope under control - - this.containerId = containerId; - - /** - * Initialization on construction - */ - // intialize various variables we use for visualization - var maxXaxisForCircle="40%"; - var maxYaxisForCircle="40%"; - var maxRadiusForCircle="125"; - var maxDomain = 2000; - - self.circleRadius = d3.scale.pow().exponent(0.5).domain([0, maxDomain]).range(["5", maxRadiusForCircle]); // requests per second per host - self.circleYaxis = d3.scale.linear().domain([0, maxDomain]).range(["30%", maxXaxisForCircle]); - self.circleXaxis = d3.scale.linear().domain([0, maxDomain]).range(["30%", maxYaxisForCircle]); - self.colorRange = d3.scale.linear().domain([10, 25, 40, 50]).range(["green", "#FFCC00", "#FF9900", "red"]); - self.errorPercentageColorRange = d3.scale.linear().domain([0, 10, 35, 50]).range(["grey", "black", "#FF9900", "red"]); - - /** - * We want to keep sorting in the background since data values are always changing, so this will re-sort every X milliseconds - * to maintain whatever sort the user (or default) has chosen. - * - * In other words, sorting only for adds/deletes is not sufficient as all but alphabetical sort are dynamically changing. - */ - setInterval(function() { - // sort since we have added a new one - self.sortSameAsLast(); - }, 1000) - - /** - * END of Initialization on construction - */ - - /** - * Event listener to handle new messages from EventSource as streamed from the server. - */ - /* public */ self.eventSourceMessageListener = function(e) { - var data = JSON.parse(e.data); - if(data) { - // check for reportingHosts (if not there, set it to 1 for singleHost vs cluster) - if(!data.reportingHosts) { - data.reportingHosts = 1; - } - - if(data && data.type == 'HystrixThreadPool') { - if (data.deleteData == 'true') { - deleteThreadPool(data.escapedName); - } else { - displayThreadPool(data); - } - } - } - } - - /** - * Pre process the data before displying in the UI. - * e.g Get Averages from sums, do rate calculation etc. - */ - function preProcessData(data) { - validateData(data); - // escape string used in jQuery & d3 selectors - data.escapedName = data.name.replace(/([ !"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g,'\\$1'); - // do math - converAllAvg(data); - calcRatePerSecond(data); - } - - function converAllAvg(data) { - convertAvg(data, "propertyValue_queueSizeRejectionThreshold", false); - } - - function convertAvg(data, key, decimal) { - if (decimal) { - data[key] = roundNumber(data[key]/data["reportingHosts"]); - } else { - data[key] = Math.floor(data[key]/data["reportingHosts"]); - } - } - - function calcRatePerSecond(data) { - var numberSeconds = data["propertyValue_metricsRollingStatisticalWindowInMilliseconds"] / 1000; - - var totalThreadsExecuted = data["rollingCountThreadsExecuted"]; - if (totalThreadsExecuted < 0) { - totalThreadsExecuted = 0; - } - data["ratePerSecond"] = roundNumber(totalThreadsExecuted / numberSeconds); - data["ratePerSecondPerHost"] = roundNumber(totalThreadsExecuted / numberSeconds / data["reportingHosts"]); - } - - function validateData(data) { - - assertNotNull(data,"type"); - assertNotNull(data,"name"); - // assertNotNull(data,"currentTime"); - assertNotNull(data,"currentActiveCount"); - assertNotNull(data,"currentCompletedTaskCount"); - assertNotNull(data,"currentCorePoolSize"); - assertNotNull(data,"currentLargestPoolSize"); - assertNotNull(data,"currentMaximumPoolSize"); - assertNotNull(data,"currentPoolSize"); - assertNotNull(data,"currentQueueSize"); - assertNotNull(data,"currentTaskCount"); - assertNotNull(data,"rollingCountThreadsExecuted"); - assertNotNull(data,"rollingMaxActiveThreads"); - assertNotNull(data,"reportingHosts"); - - assertNotNull(data,"propertyValue_queueSizeRejectionThreshold"); - assertNotNull(data,"propertyValue_metricsRollingStatisticalWindowInMilliseconds"); - } - - function assertNotNull(data, key) { - if(data[key] == undefined) { - if (key == "dependencyOwner") { - data["dependencyOwner"] = data.name; - } else { - throw new Error("Key Missing: " + key + " for " + data.name) - } - } - } - - /** - * Method to display the THREAD_POOL data - * - * @param data - */ - /* private */ function displayThreadPool(data) { - - try { - preProcessData(data); - } catch (err) { - log("Failed preProcessData: " + err.message); - return; - } - - // add the 'addCommas' function to the 'data' object so the HTML templates can use it - data.addCommas = addCommas; - // add the 'roundNumber' function to the 'data' object so the HTML templates can use it - data.roundNumber = roundNumber; - - var addNew = false; - // check if we need to create the container - if(!$('#THREAD_POOL_' + data.escapedName).length) { - // it doesn't exist so add it - var html = tmpl(htmlTemplateContainer, data); - // remove the loading thing first - $('#' + containerId + ' span.loading').remove(); - // get the current last column and remove the 'last' class from it - $('#' + containerId + ' div.last').removeClass('last'); - // now create the new data and add it - $('#' + containerId + '').append(html); - // add the 'last' class to the column we just added - $('#' + containerId + ' div.monitor').last().addClass('last'); - - // add the default sparkline graph - d3.selectAll('#graph_THREAD_POOL_' + data.escapedName + ' svg').append("svg:path"); - - // remember this is new so we can trigger a sort after setting data - addNew = true; - } - - // set the rate on the div element so it's available for sorting - $('#THREAD_POOL_' + data.escapedName).attr('rate_value', data.ratePerSecondPerHost); - - // now update/insert the data - $('#THREAD_POOL_' + data.escapedName + ' div.monitor_data').html(tmpl(htmlTemplate, data)); - - // set variables for circle visualization - var rate = data.ratePerSecondPerHost; - // we will treat each item in queue as 1% of an error visualization - // ie. 5 threads in queue per instance == 5% error percentage - var errorPercentage = data.currentQueueSize / data.reportingHosts; - - updateCircle('#THREAD_POOL_' + data.escapedName + ' circle', rate, errorPercentage); - - if(addNew) { - // sort since we added a new circuit - self.sortSameAsLast(); - } - } - - /* round a number to X digits: num => the number to round, dec => the number of decimals */ - /* private */ function roundNumber(num) { - var dec=1; // we are hardcoding to support only 1 decimal so that our padding logic at the end is simple - var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); - var resultAsString = result.toString(); - if(resultAsString.indexOf('.') == -1) { - resultAsString = resultAsString + '.'; - for(var i=0; i parseInt(maxXaxisForCircle)) { - newXaxisForCircle = maxXaxisForCircle; - } - var newYaxisForCircle = self.circleYaxis(rate); - if(parseInt(newYaxisForCircle) > parseInt(maxYaxisForCircle)) { - newYaxisForCircle = maxYaxisForCircle; - } - var newRadiusForCircle = self.circleRadius(rate); - if(parseInt(newRadiusForCircle) > parseInt(maxRadiusForCircle)) { - newRadiusForCircle = maxRadiusForCircle; - } - - d3.selectAll(cssTarget) - .transition() - .duration(400) - .attr("cy", newYaxisForCircle) - .attr("cx", newXaxisForCircle) - .attr("r", newRadiusForCircle) - .style("fill", self.colorRange(errorPercentage)); - } - - /* private */ function deleteThreadPool(poolName) { - $('#THREAD_POOL_' + poolName).remove(); - } - - } - - // public methods for sorting - HystrixThreadPoolMonitor.prototype.sortByVolume = function() { - var direction = "desc"; - if(this.sortedBy == 'rate_desc') { - direction = 'asc'; - } - this.sortByVolumeInDirection(direction); - } - - HystrixThreadPoolMonitor.prototype.sortByVolumeInDirection = function(direction) { - this.sortedBy = 'rate_' + direction; - $('#' + this.containerId + ' div.monitor').tsort({order: direction, attr: 'rate_value'}); - } - - HystrixThreadPoolMonitor.prototype.sortAlphabetically = function() { - var direction = "asc"; - if(this.sortedBy == 'alph_asc') { - direction = 'desc'; - } - this.sortAlphabeticalInDirection(direction); - } - - HystrixThreadPoolMonitor.prototype.sortAlphabeticalInDirection = function(direction) { - this.sortedBy = 'alph_' + direction; - $('#' + this.containerId + ' div.monitor').tsort("p.name", {order: direction}); - } - - HystrixThreadPoolMonitor.prototype.sortByMetricInDirection = function(direction, metric) { - $('#' + this.containerId + ' div.monitor').tsort(metric, {order: direction}); - } - - // this method is for when new divs are added to cause the elements to be sorted to whatever the user last chose - HystrixThreadPoolMonitor.prototype.sortSameAsLast = function() { - if(this.sortedBy == 'alph_asc') { - this.sortAlphabeticalInDirection('asc'); - } else if(this.sortedBy == 'alph_desc') { - this.sortAlphabeticalInDirection('desc'); - } else if(this.sortedBy == 'rate_asc') { - this.sortByVolumeInDirection('asc'); - } else if(this.sortedBy == 'rate_desc') { - this.sortByVolumeInDirection('desc'); - } else if(this.sortedBy == 'error_asc') { - this.sortByErrorInDirection('asc'); - } else if(this.sortedBy == 'error_desc') { - this.sortByErrorInDirection('desc'); - } else if(this.sortedBy == 'lat90_asc') { - this.sortByMetricInDirection('asc', 'p90'); - } else if(this.sortedBy == 'lat90_desc') { - this.sortByMetricInDirection('desc', 'p90'); - } else if(this.sortedBy == 'lat99_asc') { - this.sortByMetricInDirection('asc', 'p99'); - } else if(this.sortedBy == 'lat99_desc') { - this.sortByMetricInDirection('desc', 'p99'); - } else if(this.sortedBy == 'lat995_asc') { - this.sortByMetricInDirection('asc', 'p995'); - } else if(this.sortedBy == 'lat995_desc') { - this.sortByMetricInDirection('desc', 'p995'); - } else if(this.sortedBy == 'latMean_asc') { - this.sortByMetricInDirection('asc', 'pMean'); - } else if(this.sortedBy == 'latMean_desc') { - this.sortByMetricInDirection('desc', 'pMean'); - } else if(this.sortedBy == 'latMedian_asc') { - this.sortByMetricInDirection('asc', 'pMedian'); - } else if(this.sortedBy == 'latMedian_desc') { - this.sortByMetricInDirection('desc', 'pMedian'); - } - } - - // default sort type and direction - this.sortedBy = 'alph_asc'; - - - // a temporary home for the logger until we become more sophisticated - function log(message) { - console.log(message); - }; - - function addCommas(nStr){ - nStr += ''; - if(nStr.length <=3) { - return nStr; //shortcut if we don't need commas - } - x = nStr.split('.'); - x1 = x[0]; - x2 = x.length > 1 ? '.' + x[1] : ''; - var rgx = /(\d+)(\d{3})/; - while (rgx.test(x1)) { - x1 = x1.replace(rgx, '$1' + ',' + '$2'); - } - return x1 + x2; - } -})(window) - - diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixThreadPool/templates/hystrixThreadPool.html b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixThreadPool/templates/hystrixThreadPool.html deleted file mode 100644 index 1e653ccb..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixThreadPool/templates/hystrixThreadPool.html +++ /dev/null @@ -1,33 +0,0 @@ - -
- - - - -
- -
-
Active
-
<%= currentActiveCount%>
- -
Max Active
-
<%= addCommas(rollingMaxActiveThreads)%>
-
- -
-
Queued
-
<%= currentQueueSize %>
-
Executions
-
<%= addCommas(rollingCountThreadsExecuted)%>
-
-
-
Pool Size
-
<%= currentPoolSize %>
-
Queue Size
-
<%= propertyValue_queueSizeRejectionThreshold %>
-
- \ No newline at end of file diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixThreadPool/templates/hystrixThreadPoolContainer.html b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixThreadPool/templates/hystrixThreadPoolContainer.html deleted file mode 100644 index 035ae845..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/components/hystrixThreadPool/templates/hystrixThreadPoolContainer.html +++ /dev/null @@ -1,34 +0,0 @@ -
- - <% - var displayName = name; - var toolTip = ""; - if(displayName.length > 32) { - displayName = displayName.substring(0,4) + "..." + displayName.substring(displayName.length-20, displayName.length); - toolTip = "title=\"" + name + "\""; - } - %> - -
-

><%= displayName %>

-
-
-
- - - - -
diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/global.css b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/global.css deleted file mode 100644 index 74e80d17..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/global.css +++ /dev/null @@ -1,71 +0,0 @@ -@IMPORT url("resets.css"); - -body { - font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; -} - -img, object, embed { - max-width: 100%; -} - -img { - height: auto; -} - - -#header { - background: #FFFFFF url(../images/hystrix-logo-tagline-tiny.png) no-repeat scroll 99% 0%; - height: 65px; - margin-bottom: 5px; -} - -#header h2 { - float:left; - color: black; - position:relative; - padding-left: 20px; - top: 26px; - font-size: 20px; - font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; -} - -#header .header_nav { - position:absolute; - top:48px; - right:15px; -} - -#header .header_links { - float:left; - color: lightgray; - font-size: 18px; - top: 3px; - padding-left: 10px; - font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; -} - -#header .header_links a { - color: white; -} - -#header .header_clusters { - float:left; - position:relative; - padding-left: 10px; - top: -1px; - font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; -} - - -@media screen and (min-width: 1500px) { - - #header .header_nav { - top:13px; - right:130px; - } - - #header { - background: #FFFFFF url(../images/hystrix-logo-tagline-tiny.png) no-repeat scroll 99% 50%; - height: 65px; - } -} diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/monitor.css b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/monitor.css deleted file mode 100644 index 04b929c2..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/monitor.css +++ /dev/null @@ -1,105 +0,0 @@ -.container { - padding-left: 20px; - padding-right: 20px; -} - -.row { - width: 100%; - margin: 0 auto; - overflow: hidden; -} - -.spacer { - width: 100%; - margin: 0 auto; - padding-top:4px; - clear:both; -} - - -.last { - margin-right: 0px; -} - -.menubar { - overflow: hidden; - border-bottom: 1px solid black; -} - -.menubar div { - padding-bottom:5px; - - margin: 0 auto; - overflow: hidden; - - font-size: 80%; - font-family:'Bookman Old Style',Bookman,'URW Bookman L','Palatino Linotype',serif; - - float:left; -} - -.menubar .title { - float: left; - padding-right: 20px; - - font-size: 110%; - font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; - font-weight: bold; - - vertical-align: bottom; -} - -.menubar .menu_actions { - float: left; - position:relative; - top: 4px; -} - -.menubar .menu_legend { - float: right; - position:relative; - top: 4px; - -} - -h3.sectionHeader { - color: black; - font-size: 110%; - padding-top: 4px; - padding-bottom: 4px; - padding-left: 8px; - font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; - background: lightgrey; -} - -.success { - color: green; -} -.shortCircuited { - color: blue; -} -.timeout { - color: #FF9900; /* shade of orange */ -} -.failure { - color: red; -} - -.rejected { - color: purple; -} - -.exceptionsThrown { - color: brown; -} - -.badRequest { - color: #00CC99; -} - -@media screen and (max-width: 1100px) { - .container { - padding-left: 5px; - padding-right: 5px; - } -} diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/resets.css b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/resets.css deleted file mode 100644 index 4d137c7e..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/resets.css +++ /dev/null @@ -1,102 +0,0 @@ -/* -html5doctor.com Reset Stylesheet -v1.6.1 -Last Updated: 2010-09-17 -Author: Richard Clark - http://richclarkdesign.com -Twitter: @rich_clark -*/ - -html, body, div, span, object, iframe, -h1, h2, h3, h4, h5, h6, p, blockquote, pre, -abbr, address, cite, code, -del, dfn, em, img, ins, kbd, q, samp, -small, strong, sub, sup, var, -b, i, -dl, dt, dd, ol, ul, li, -fieldset, form, label, legend, -table, caption, tbody, tfoot, thead, tr, th, td, -article, aside, canvas, details, figcaption, figure, -footer, header, hgroup, menu, nav, section, summary, -time, mark, audio, video { - margin:0; - padding:0; - border:0; - outline:0; - font-size:100%; - vertical-align:baseline; - background:transparent; -} - -body { - line-height:1; -} - -article,aside,details,figcaption,figure, -footer,header,hgroup,menu,nav,section { - display:block; -} - -nav ul { - list-style:none; -} - -blockquote, q { - quotes:none; -} - -blockquote:before, blockquote:after, -q:before, q:after { - content:''; - content:none; -} - -a { - margin:0; - padding:0; - font-size:100%; - vertical-align:baseline; - background:transparent; -} - -/* change colours to suit your needs */ -ins { - background-color:#ff9; - color:#000; - text-decoration:none; -} - -/* change colours to suit your needs */ -mark { - background-color:#ff9; - color:#000; - font-style:italic; - font-weight:bold; -} - -del { - text-decoration: line-through; -} - -abbr[title], dfn[title] { - border-bottom:1px dotted; - cursor:help; -} - -table { - border-collapse:collapse; - border-spacing:0; -} - -/* change border colour to suit your needs */ -hr { - display:block; - height:1px; - border:0; - border-top:1px solid #cccccc; - margin:1em 0; - padding:0; -} - -input, select { - vertical-align:middle; -} \ No newline at end of file diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/1236_grid.css b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/1236_grid.css deleted file mode 100644 index 052ee488..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/1236_grid.css +++ /dev/null @@ -1,21 +0,0 @@ -/* SimpleGrid - a fork of CSSGrid by Crowd Favorite (https://github.com/crowdfavorite/css-grid) - * http://simplegrid.info - * by Conor Muirhead (http://conor.cc) of Early LLC (http://earlymade.com) - * License: http://creativecommons.org/licenses/MIT/ */ - -/* Containers */ -body { font-size: 1.125em; } -.grid{ width:1206px; } - -/* 6-Col Grid Sizes */ -.slot-0,.slot-1,.slot-2,.slot-3,.slot-4,.slot-5{ width:176px; } /* Sixths */ -.slot-0-1,.slot-1-2,.slot-2-3,.slot-3-4,.slot-4-5{ width:382px; } /* Thirds */ -.slot-0-1-2-3,.slot-1-2-3-4,.slot-2-3-4-5{ width:794px; } /* Two-Thirds */ -.slot-0-1-2-3-4,.slot-1-2-3-4-5{ width:1000px; } /* Five-Sixths */ - -/* 4-Col Grid Sizes */ -.slot-6,.slot-7,.slot-8,.slot-9{ width:279px; } /* Quarters */ -.slot-6-7-8,.slot-7-8-9{ width:897px; } /* Three-Quarters */ - -/* 6-Col/4-Col Shared Grid Sizes */ -.slot-0-1-2,.slot-1-2-3,.slot-2-3-4,.slot-3-4-5, .slot-6-7,.slot-7-8,.slot-8-9{ width:588px; } /* Halves */ \ No newline at end of file diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/720_grid.css b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/720_grid.css deleted file mode 100644 index 0ef2432c..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/720_grid.css +++ /dev/null @@ -1,33 +0,0 @@ -/* SimpleGrid - a fork of CSSGrid by Crowd Favorite (https://github.com/crowdfavorite/css-grid) - * http://simplegrid.info - * by Conor Muirhead (http://conor.cc) of Early LLC (http://earlymade.com) - * License: http://creativecommons.org/licenses/MIT/ */ - -/* Containers */ -body { font-size: 0.875em; padding: 0; } -.grid{ margin:0 auto; padding: 0 10px; width:700px; } -.row{ clear:left; } - -/* Slots Setup */ -.slot-0,.slot-1,.slot-2,.slot-3,.slot-4,.slot-5,.slot-0-1,.slot-0-1-2,.slot-0-1-2-3,.slot-0-1-2-3-4,.slot-0-1-2-3-4-5,.slot-1-2,.slot-1-2-3,.slot-1-2-3-4,.slot-1-2-3-4-5,.slot-2-3,.slot-2-3-4,.slot-2-3-4-5,.slot-3-4,.slot-3-4-5,.slot-4-5,.slot-6,.slot-7,.slot-8,.slot-9,.slot-6-7,.slot-6-7-8,.slot-6-7-8-9,.slot-7-8,.slot-7-8-9,.slot-8-9{ display:inline; float:left; margin-left:20px; } - -/* 6-Col Grid Sizes */ -.slot-0,.slot-1,.slot-2,.slot-3,.slot-4,.slot-5{ width:100px; } /* Sixths */ -.slot-0-1,.slot-1-2,.slot-2-3,.slot-3-4,.slot-4-5{ width:220px; } /* Thirds */ -.slot-0-1-2-3,.slot-1-2-3-4,.slot-2-3-4-5{ width:460px; } /* Two-Thirds */ -.slot-0-1-2-3-4,.slot-1-2-3-4-5{ width:580px; } /* Five-Sixths */ - -/* 4-Col Grid Sizes */ -.slot-6,.slot-7,.slot-8,.slot-9{ width:160px; } /* Quarters */ -.slot-6-7-8,.slot-7-8-9{ width:520px; } /* Three-Quarters */ - -/* 6-Col/4-Col Shared Grid Sizes */ -.slot-0-1-2,.slot-1-2-3,.slot-2-3-4,.slot-3-4-5, .slot-6-7,.slot-7-8,.slot-8-9{ width:340px; } /* Halves */ -.slot-0-1-2-3-4-5, .slot-6-7-8-9{ width: 100%; } /* Full-Width */ - -/* Zeroing Out Leftmost Slot Margins */ -.slot-0,.slot-0-1,.slot-0-1-2,.slot-0-1-2-3,.slot-0-1-2-3-4,.slot-0-1-2-3-4-5,.slot-6,.slot-6-7,.slot-6-7-8,.slot-6-7-8-9,.slot-1 .slot-1,.slot-1-2 .slot-1,.slot-1-2 .slot-1-2,.slot-1-2-3 .slot-1,.slot-1-2-3 .slot-1-2,.slot-1-2-3 .slot-1-2-3,.slot-1-2-3-4 .slot-1,.slot-1-2-3-4 .slot-1-2,.slot-1-2-3-4 .slot-1-2-3,.slot-1-2-3-4 .slot-1-2-3-4,.slot-1-2-3-4-5 .slot-1,.slot-1-2-3-4-5 .slot-1-2,.slot-1-2-3-4-5 .slot-1-2-3,.slot-1-2-3-4-5 .slot-1-2-3-4,.slot-1-2-3-4-5 .slot-1-2-3-4-5,.slot-2 .slot-2,.slot-2-3 .slot-2,.slot-2-3 .slot-2-3,.slot-2-3-4 .slot-2,.slot-2-3-4 .slot-2-3,.slot-2-3-4 .slot-2-3-4,.slot-2-3-4-5 .slot-2,.slot-2-3-4-5 .slot-2-3,.slot-2-3-4-5 .slot-2-3-4,.slot-2-3-4-5 .slot-2-3-4-5,.slot-3 .slot-3,.slot-3-4 .slot-3,.slot-3-4 .slot-3-4,.slot-3-4-5 .slot-3,.slot-3-4-5 .slot-3-4,.slot-3-4-5 .slot-3-4-5,.slot-4 .slot-4,.slot-4-5 .slot-4,.slot-4-5 .slot-4-5,.slot-5 .slot-5,.slot-7 .slot-7,.slot-7-8 .slot-7,.slot-7-8 .slot-7-8,.slot-7-8-9 .slot-7,.slot-7-8-9 .slot-7-8,.slot-7-8-9 .slot-7-8-9,.slot-8 .slot-8,.slot-8-9 .slot-8,.slot-8-9 .slot-8-9{ margin-left:0 !important; } /* Important is to avoid repeating this in larger screen css files */ - -/* Row Clearfix */ -.row:after{ visibility:hidden; display:block; font-size:0; content:" "; clear:both; height:0; } -.row{ zoom:1; } \ No newline at end of file diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/986_grid.css b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/986_grid.css deleted file mode 100644 index 83a59788..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/986_grid.css +++ /dev/null @@ -1,24 +0,0 @@ -/* SimpleGrid - a fork of CSSGrid by Crowd Favorite (https://github.com/crowdfavorite/css-grid) - * http://simplegrid.info - * by Conor Muirhead (http://conor.cc) of Early LLC (http://earlymade.com) - * License: http://creativecommons.org/licenses/MIT/ */ - -/* Containers */ -body { font-size: 100%; } -.grid{ width:966px; } - -/* Slots Setup */ -.slot-0,.slot-1,.slot-2,.slot-3,.slot-4,.slot-5,.slot-0-1,.slot-0-1-2,.slot-0-1-2-3,.slot-0-1-2-3-4,.slot-0-1-2-3-4-5,.slot-1-2,.slot-1-2-3,.slot-1-2-3-4,.slot-1-2-3-4-5,.slot-2-3,.slot-2-3-4,.slot-2-3-4-5,.slot-3-4,.slot-3-4-5,.slot-4-5,.slot-6,.slot-7,.slot-8,.slot-9,.slot-6-7,.slot-6-7-8,.slot-6-7-8-9,.slot-7-8,.slot-7-8-9,.slot-8-9{ display:inline; float:left; margin-left:30px; } - -/* 6-Col Grid Sizes */ -.slot-0,.slot-1,.slot-2,.slot-3,.slot-4,.slot-5{ width:136px; } /* Sixths */ -.slot-0-1,.slot-1-2,.slot-2-3,.slot-3-4,.slot-4-5{ width:302px; } /* Thirds */ -.slot-0-1-2-3,.slot-1-2-3-4,.slot-2-3-4-5{ width:634px; } /* Two-Thirds */ -.slot-0-1-2-3-4,.slot-1-2-3-4-5{ width:800px; } /* Five-Sixths */ - -/* 4-Col Grid Sizes */ -.slot-6,.slot-7,.slot-8,.slot-9{ width:219px; } /* Quarters */ -.slot-6-7-8,.slot-7-8-9{ width:717px; } /* Three-Quarters */ - -/* 6-Col/4-Col Shared Grid Sizes */ -.slot-0-1-2,.slot-1-2-3,.slot-2-3-4,.slot-3-4-5, .slot-6-7,.slot-7-8,.slot-8-9{ width:468px; } /* Halves */ \ No newline at end of file diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/LICENSE.txt b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/LICENSE.txt deleted file mode 100644 index e942914a..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/LICENSE.txt +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2011 Crowd Favorite, Ltd. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/README.txt b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/README.txt deleted file mode 100644 index 15cfc8c3..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/README.txt +++ /dev/null @@ -1 +0,0 @@ -http://simplegrid.info/ \ No newline at end of file diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/percentage_grid.css b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/percentage_grid.css deleted file mode 100644 index 13cb4b2d..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/css/simplegrid/percentage_grid.css +++ /dev/null @@ -1,27 +0,0 @@ -/* Extension of SimpleGrid by benjchristensen to allow percentage based sizing on very large displays - * - * SimpleGrid - a fork of CSSGrid by Crowd Favorite (https://github.com/crowdfavorite/css-grid) - * http://simplegrid.info - * by Conor Muirhead (http://conor.cc) of Early LLC (http://earlymade.com) - * License: http://creativecommons.org/licenses/MIT/ */ - -/* Containers */ -body { font-size: 1.125em; } -.grid{ width:100%; } - -/* Slots Setup */ -.slot-0,.slot-1,.slot-2,.slot-3,.slot-4,.slot-5,.slot-0-1,.slot-0-1-2,.slot-0-1-2-3,.slot-0-1-2-3-4,.slot-0-1-2-3-4-5,.slot-1-2,.slot-1-2-3,.slot-1-2-3-4,.slot-1-2-3-4-5,.slot-2-3,.slot-2-3-4,.slot-2-3-4-5,.slot-3-4,.slot-3-4-5,.slot-4-5,.slot-6,.slot-7,.slot-8,.slot-9,.slot-6-7,.slot-6-7-8,.slot-6-7-8-9,.slot-7-8,.slot-7-8-9,.slot-8-9{ display:inline; float:left; margin-left:0px; } - - -/* 6-Col Grid Sizes */ -.slot-0,.slot-1,.slot-2,.slot-3,.slot-4,.slot-5{ width:16.6%; } /* Sixths */ -.slot-0-1,.slot-1-2,.slot-2-3,.slot-3-4,.slot-4-5{ width:33.3%; } /* Thirds */ -.slot-0-1-2-3,.slot-1-2-3-4,.slot-2-3-4-5{ width:66.6%; } /* Two-Thirds */ -.slot-0-1-2-3-4,.slot-1-2-3-4-5{ width:83.3%; } /* Five-Sixths */ - -/* 4-Col Grid Sizes */ -.slot-6,.slot-7,.slot-8,.slot-9{ width:25%; } /* Quarters */ -.slot-6-7-8,.slot-7-8-9{ width:75%; } /* Three-Quarters */ - -/* 6-Col/4-Col Shared Grid Sizes */ -.slot-0-1-2,.slot-1-2-3,.slot-2-3-4,.slot-3-4-5, .slot-6-7,.slot-7-8,.slot-8-9{ width:50%; } /* Halves */ \ No newline at end of file diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/images/hystrix-logo-tagline-tiny.png b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/images/hystrix-logo-tagline-tiny.png deleted file mode 100644 index 8919c292..00000000 Binary files a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/images/hystrix-logo-tagline-tiny.png and /dev/null differ diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/images/hystrix-logo.png b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/images/hystrix-logo.png deleted file mode 100644 index 694a9c9c..00000000 Binary files a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/images/hystrix-logo.png and /dev/null differ diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/js/jquery.tinysort.min.js b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/js/jquery.tinysort.min.js deleted file mode 100644 index 40d62eb5..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/js/jquery.tinysort.min.js +++ /dev/null @@ -1,12 +0,0 @@ -/* -* jQuery TinySort - A plugin to sort child nodes by (sub) contents or attributes. -* -* Version: 1.0.5 -* -* Copyright (c) 2008-2011 Ron Valstar http://www.sjeiti.com/ -* -* Dual licensed under the MIT and GPL licenses: -* http://www.opensource.org/licenses/mit-license.php -* http://www.gnu.org/licenses/gpl.html -*/ -(function(b){b.tinysort={id:"TinySort",version:"1.0.5",copyright:"Copyright (c) 2008-2011 Ron Valstar",uri:"http://tinysort.sjeiti.com/",defaults:{order:"asc",attr:"",place:"start",returns:false,useVal:false}};b.fn.extend({tinysort:function(h,j){if(h&&typeof(h)!="string"){j=h;h=null}var e=b.extend({},b.tinysort.defaults,j);var p={};this.each(function(t){var v=(!h||h=="")?b(this):b(this).find(h);var u=e.order=="rand"?""+Math.random():(e.attr==""?(e.useVal?v.val():v.text()):v.attr(e.attr));var s=b(this).parent();if(!p[s]){p[s]={s:[],n:[]}}if(v.length>0){p[s].s.push({s:u,e:b(this),n:t})}else{p[s].n.push({e:b(this),n:t})}});for(var g in p){var d=p[g];d.s.sort(function k(t,s){var i=t.s.toLowerCase?t.s.toLowerCase():t.s;var u=s.s.toLowerCase?s.s.toLowerCase():s.s;if(c(t.s)&&c(s.s)){i=parseFloat(t.s);u=parseFloat(s.s)}return(e.order=="asc"?1:-1)*(iu?1:0))})}var m=[];for(var g in p){var d=p[g];var n=[];var f=b(this).length;switch(e.place){case"first":b.each(d.s,function(s,t){f=Math.min(f,t.n)});break;case"org":b.each(d.s,function(s,t){n.push(t.n)});break;case"end":f=d.n.length;break;default:f=0}var q=[0,0];for(var l=0;l=f&&l0?d[1]:false}function a(e,f){var d=false;b.each(e,function(h,g){if(!d){d=g==f}});return d}b.fn.TinySort=b.fn.Tinysort=b.fn.tsort=b.fn.tinysort})(jQuery); \ No newline at end of file diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/js/tmpl.js b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/js/tmpl.js deleted file mode 100644 index d7098f78..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/static/hystrix/js/tmpl.js +++ /dev/null @@ -1,43 +0,0 @@ - -//Simple JavaScript Templating -//John Resig - http://ejohn.org/ - MIT Licensed -// http://ejohn.org/blog/javascript-micro-templating/ -(function(window, undefined) { - var cache = {}; - - window.tmpl = function tmpl(str, data) { - try { - // Figure out if we're getting a template, or if we need to - // load the template - and be sure to cache the result. - var fn = !/\W/.test(str) ? - cache[str] = cache[str] || - tmpl(document.getElementById(str).innerHTML) : - - // Generate a reusable function that will serve as a template - // generator (and which will be cached). - new Function("obj", - "var p=[],print=function(){p.push.apply(p,arguments);};" + - - // Introduce the data as local variables using with(){} - "with(obj){p.push('" + - - // Convert the template into pure JavaScript - str - .replace(/[\r\t\n]/g, " ") - .split("<%").join("\t") - .replace(/((^|%>)[^\t]*)'/g, "$1\r") - .replace(/\t=(.*?)%>/g, "',$1,'") - .split("\t").join("');") - .split("%>").join("p.push('") - .split("\r").join("\\'") - + "');}return p.join('');"); - - //console.log(fn); - - // Provide some basic currying to the user - return data ? fn(data) : fn; - }catch(e) { - console.log(e); - } - }; -})(window); diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/templates/hystrix/index.ftl b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/templates/hystrix/index.ftl deleted file mode 100644 index 864dfe79..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/templates/hystrix/index.ftl +++ /dev/null @@ -1,58 +0,0 @@ -<#import "/spring.ftl" as spring /> - - - - - -Hystrix Dashboard - - - - - - - -
- -
- -
-
- -

Hystrix Dashboard

- -

- Cluster via Turbine (default cluster): http://turbine-hostname:port/turbine.stream -
- Cluster via Turbine (custom cluster): http://turbine-hostname:port/turbine.stream?cluster=[clusterName] -
- Single Hystrix App: http://hystrix-app:port/hystrix.stream -

- Delay: ms -      - Title:
-
- -

-
- -
-
- - \ No newline at end of file diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/templates/hystrix/monitor.ftl b/spring-cloud-netflix-hystrix-dashboard/src/main/resources/templates/hystrix/monitor.ftl deleted file mode 100644 index b4f3edb0..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/resources/templates/hystrix/monitor.ftl +++ /dev/null @@ -1,202 +0,0 @@ -<#import "/spring.ftl" as spring /> - - - - - - Hystrix Monitor - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- -
-
Loading ...
- -
- -
- -
-
Loading ...
-
- - - - - - - - diff --git a/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardConfigurationTests.java b/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardConfigurationTests.java deleted file mode 100644 index 33d8a644..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardConfigurationTests.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.dashboard; - -import java.util.Map; - -import org.apache.http.Header; -import org.apache.http.message.BasicHeader; -import org.junit.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.boot.web.servlet.ServletRegistrationBean; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.test.util.ReflectionTestUtils; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; - -/** - * @author Roy Clarkson - * @author Fahim Farook - * @author Biju Kunjummen - */ -public class HystrixDashboardConfigurationTests { - - @Test - public void normal() { - MockHttpServletResponse response = new MockHttpServletResponse(); - Header[] headers = new Header[1]; - headers[0] = new BasicHeader("Content-Type", "text/proxy.stream"); - HystrixDashboardConfiguration.ProxyStreamServlet proxyStreamServlet = new HystrixDashboardConfiguration.ProxyStreamServlet(); - ReflectionTestUtils.invokeMethod(proxyStreamServlet, - "copyHeadersToServletResponse", headers, response); - assertThat(response.getHeaderNames().size(), is(1)); - assertThat(response.getHeader("Content-Type"), is("text/proxy.stream")); - } - - @Test - public void connectionClose() { - MockHttpServletResponse response = new MockHttpServletResponse(); - Header[] headers = new Header[2]; - headers[0] = new BasicHeader("Content-Type", "text/proxy.stream"); - headers[1] = new BasicHeader("Connection", "close"); - HystrixDashboardConfiguration.ProxyStreamServlet proxyStreamServlet = new HystrixDashboardConfiguration.ProxyStreamServlet(); - ReflectionTestUtils.invokeMethod(proxyStreamServlet, - "copyHeadersToServletResponse", headers, response); - assertThat(response.getHeaderNames().size(), is(2)); - assertThat(response.getHeader("Content-Type"), is("text/proxy.stream")); - assertThat(response.getHeader("Connection"), is("close")); - } - - @Test - public void ignoreConnectionClose() { - MockHttpServletResponse response = new MockHttpServletResponse(); - Header[] headers = new Header[2]; - headers[0] = new BasicHeader("Content-Type", "text/proxy.stream"); - headers[1] = new BasicHeader("Connection", "close"); - HystrixDashboardConfiguration.ProxyStreamServlet proxyStreamServlet = new HystrixDashboardConfiguration.ProxyStreamServlet(); - proxyStreamServlet.setEnableIgnoreConnectionCloseHeader(true); - ReflectionTestUtils.invokeMethod(proxyStreamServlet, - "copyHeadersToServletResponse", headers, response); - assertThat(response.getHeaderNames().size(), is(1)); - assertThat(response.getHeader("Content-Type"), is("text/proxy.stream")); - assertNull(response.getHeader("Connection")); - } - - @Test - public void doNotIgnoreConnectionClose() { - MockHttpServletResponse response = new MockHttpServletResponse(); - Header[] headers = new Header[2]; - headers[0] = new BasicHeader("Content-Type", "text/proxy.stream"); - headers[1] = new BasicHeader("Connection", "close"); - HystrixDashboardConfiguration.ProxyStreamServlet proxyStreamServlet = new HystrixDashboardConfiguration.ProxyStreamServlet(); - proxyStreamServlet.setEnableIgnoreConnectionCloseHeader(false); - ReflectionTestUtils.invokeMethod(proxyStreamServlet, - "copyHeadersToServletResponse", headers, response); - assertThat(response.getHeaderNames().size(), is(2)); - assertThat(response.getHeader("Content-Type"), is("text/proxy.stream")); - assertThat(response.getHeader("Connection"), is("close")); - } - - @Test - public void initParameters() { - new ApplicationContextRunner() - .withUserConfiguration(HystrixDashboardConfiguration.class) - .withPropertyValues( - "hystrix.dashboard.init-parameters.wl-dispatch-polixy=work-manager-hystrix") - .run(context -> { - final ServletRegistrationBean registration = context - .getBean(ServletRegistrationBean.class); - assertNotNull(registration); - - final Map initParameters = registration - .getInitParameters(); - assertNotNull(initParameters); - assertThat(initParameters.get("wl-dispatch-polixy"), - is("work-manager-hystrix")); - }); - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardContextTests.java b/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardContextTests.java deleted file mode 100644 index fe8724d6..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardContextTests.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.hystrix.dashboard; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.netflix.hystrix.dashboard.HystrixDashboardContextTests.Application; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * @author Dave Syer - * - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "spring.application.name=hystrix-dashboard", - "server.servlet.context-path=/context" }) -public class HystrixDashboardContextTests { - - public static final String JQUERY_PATH = "/context/webjars/jquery/2.1.1/jquery.min.js"; - @LocalServerPort - private int port = 0; - - @Test - public void homePage() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/context/hystrix", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - String body = entity.getBody(); - assertTrue("wrong base path rendered in template", - body.contains("base href=\"/context/hystrix\"")); - } - - @Test - public void correctJavascriptLink() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/context/hystrix", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - String body = entity.getBody(); - assertTrue("wrong jquery path rendered in template", - body.contains("src=\""+JQUERY_PATH+"\"")); - } - - @Test - public void cssAvailable() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/context/hystrix/css/global.css", - String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Test - public void webjarsAvailable() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + JQUERY_PATH, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Test - public void monitorPage() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/context/hystrix/monitor", - String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - String body = entity.getBody(); - assertTrue("wrong base path rendered in template", - body.contains("base href=\"/context/hystrix/monitor\"")); - } - - @Configuration - @EnableAutoConfiguration - @EnableHystrixDashboard - protected static class Application { - } - -} diff --git a/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardHomePageTests.java b/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardHomePageTests.java deleted file mode 100644 index 5e6c38b8..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardHomePageTests.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.dashboard; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.cloud.netflix.hystrix.dashboard.HystrixDashboardHomePageTests.Application; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.bind.annotation.RequestMapping; - -import static org.junit.Assert.assertEquals; - -/** - * @author Dave Syer - * - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { - "server.port=0", "spring.application.name=hystrix-dashboard" }) -public class HystrixDashboardHomePageTests { - - @Value("${local.server.port}") - private int port = 0; - - @Test - public void homePage() { - ResponseEntity entity = new TestRestTemplate() - .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - entity.getBody().contains(""); - } - - @Test - public void cssAvailable() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/hystrix/css/global.css", - String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Test - public void monitorPage() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/hystrix/monitor", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Configuration - @EnableAutoConfiguration - @EnableHystrixDashboard - @Controller - protected static class Application { - - @RequestMapping("/") - public String home() { - return "forward:/hystrix"; - } - - } - -} diff --git a/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardTests.java b/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardTests.java deleted file mode 100644 index c1f00302..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardTests.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.dashboard; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.cloud.netflix.hystrix.dashboard.HystrixDashboardTests.Application; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * @author Dave Syer - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { - "spring.application.name=hystrix-dashboard" }) -public class HystrixDashboardTests { - - @Value("${local.server.port}") - private int port = 0; - - @Test - public void homePage() { - ResponseEntity entity = new TestRestTemplate() - .getForEntity("http://localhost:" + this.port + "/hystrix", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - String body = entity.getBody(); - assertTrue(body.contains("")); - assertTrue(body.contains("\"/webjars")); - assertTrue(body.contains("= \"/hystrix/monitor")); - } - - @Test - public void cssAvailable() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/hystrix/css/global.css", - String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - } - - @Test - public void monitorPage() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/hystrix/monitor", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - String body = entity.getBody(); - assertTrue(body.contains("")); - } - - @Configuration - @EnableAutoConfiguration - @EnableHystrixDashboard - protected static class Application { - } - -} diff --git a/spring-cloud-netflix-hystrix-dashboard/src/test/resources/templates/test.txt b/spring-cloud-netflix-hystrix-dashboard/src/test/resources/templates/test.txt deleted file mode 100644 index 69d32d57..00000000 --- a/spring-cloud-netflix-hystrix-dashboard/src/test/resources/templates/test.txt +++ /dev/null @@ -1 +0,0 @@ -The presence of this templates directory tests the Spring Boot FreeMarker configuration \ No newline at end of file diff --git a/spring-cloud-netflix-hystrix-stream/pom.xml b/spring-cloud-netflix-hystrix-stream/pom.xml deleted file mode 100644 index 5d6d4d31..00000000 --- a/spring-cloud-netflix-hystrix-stream/pom.xml +++ /dev/null @@ -1,150 +0,0 @@ - - - 4.0.0 - - org.springframework.cloud - spring-cloud-netflix - 2.0.0.BUILD-SNAPSHOT - .. - - spring-cloud-netflix-hystrix-stream - jar - Spring Cloud Netflix Hystrix Stream - Spring Cloud Netflix Hystrix Stream - - ${basedir}/.. - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework.boot - spring-boot-starter-logging - - - org.springframework.cloud - spring-cloud-commons - - - org.springframework.cloud - spring-cloud-netflix-core - - - org.springframework.cloud - spring-cloud-stream - - - com.fasterxml.jackson.core - jackson-databind - - - com.netflix.hystrix - hystrix-core - - - com.netflix.hystrix - hystrix-metrics-event-stream - test - - - com.netflix.hystrix - hystrix-javanica - test - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.boot - spring-boot-starter-web - test - - - org.springframework.boot - spring-boot-starter-actuator - test - - - org.springframework.cloud - spring-cloud-stream-test-support - test - - - org.springframework.cloud - spring-cloud-netflix-hystrix-contract - test - - - org.springframework.cloud - spring-cloud-contract-verifier - test - - - org.springframework.cloud - spring-cloud-starter-netflix-eureka-client - test - - - - - - org.springframework.cloud - spring-cloud-contract-maven-plugin - ${donotreplacespring-cloud-contract.version} - true - - - - .* - org.springframework.cloud.netflix.hystrix.stream.StreamSourceTestBase - - - - - - org.springframework.cloud - spring-cloud-netflix-hystrix-contract - ${project.version} - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.springframework.cloud - spring-cloud-contract-maven-plugin - [1.0.0.RELEASE,) - - convert - generateTests - - - - - - - - - - - - - - diff --git a/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfiguration.java b/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfiguration.java deleted file mode 100644 index 2bca33d1..00000000 --- a/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfiguration.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.stream; - -import javax.annotation.PostConstruct; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.actuator.HasFeatures; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClient; -import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryProperties; -import org.springframework.cloud.client.serviceregistry.Registration; -import org.springframework.cloud.stream.annotation.EnableBinding; -import org.springframework.cloud.stream.annotation.Output; -import org.springframework.cloud.stream.config.BindingProperties; -import org.springframework.cloud.stream.config.BindingServiceProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.messaging.MessageChannel; -import org.springframework.scheduling.annotation.EnableScheduling; - -import com.netflix.hystrix.HystrixCircuitBreaker; - -/** - * Autoconfiguration for a Spring Cloud Hystrix on Spring Cloud Stream. Enabled by default - * if spring-cloud-stream is on the classpath, and can be switched off with - * hystrix.stream.queue.enabled. There are some high level configuration - * options in {@link HystrixStreamProperties}. The binding name for Spring Cloud Stream is - * {@link HystrixStreamClient#OUTPUT} so you can configure stream other properties through - * that. - * - * @author Spencer Gibb - * @author Dave Syer - */ -@Configuration -@ConditionalOnClass({ HystrixCircuitBreaker.class, EnableBinding.class }) -@ConditionalOnProperty(value = "hystrix.stream.queue.enabled", matchIfMissing = true) -@EnableConfigurationProperties -@EnableScheduling -@EnableBinding(HystrixStreamClient.class) -public class HystrixStreamAutoConfiguration { - - @Autowired - private BindingServiceProperties bindings; - - @Autowired - private HystrixStreamProperties properties; - - @Autowired - @Output(HystrixStreamClient.OUTPUT) - private MessageChannel outboundChannel; - - @Autowired(required = false) - private Registration registration; - - @Bean - public HasFeatures hystrixStreamQueueFeature() { - return HasFeatures.namedFeature("Hystrix Stream (Queue)", - HystrixStreamAutoConfiguration.class); - } - - @PostConstruct - public void init() { - BindingProperties outputBinding = this.bindings.getBindings() - .get(HystrixStreamClient.OUTPUT); - if (outputBinding == null) { - this.bindings.getBindings().put(HystrixStreamClient.OUTPUT, - new BindingProperties()); - } - BindingProperties output = this.bindings.getBindings() - .get(HystrixStreamClient.OUTPUT); - if (output.getDestination() == null) { - output.setDestination(this.properties.getDestination()); - } - if (output.getContentType() == null) { - output.setContentType(this.properties.getContentType()); - } - } - - @Bean - public HystrixStreamProperties hystrixStreamProperties() { - return new HystrixStreamProperties(); - } - - @Bean - public HystrixStreamTask hystrixStreamTask(SimpleDiscoveryProperties simpleDiscoveryProperties) { - ServiceInstance serviceInstance = this.registration; - if (serviceInstance == null) { - serviceInstance = simpleDiscoveryProperties.getLocal(); - } - return new HystrixStreamTask(this.outboundChannel, serviceInstance, - this.properties); - } - -} diff --git a/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamClient.java b/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamClient.java deleted file mode 100644 index 107053fb..00000000 --- a/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamClient.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.stream; - -import org.springframework.cloud.stream.annotation.Output; -import org.springframework.messaging.MessageChannel; - -/** - * @author Dave Syer - * - */ -public interface HystrixStreamClient { - - String OUTPUT = "hystrixStreamOutput"; - - @Output(OUTPUT) - MessageChannel hystrixStreamOutput(); -} diff --git a/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamProperties.java b/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamProperties.java deleted file mode 100644 index 86db29d8..00000000 --- a/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamProperties.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.stream; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.cloud.netflix.hystrix.HystrixConstants; - -/** - * @author Spencer Gibb - */ -@ConfigurationProperties("hystrix.stream.queue") -public class HystrixStreamProperties { - - /** Flag to indicate that Hystrix Stream is enabled. Default is true. */ - private boolean enabled = true; - - /** Flag to indicate to prefix metric names with serviceId. Default is true. */ - private boolean prefixMetricName = true; - - /** Flag to indicate to send the id field in the metrics. Default is true */ - private boolean sendId = true; - - /** The destination of the stream. Destination as defined by Spring Cloud Stream. Defaults to springCloudHystrixStream */ - private String destination = HystrixConstants.HYSTRIX_STREAM_DESTINATION; - - /** The content type of the messages. Defaults to application/json */ - private String contentType = "application/json"; - - /** How often (in ms) to send messages to the stream. Defaults to 500. */ - private long sendRate = 500; - - /** How often to put messages in the queue. This queue drains to the stream. Defaults to 500. */ - private long gatherRate = 500; - - /** The size of the metrics queue. This queue drains to the stream. Defaults to 1000. */ - private int size = 1000; - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public boolean isPrefixMetricName() { - return prefixMetricName; - } - - public void setPrefixMetricName(boolean prefixMetricName) { - this.prefixMetricName = prefixMetricName; - } - - public boolean isSendId() { - return sendId; - } - - public void setSendId(boolean sendId) { - this.sendId = sendId; - } - - public String getDestination() { - return destination; - } - - public void setDestination(String destination) { - this.destination = destination; - } - - public String getContentType() { - return contentType; - } - - public void setContentType(String contentType) { - this.contentType = contentType; - } - - public long getSendRate() { - return sendRate; - } - - public void setSendRate(long sendRate) { - this.sendRate = sendRate; - } - - public long getGatherRate() { - return gatherRate; - } - - public void setGatherRate(long gatherRate) { - this.gatherRate = gatherRate; - } - - public int getSize() { - return size; - } - - public void setSize(int size) { - this.size = size; - } - -} diff --git a/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTask.java b/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTask.java deleted file mode 100644 index 28f14aff..00000000 --- a/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTask.java +++ /dev/null @@ -1,393 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.stream; - -import java.io.IOException; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Collection; -import java.util.concurrent.LinkedBlockingQueue; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.BeansException; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.messaging.MessageChannel; -import org.springframework.messaging.MessageHeaders; -import org.springframework.messaging.support.MessageBuilder; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.util.Assert; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonGenerator; -import com.netflix.hystrix.HystrixCircuitBreaker; -import com.netflix.hystrix.HystrixCommandKey; -import com.netflix.hystrix.HystrixCommandMetrics; -import com.netflix.hystrix.HystrixCommandProperties; -import com.netflix.hystrix.HystrixThreadPoolKey; -import com.netflix.hystrix.HystrixThreadPoolMetrics; -import com.netflix.hystrix.util.HystrixRollingNumberEvent; - -/** - * @author Spencer Gibb - * - * @see com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsPoller (nested - * private class MetricsPoller) - */ -public class HystrixStreamTask implements ApplicationContextAware { - - private static Log log = LogFactory.getLog(HystrixStreamTask.class); - - private MessageChannel outboundChannel; - - private ServiceInstance registration; - - private HystrixStreamProperties properties; - - private ApplicationContext context; - - // Visible for testing - final LinkedBlockingQueue jsonMetrics; - - private final JsonFactory jsonFactory = new JsonFactory(); - - public HystrixStreamTask(MessageChannel outboundChannel, - ServiceInstance registration, HystrixStreamProperties properties) { - Assert.notNull(outboundChannel, "outboundChannel may not be null"); - Assert.notNull(registration, "registration may not be null"); - Assert.notNull(properties, "properties may not be null"); - this.outboundChannel = outboundChannel; - this.registration = registration; - this.properties = properties; - this.jsonMetrics = new LinkedBlockingQueue<>(properties.getSize()); - } - - /* for testing */ ServiceInstance getRegistration() { - return registration; - } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { - this.context = applicationContext; - } - - // TODO: use integration to split this up? - @Scheduled(fixedRateString = "${hystrix.stream.queue.sendRate:500}") - public void sendMetrics() { - ArrayList metrics = new ArrayList<>(); - this.jsonMetrics.drainTo(metrics); - - if (!metrics.isEmpty()) { - if (log.isTraceEnabled()) { - log.trace("sending stream metrics size: " + metrics.size()); - } - for (String json : metrics) { - // TODO: batch all metrics to one message - try { - // TODO: remove the explicit content type when s-c-stream can handle - // that for us - this.outboundChannel.send(MessageBuilder.withPayload(json) - .setHeader(MessageHeaders.CONTENT_TYPE, - this.properties.getContentType()) - .build()); - } - catch (Exception ex) { - if (log.isTraceEnabled()) { - log.trace("failed sending stream metrics: " + ex.getMessage()); - } - } - } - } - } - - @Scheduled(fixedRateString = "${hystrix.stream.queue.gatherRate:500}") - public void gatherMetrics() { - try { - // command metrics - Collection instances = HystrixCommandMetrics - .getInstances(); - if (!instances.isEmpty()) { - log.trace("gathering metrics size: " + instances.size()); - } - - for (HystrixCommandMetrics commandMetrics : instances) { - HystrixCommandKey key = commandMetrics.getCommandKey(); - HystrixCircuitBreaker circuitBreaker = HystrixCircuitBreaker.Factory - .getInstance(key); - - StringWriter jsonString = new StringWriter(); - JsonGenerator json = this.jsonFactory.createGenerator(jsonString); - - json.writeStartObject(); - - addServiceData(json, registration); - json.writeStringField("event", "message"); - json.writeObjectFieldStart("data"); - json.writeStringField("type", "HystrixCommand"); - String name = key.name(); - - if (this.properties.isPrefixMetricName() && registration != null) { - name = registration.getServiceId() + "." + name; - } - - json.writeStringField("name", name); - json.writeStringField("group", commandMetrics.getCommandGroup().name()); - json.writeNumberField("currentTime", System.currentTimeMillis()); - - // circuit breaker - if (circuitBreaker == null) { - // circuit breaker is disabled and thus never open - json.writeBooleanField("isCircuitBreakerOpen", false); - } - else { - json.writeBooleanField("isCircuitBreakerOpen", - circuitBreaker.isOpen()); - } - HystrixCommandMetrics.HealthCounts healthCounts = commandMetrics - .getHealthCounts(); - json.writeNumberField("errorPercentage", - healthCounts.getErrorPercentage()); - json.writeNumberField("errorCount", healthCounts.getErrorCount()); - json.writeNumberField("requestCount", healthCounts.getTotalRequests()); - - // rolling counters - json.writeNumberField("rollingCountCollapsedRequests", commandMetrics - .getRollingCount(HystrixRollingNumberEvent.COLLAPSED)); - json.writeNumberField("rollingCountExceptionsThrown", commandMetrics - .getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); - json.writeNumberField("rollingCountFailure", commandMetrics - .getRollingCount(HystrixRollingNumberEvent.FAILURE)); - json.writeNumberField("rollingCountFallbackFailure", commandMetrics - .getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); - json.writeNumberField("rollingCountFallbackRejection", commandMetrics - .getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); - json.writeNumberField("rollingCountFallbackSuccess", commandMetrics - .getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); - json.writeNumberField("rollingCountResponsesFromCache", commandMetrics - .getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); - json.writeNumberField("rollingCountSemaphoreRejected", commandMetrics - .getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); - json.writeNumberField("rollingCountShortCircuited", commandMetrics - .getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); - json.writeNumberField("rollingCountSuccess", commandMetrics - .getRollingCount(HystrixRollingNumberEvent.SUCCESS)); - json.writeNumberField("rollingCountThreadPoolRejected", commandMetrics - .getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); - json.writeNumberField("rollingCountTimeout", commandMetrics - .getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); - - json.writeNumberField("currentConcurrentExecutionCount", - commandMetrics.getCurrentConcurrentExecutionCount()); - - // latency percentiles - json.writeNumberField("latencyExecute_mean", - commandMetrics.getExecutionTimeMean()); - json.writeObjectFieldStart("latencyExecute"); - json.writeNumberField("0", commandMetrics.getExecutionTimePercentile(0)); - json.writeNumberField("25", - commandMetrics.getExecutionTimePercentile(25)); - json.writeNumberField("50", - commandMetrics.getExecutionTimePercentile(50)); - json.writeNumberField("75", - commandMetrics.getExecutionTimePercentile(75)); - json.writeNumberField("90", - commandMetrics.getExecutionTimePercentile(90)); - json.writeNumberField("95", - commandMetrics.getExecutionTimePercentile(95)); - json.writeNumberField("99", - commandMetrics.getExecutionTimePercentile(99)); - json.writeNumberField("99.5", - commandMetrics.getExecutionTimePercentile(99.5)); - json.writeNumberField("100", - commandMetrics.getExecutionTimePercentile(100)); - json.writeEndObject(); - // - json.writeNumberField("latencyTotal_mean", - commandMetrics.getTotalTimeMean()); - json.writeObjectFieldStart("latencyTotal"); - json.writeNumberField("0", commandMetrics.getTotalTimePercentile(0)); - json.writeNumberField("25", commandMetrics.getTotalTimePercentile(25)); - json.writeNumberField("50", commandMetrics.getTotalTimePercentile(50)); - json.writeNumberField("75", commandMetrics.getTotalTimePercentile(75)); - json.writeNumberField("90", commandMetrics.getTotalTimePercentile(90)); - json.writeNumberField("95", commandMetrics.getTotalTimePercentile(95)); - json.writeNumberField("99", commandMetrics.getTotalTimePercentile(99)); - json.writeNumberField("99.5", - commandMetrics.getTotalTimePercentile(99.5)); - json.writeNumberField("100", commandMetrics.getTotalTimePercentile(100)); - json.writeEndObject(); - - // property values for reporting what is actually seen by the command - // rather than what was set somewhere - HystrixCommandProperties commandProperties = commandMetrics - .getProperties(); - - json.writeNumberField( - "propertyValue_circuitBreakerRequestVolumeThreshold", - commandProperties.circuitBreakerRequestVolumeThreshold().get()); - json.writeNumberField( - "propertyValue_circuitBreakerSleepWindowInMilliseconds", - commandProperties.circuitBreakerSleepWindowInMilliseconds() - .get()); - json.writeNumberField( - "propertyValue_circuitBreakerErrorThresholdPercentage", - commandProperties.circuitBreakerErrorThresholdPercentage().get()); - json.writeBooleanField("propertyValue_circuitBreakerForceOpen", - commandProperties.circuitBreakerForceOpen().get()); - json.writeBooleanField("propertyValue_circuitBreakerForceClosed", - commandProperties.circuitBreakerForceClosed().get()); - json.writeBooleanField("propertyValue_circuitBreakerEnabled", - commandProperties.circuitBreakerEnabled().get()); - - json.writeStringField("propertyValue_executionIsolationStrategy", - commandProperties.executionIsolationStrategy().get().name()); - json.writeNumberField( - "propertyValue_executionIsolationThreadTimeoutInMilliseconds", - commandProperties.executionIsolationThreadTimeoutInMilliseconds() - .get()); - json.writeBooleanField( - "propertyValue_executionIsolationThreadInterruptOnTimeout", - commandProperties.executionIsolationThreadInterruptOnTimeout() - .get()); - json.writeStringField( - "propertyValue_executionIsolationThreadPoolKeyOverride", - commandProperties.executionIsolationThreadPoolKeyOverride() - .get()); - json.writeNumberField( - "propertyValue_executionIsolationSemaphoreMaxConcurrentRequests", - commandProperties - .executionIsolationSemaphoreMaxConcurrentRequests() - .get()); - json.writeNumberField( - "propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests", - commandProperties - .fallbackIsolationSemaphoreMaxConcurrentRequests().get()); - - // TODO - /* - * The following are commented out as these rarely change and are verbose - * for streaming for something people don't change. We could perhaps allow - * a property or request argument to include these. - */ - - // json.put("propertyValue_metricsRollingPercentileEnabled", - // commandProperties.metricsRollingPercentileEnabled().get()); - // json.put("propertyValue_metricsRollingPercentileBucketSize", - // commandProperties.metricsRollingPercentileBucketSize().get()); - // json.put("propertyValue_metricsRollingPercentileWindow", - // commandProperties.metricsRollingPercentileWindowInMilliseconds().get()); - // json.put("propertyValue_metricsRollingPercentileWindowBuckets", - // commandProperties.metricsRollingPercentileWindowBuckets().get()); - // json.put("propertyValue_metricsRollingStatisticalWindowBuckets", - // commandProperties.metricsRollingStatisticalWindowBuckets().get()); - json.writeNumberField( - "propertyValue_metricsRollingStatisticalWindowInMilliseconds", - commandProperties.metricsRollingStatisticalWindowInMilliseconds() - .get()); - - json.writeBooleanField("propertyValue_requestCacheEnabled", - commandProperties.requestCacheEnabled().get()); - json.writeBooleanField("propertyValue_requestLogEnabled", - commandProperties.requestLogEnabled().get()); - - json.writeNumberField("reportingHosts", 1); // this will get summed across - // all instances in a cluster - - json.writeEndObject(); // end data attribute - json.writeEndObject(); - json.close(); - - // output - this.jsonMetrics.add(jsonString.getBuffer().toString()); - } - - // thread pool metrics - for (HystrixThreadPoolMetrics threadPoolMetrics : HystrixThreadPoolMetrics - .getInstances()) { - HystrixThreadPoolKey key = threadPoolMetrics.getThreadPoolKey(); - - StringWriter jsonString = new StringWriter(); - JsonGenerator json = this.jsonFactory.createGenerator(jsonString); - json.writeStartObject(); - - addServiceData(json, this.registration); - json.writeObjectFieldStart("data"); - - json.writeStringField("type", "HystrixThreadPool"); - json.writeStringField("name", key.name()); - json.writeNumberField("currentTime", System.currentTimeMillis()); - - json.writeNumberField("currentActiveCount", - threadPoolMetrics.getCurrentActiveCount().intValue()); - json.writeNumberField("currentCompletedTaskCount", - threadPoolMetrics.getCurrentCompletedTaskCount().longValue()); - json.writeNumberField("currentCorePoolSize", - threadPoolMetrics.getCurrentCorePoolSize().intValue()); - json.writeNumberField("currentLargestPoolSize", - threadPoolMetrics.getCurrentLargestPoolSize().intValue()); - json.writeNumberField("currentMaximumPoolSize", - threadPoolMetrics.getCurrentMaximumPoolSize().intValue()); - json.writeNumberField("currentPoolSize", - threadPoolMetrics.getCurrentPoolSize().intValue()); - json.writeNumberField("currentQueueSize", - threadPoolMetrics.getCurrentQueueSize().intValue()); - json.writeNumberField("currentTaskCount", - threadPoolMetrics.getCurrentTaskCount().longValue()); - json.writeNumberField("rollingCountThreadsExecuted", - threadPoolMetrics.getRollingCountThreadsExecuted()); - json.writeNumberField("rollingMaxActiveThreads", - threadPoolMetrics.getRollingMaxActiveThreads()); - - json.writeNumberField("propertyValue_queueSizeRejectionThreshold", - threadPoolMetrics.getProperties().queueSizeRejectionThreshold() - .get()); - json.writeNumberField( - "propertyValue_metricsRollingStatisticalWindowInMilliseconds", - threadPoolMetrics.getProperties() - .metricsRollingStatisticalWindowInMilliseconds().get()); - - json.writeNumberField("reportingHosts", 1); // this will get summed across - // all instances in a cluster - - json.writeEndObject(); // end of data object - json.writeEndObject(); - json.close(); - // output to stream - this.jsonMetrics.add(jsonString.getBuffer().toString()); - } - } - catch (Exception ex) { - log.error("Error adding metrics to queue", ex); - } - } - - private void addServiceData(JsonGenerator json, ServiceInstance localService) - throws IOException { - json.writeObjectFieldStart("origin"); - json.writeStringField("host", localService.getHost()); - json.writeNumberField("port", localService.getPort()); - json.writeStringField("serviceId", localService.getServiceId()); - if (this.properties.isSendId()) { - json.writeStringField("id", this.context.getId()); - } - json.writeEndObject(); - } - -} diff --git a/spring-cloud-netflix-hystrix-stream/src/main/resources/META-INF/spring.factories b/spring-cloud-netflix-hystrix-stream/src/main/resources/META-INF/spring.factories deleted file mode 100644 index ca7c0a24..00000000 --- a/spring-cloud-netflix-hystrix-stream/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -org.springframework.cloud.netflix.hystrix.stream.HystrixStreamAutoConfiguration diff --git a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfigurationNoRegistrationTests.java b/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfigurationNoRegistrationTests.java deleted file mode 100644 index 4f9dccdd..00000000 --- a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfigurationNoRegistrationTests.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.stream; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClient; -import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryProperties; -import org.springframework.cloud.client.serviceregistry.Registration; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Spencer Gibb - */ -@RunWith(SpringRunner.class) -@SpringBootTest("eureka.client.enabled=false") -@DirtiesContext -public class HystrixStreamAutoConfigurationNoRegistrationTests { - - @Autowired - HystrixStreamTask task; - - @Autowired(required = false) - Registration registration; - - @Autowired - SimpleDiscoveryProperties simpleDiscoveryProperties; - - @Test - public void withoutRegistrationWorks() throws Exception { - assertThat(this.registration).isNull(); - assertThat(this.simpleDiscoveryProperties).isNotNull(); - assertThat(task.getRegistration()).isEqualTo(this.simpleDiscoveryProperties.getLocal()); - } - - @EnableAutoConfiguration - @SpringBootConfiguration - protected static class Config { - } - -} diff --git a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfigurationTests.java b/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfigurationTests.java deleted file mode 100644 index 8473aae0..00000000 --- a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfigurationTests.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.stream; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.cloud.client.serviceregistry.Registration; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Spencer Gibb - */ -@RunWith(SpringRunner.class) -@DirtiesContext -public class HystrixStreamAutoConfigurationTests { - - @Autowired - HystrixStreamTask task; - - @Autowired - Registration registration; - - @Test - public void withRegistrationWorks() throws Exception { - assertThat(task.getRegistration()).isEqualTo(this.registration); - } - - @EnableAutoConfiguration - @SpringBootConfiguration - protected static class Config { - } - -} diff --git a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTaskTests.java b/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTaskTests.java deleted file mode 100644 index 7a98c4ec..00000000 --- a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTaskTests.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.springframework.cloud.netflix.hystrix.stream; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.runners.MockitoJUnitRunner; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.client.serviceregistry.Registration; -import org.springframework.context.ApplicationContext; -import org.springframework.messaging.Message; -import org.springframework.messaging.MessageChannel; - -import com.netflix.hystrix.HystrixCommandGroupKey; -import com.netflix.hystrix.HystrixCommandKey; -import com.netflix.hystrix.HystrixCommandMetrics; -import com.netflix.hystrix.HystrixCommandProperties; -import com.netflix.hystrix.strategy.properties.HystrixPropertiesCommandDefault; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.mockito.BDDMockito.then; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.verifyZeroInteractions; - -/** - * @author Marcin Grzejszczak - */ -@RunWith(MockitoJUnitRunner.class) -public class HystrixStreamTaskTests { - @Mock MessageChannel outboundChannel; - @Mock DiscoveryClient discoveryClient; - @Mock ApplicationContext context; - @Spy HystrixStreamProperties properties; - @Mock Registration registration; - @InjectMocks HystrixStreamTask hystrixStreamTask; - - @Test - public void should_not_send_metrics_when_they_are_empty() throws Exception { - this.hystrixStreamTask.sendMetrics(); - - verifyZeroInteractions(this.outboundChannel); - } - - @Test - public void should_send_metrics_when_they_are_not_empty() throws Exception { - this.hystrixStreamTask.jsonMetrics.put("someJson"); - - this.hystrixStreamTask.sendMetrics(); - - then(this.outboundChannel).should().send(any(Message.class)); - } - - @Test - public void should_gather_json_metrics() throws Exception { - HystrixCommandKey hystrixCommandKey = HystrixCommandKey.Factory.asKey("commandKey"); - HystrixCommandMetrics.getInstance(hystrixCommandKey, - HystrixCommandGroupKey.Factory.asKey("commandGroupKey"), - new HystrixPropertiesCommandDefault(hystrixCommandKey, HystrixCommandProperties.defaultSetter())); - - this.hystrixStreamTask.setApplicationContext(this.context); - this.hystrixStreamTask.gatherMetrics(); - - assertThat(this.hystrixStreamTask.jsonMetrics.isEmpty(), is(false)); - } -} diff --git a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTests.java b/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTests.java deleted file mode 100644 index 2aed71a6..00000000 --- a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTests.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.stream; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; -import org.springframework.cloud.client.serviceregistry.Registration; -import org.springframework.cloud.stream.test.binder.MessageCollector; -import org.springframework.messaging.Message; -import org.springframework.messaging.MessageChannel; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Spencer Gibb - * @author Daniel Lavoie - */ -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { - "debug=true", "spring.jmx.enabled=true", "spring.application.name=mytestapp" }) -@DirtiesContext -public class HystrixStreamTests { - - @Autowired - private HystrixStreamTask task; - - @Autowired - private Application application; - - @Autowired(required = false) - private Registration registration; - - @Autowired - private ObjectMapper mapper; - - @Autowired - private MessageCollector collector; - - @Autowired - @Qualifier(HystrixStreamClient.OUTPUT) - private MessageChannel output; - - @EnableAutoConfiguration - @EnableCircuitBreaker - @RestController - @SpringBootConfiguration - public static class Application { - - @HystrixCommand - @RequestMapping("/") - public String hello() { - return "Hello World"; - } - } - - @Test - public void contextLoads() throws Exception { - this.application.hello(); - // It is important that local service instance resolves for metrics - // origin details to be populated - assertThat(this.registration).isNotNull(); - assertThat(this.registration.getServiceId()).isEqualTo("mytestapp"); - this.task.gatherMetrics(); - Message message = this.collector.forChannel(output).take(); - JsonNode tree = mapper.readTree((String)message.getPayload()); - assertThat(tree.hasNonNull("origin")).isTrue(); - assertThat(tree.hasNonNull("data")).isTrue(); - assertThat(tree.hasNonNull("event")).isTrue(); - assertThat(tree.findValue("event").asText()).isEqualTo("message"); - } - -} diff --git a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/StreamSourceTestBase.java b/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/StreamSourceTestBase.java deleted file mode 100644 index 0ff24a91..00000000 --- a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/StreamSourceTestBase.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright 2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.hystrix.stream; - -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; - -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; -import org.springframework.cloud.contract.verifier.messaging.MessageVerifier; -import org.springframework.cloud.contract.verifier.messaging.boot.AutoConfigureMessageVerifier; -import org.springframework.cloud.contract.verifier.messaging.stream.StreamStubMessages; -import org.springframework.cloud.netflix.hystrix.contract.HystrixContractUtils; -import org.springframework.cloud.netflix.hystrix.stream.StreamSourceTestBase.TestApplication; -import org.springframework.cloud.stream.config.BindingProperties; -import org.springframework.cloud.stream.config.BindingServiceProperties; -import org.springframework.cloud.stream.test.binder.MessageCollector; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.messaging.Message; -import org.springframework.messaging.MessageChannel; -import org.springframework.messaging.MessageHeaders; -import org.springframework.messaging.converter.DefaultContentTypeResolver; -import org.springframework.messaging.converter.MappingJackson2MessageConverter; -import org.springframework.messaging.support.MessageBuilder; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.util.MimeTypeUtils; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - * Base class for sensor autogenerated tests (used by Spring Cloud Contract). - * - * This bootstraps the Spring Boot application code. - * - * @author Marius Bogoevici - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = TestApplication.class, properties = "spring.application.name=application") -@AutoConfigureMessageVerifier -public abstract class StreamSourceTestBase { - - @Autowired - TestApplication application; - - public void createMetricsData() throws Exception { - application.hello(); - } - - public void assertOrigin(Object input) { - System.err.println(input); - @SuppressWarnings("unchecked") - Map origin = (Map) input; - HystrixContractUtils.checkOrigin(origin); - } - - public void assertData(Object input) { - // System.err.println(input); - @SuppressWarnings("unchecked") - Map data = (Map) input; - HystrixContractUtils.checkData(data, TestApplication.class.getSimpleName(), - "application.hello"); - } - - public void assertEvent(Object input) { - HystrixContractUtils.checkEvent((String) input); - } - - @EnableAutoConfiguration - @EnableCircuitBreaker - @RestController - public static class TestApplication { - - @HystrixCommand - @RequestMapping("/") - public String hello() { - return "Hello World"; - } - - public static void main(String[] args) { - SpringApplication.run(TestApplication.class, args); - } - - // TODO: remove this as soon as contract 2.0.0 is available - @Bean - MessageVerifier> contractVerifierMessageExchange( - ApplicationContext applicationContext) { - return new PatchedStubMessages(applicationContext); - } - } - - static class PatchedStubMessages implements MessageVerifier> { - - private static final Logger log = LoggerFactory - .getLogger(StreamStubMessages.class); - - private final ApplicationContext context; - private final MessageCollector messageCollector; - private final ContractVerifierStreamMessageBuilder builder = new ContractVerifierStreamMessageBuilder(); - - public PatchedStubMessages(ApplicationContext context) { - this.context = context; - this.messageCollector = context.getBean(MessageCollector.class); - } - - @Override - public void send(T payload, Map headers, String destination) { - send(this.builder.create(payload, headers), destination); - } - - @Override - public void send(Message message, String destination) { - try { - MessageChannel messageChannel = this.context - .getBean(resolvedDestination(destination), MessageChannel.class); - messageChannel.send(message); - } - catch (Exception e) { - log.error( - "Exception occurred while trying to send a message [" + message - + "] " + "to a channel with name [" + destination + "]", - e); - throw e; - } - } - - @Override - public Message receive(String destination, long timeout, TimeUnit timeUnit) { - try { - MessageChannel messageChannel = this.context - .getBean(resolvedDestination(destination), MessageChannel.class); - Message message = this.messageCollector.forChannel(messageChannel) - .poll(timeout, timeUnit); - if (message == null) { - return message; - } - return MessageBuilder.createMessage(message.getPayload(), message.getHeaders()); - } - catch (Exception e) { - log.error("Exception occurred while trying to read a message from " - + " a channel with name [" + destination + "]", e); - throw new IllegalStateException(e); - } - } - - private String resolvedDestination(String destination) { - try { - BindingServiceProperties channelBindingServiceProperties = this.context - .getBean(BindingServiceProperties.class); - for (Map.Entry entry : channelBindingServiceProperties - .getBindings().entrySet()) { - if (destination.equals(entry.getValue().getDestination())) { - if (log.isDebugEnabled()) { - log.debug("Found a channel named [{}] with destination [{}]", - entry.getKey(), destination); - } - return entry.getKey(); - } - } - } - catch (Exception e) { - log.error( - "Exception took place while trying to resolve the destination. Will assume the name [" - + destination + "]", - e); - } - if (log.isDebugEnabled()) { - log.debug("No destination named [" + destination - + "] was found. Assuming that the destination equals the channel name", - destination); - } - return destination; - } - - @Override - public Message receive(String destination) { - return receive(destination, 5, TimeUnit.SECONDS); - } - - private MappingJackson2MessageConverter converter() { - ObjectMapper mapper = null; - try { - mapper = this.context.getBean(ObjectMapper.class); - } - catch (NoSuchBeanDefinitionException e) { - - } - MappingJackson2MessageConverter converter = createJacksonConverter(); - if (mapper != null) { - converter.setObjectMapper(mapper); - } - return converter; - } - - protected MappingJackson2MessageConverter createJacksonConverter() { - DefaultContentTypeResolver resolver = new DefaultContentTypeResolver(); - resolver.setDefaultMimeType(MimeTypeUtils.APPLICATION_JSON); - MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); - converter.setContentTypeResolver(resolver); - return converter; - } - - } - - static class ContractVerifierStreamMessageBuilder { - - public Message create(T payload, Map headers) { - return MessageBuilder.createMessage(payload, new MessageHeaders(headers)); - } - - } -} diff --git a/spring-cloud-netflix-hystrix-stream/src/test/resources/application.yml b/spring-cloud-netflix-hystrix-stream/src/test/resources/application.yml deleted file mode 100644 index dc48699c..00000000 --- a/spring-cloud-netflix-hystrix-stream/src/test/resources/application.yml +++ /dev/null @@ -1,6 +0,0 @@ -server: - port: 17642 - -logging: - level: - org.springframework.netflix.hystrix.stream: TRACE \ No newline at end of file diff --git a/spring-cloud-netflix-hystrix-stream/src/test/resources/contracts/shouldProduceValidMetricsData.groovy b/spring-cloud-netflix-hystrix-stream/src/test/resources/contracts/shouldProduceValidMetricsData.groovy deleted file mode 100644 index 452bbd44..00000000 --- a/spring-cloud-netflix-hystrix-stream/src/test/resources/contracts/shouldProduceValidMetricsData.groovy +++ /dev/null @@ -1,29 +0,0 @@ -package contracts - -import org.springframework.cloud.netflix.hystrix.contract.HystrixContractUtils - -org.springframework.cloud.contract.spec.Contract.make { - // Human readable description - description 'Should produce valid metrics data' - // Label by means of which the output message can be triggered - label 'metrics' - // input to the contract - input { - // the contract will be triggered by a method - triggeredBy('createMetricsData()') - } - // output message of the contract - outputMessage { - // destination to which the output message will be sent - sentTo 'hystrixStreamOutput' - headers { - header('contentType': 'application/json') - } - body(HystrixContractUtils.simpleBody()) - testMatchers { - jsonPath('$.origin', byCommand('assertOrigin($it)')) - jsonPath('$.event', byCommand('assertEvent($it)')) - jsonPath('$.data', byCommand('assertData($it)')) - } - } -} diff --git a/spring-cloud-netflix-ribbon/pom.xml b/spring-cloud-netflix-ribbon/pom.xml deleted file mode 100644 index 17807f67..00000000 --- a/spring-cloud-netflix-ribbon/pom.xml +++ /dev/null @@ -1,126 +0,0 @@ - - - - spring-cloud-netflix - org.springframework.cloud - 2.0.0.BUILD-SNAPSHOT - .. - - 4.0.0 - - org.springframework.cloud - spring-cloud-netflix-ribbon - - ${basedir}/.. - - - - - org.springframework.boot - spring-boot-starter-web - true - - - org.springframework.boot - spring-boot - true - - - org.springframework.boot - spring-boot-autoconfigure - true - - - org.springframework.cloud - spring-cloud-commons - true - - - org.springframework.cloud - spring-cloud-context - true - - - org.springframework.cloud - spring-cloud-netflix-archaius - - - com.netflix.ribbon - ribbon - true - - - com.netflix.ribbon - ribbon-core - true - - - com.netflix.ribbon - ribbon-httpclient - true - - - com.netflix.ribbon - ribbon-loadbalancer - true - - - - com.sun.jersey.contribs - jersey-apache-client4 - true - - - com.squareup.okhttp3 - okhttp - true - - - org.springframework.retry - spring-retry - true - - - commons-configuration - commons-configuration - true - - - com.netflix.servo - servo-core - true - - - com.netflix.netflix-commons - netflix-commons-util - true - - - com.netflix.hystrix - hystrix-javanica - true - - - org.springframework.cloud - spring-cloud-test-support - test - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.boot - spring-boot-starter-security - test - - - org.springframework.boot - spring-boot-starter-actuator - test - - - \ No newline at end of file diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospector.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospector.java deleted file mode 100644 index c1dfcb1d..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospector.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.util.Collections; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; - -import com.netflix.loadbalancer.Server; - -/** - * @author Spencer Gibb - */ -public class DefaultServerIntrospector implements ServerIntrospector { - - private ServerIntrospectorProperties serverIntrospectorProperties = new ServerIntrospectorProperties(); - - @Autowired(required = false) - public void setServerIntrospectorProperties(ServerIntrospectorProperties serverIntrospectorProperties){ - this.serverIntrospectorProperties = serverIntrospectorProperties; - } - - @Override - public boolean isSecure(Server server) { - return serverIntrospectorProperties.getSecurePorts().contains(server.getPort()); - } - - @Override - public Map getMetadata(Server server) { - return Collections.emptyMap(); - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/PropertiesFactory.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/PropertiesFactory.java deleted file mode 100644 index 3e26ee31..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/PropertiesFactory.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.springframework.cloud.netflix.ribbon; - -import java.util.HashMap; -import java.util.Map; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.util.StringUtils; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.IPing; -import com.netflix.loadbalancer.IRule; -import com.netflix.loadbalancer.ServerList; -import com.netflix.loadbalancer.ServerListFilter; - -import static org.springframework.cloud.netflix.ribbon.SpringClientFactory.NAMESPACE; - -/** - * @author Spencer Gibb - */ -public class PropertiesFactory { - @Autowired - private Environment environment; - - private Map classToProperty = new HashMap<>(); - - public PropertiesFactory() { - classToProperty.put(ILoadBalancer.class, "NFLoadBalancerClassName"); - classToProperty.put(IPing.class, "NFLoadBalancerPingClassName"); - classToProperty.put(IRule.class, "NFLoadBalancerRuleClassName"); - classToProperty.put(ServerList.class, "NIWSServerListClassName"); - classToProperty.put(ServerListFilter.class, "NIWSServerListFilterClassName"); - } - - public boolean isSet(Class clazz, String name) { - return StringUtils.hasText(getClassName(clazz, name)); - } - - public String getClassName(Class clazz, String name) { - if (this.classToProperty.containsKey(clazz)) { - String classNameProperty = this.classToProperty.get(clazz); - String className = environment.getProperty(name + "." + NAMESPACE + "." + classNameProperty); - return className; - } - return null; - } - - @SuppressWarnings("unchecked") - public C get(Class clazz, IClientConfig config, String name) { - String className = getClassName(clazz, name); - if (StringUtils.hasText(className)) { - try { - Class toInstantiate = Class.forName(className); - return (C) SpringClientFactory.instantiateWithConfig(toInstantiate, config); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException("Unknown class to load "+className+" for class " + clazz + " named " + name); - } - } - return null; - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RestClientRibbonConfiguration.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RestClientRibbonConfiguration.java deleted file mode 100644 index a4827be5..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RestClientRibbonConfiguration.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Lazy; - -import com.netflix.client.AbstractLoadBalancerAwareClient; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.niws.client.http.RestClient; -import com.netflix.servo.monitor.Monitors; - -/** - * @author Spencer Gibb - */ -@SuppressWarnings("deprecation") -@Configuration -@RibbonAutoConfiguration.ConditionalOnRibbonRestClient -class RestClientRibbonConfiguration { - @RibbonClientName - private String name = "client"; - - /** - * Create a Netflix {@link RestClient} integrated with Ribbon if none already exists - * in the application context. It is not required for Ribbon to work properly and is - * therefore created lazily if ever another component requires it. - * - * @param config the configuration to use by the underlying Ribbon instance - * @param loadBalancer the load balancer to use by the underlying Ribbon instance - * @param serverIntrospector server introspector to use by the underlying Ribbon instance - * @param retryHandler retry handler to use by the underlying Ribbon instance - * @return a {@link RestClient} instances backed by Ribbon - */ - @Bean - @Lazy - @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class) - public RestClient ribbonRestClient(IClientConfig config, ILoadBalancer loadBalancer, - ServerIntrospector serverIntrospector, RetryHandler retryHandler) { - RestClient client = new RibbonClientConfiguration.OverrideRestClient(config, serverIntrospector); - client.setLoadBalancer(loadBalancer); - client.setRetryHandler(retryHandler); - Monitors.registerObject("Client_" + this.name, client); - return client; - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializer.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializer.java deleted file mode 100644 index 3051bb49..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializer.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.util.List; -import org.springframework.boot.context.event.ApplicationReadyEvent; -import org.springframework.context.ApplicationListener; - -/** - * Responsible for eagerly creating the child application context holding the Ribbon - * related configuration - * - * @author Biju Kunjummen - */ -public class RibbonApplicationContextInitializer - implements ApplicationListener { - - private final SpringClientFactory springClientFactory; - - //List of Ribbon client names - private final List clientNames; - - public RibbonApplicationContextInitializer(SpringClientFactory springClientFactory, - List clientNames) { - this.springClientFactory = springClientFactory; - this.clientNames = clientNames; - } - - protected void initialize() { - if (clientNames != null) { - for (String clientName : clientNames) { - this.springClientFactory.getContext(clientName); - } - } - } - - @Override - public void onApplicationEvent(ApplicationReadyEvent event) { - initialize(); - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfiguration.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfiguration.java deleted file mode 100644 index d6e5f275..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfiguration.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.util.ArrayList; -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.condition.AnyNestedCondition; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.client.actuator.HasFeatures; -import org.springframework.cloud.client.loadbalancer.AsyncLoadBalancerAutoConfiguration; -import org.springframework.cloud.client.loadbalancer.LoadBalancedBackOffPolicyFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryListenerFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicyFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration; -import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; -import org.springframework.cloud.client.loadbalancer.RestTemplateCustomizer; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Conditional; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.client.AsyncRestTemplate; -import org.springframework.web.client.RestTemplate; -import com.netflix.client.IClient; -import com.netflix.client.http.HttpRequest; -import com.netflix.ribbon.Ribbon; - -/** - * Auto configuration for Ribbon (client side load balancing). - * - * @author Spencer Gibb - * @author Dave Syer - * @author Biju Kunjummen - */ -@Configuration -@ConditionalOnClass({ IClient.class, RestTemplate.class, AsyncRestTemplate.class, Ribbon.class}) -@RibbonClients -@AutoConfigureAfter(name = "org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration") -@AutoConfigureBefore({LoadBalancerAutoConfiguration.class, AsyncLoadBalancerAutoConfiguration.class}) -@EnableConfigurationProperties({RibbonEagerLoadProperties.class, ServerIntrospectorProperties.class}) -public class RibbonAutoConfiguration { - - @Autowired(required = false) - private List configurations = new ArrayList<>(); - - @Autowired - private RibbonEagerLoadProperties ribbonEagerLoadProperties; - - @Bean - public HasFeatures ribbonFeature() { - return HasFeatures.namedFeature("Ribbon", Ribbon.class); - } - - @Bean - public SpringClientFactory springClientFactory() { - SpringClientFactory factory = new SpringClientFactory(); - factory.setConfigurations(this.configurations); - return factory; - } - - @Bean - @ConditionalOnMissingBean(LoadBalancerClient.class) - public LoadBalancerClient loadBalancerClient() { - return new RibbonLoadBalancerClient(springClientFactory()); - } - - @Bean - @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate") - @ConditionalOnMissingBean - public LoadBalancedRetryPolicyFactory loadBalancedRetryPolicyFactory(SpringClientFactory clientFactory) { - return new RibbonLoadBalancedRetryPolicyFactory(clientFactory); - } - - @Bean - @ConditionalOnMissingClass(value = "org.springframework.retry.support.RetryTemplate") - @ConditionalOnMissingBean - public LoadBalancedRetryPolicyFactory neverRetryPolicyFactory() { - return new LoadBalancedRetryPolicyFactory.NeverRetryFactory(); - } - - @Bean - @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate") - @ConditionalOnMissingBean - public LoadBalancedBackOffPolicyFactory loadBalancedBackoffPolicyFactory() { - return new LoadBalancedBackOffPolicyFactory.NoBackOffPolicyFactory(); - } - - @Bean - @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate") - @ConditionalOnMissingBean - public LoadBalancedRetryListenerFactory loadBalancedRetryListenerFactory() { - return new LoadBalancedRetryListenerFactory.DefaultRetryListenerFactory(); - } - - @Bean - @ConditionalOnMissingBean - public PropertiesFactory propertiesFactory() { - return new PropertiesFactory(); - } - - @Bean - @ConditionalOnProperty(value = "ribbon.eager-load.enabled") - public RibbonApplicationContextInitializer ribbonApplicationContextInitializer() { - return new RibbonApplicationContextInitializer(springClientFactory(), - ribbonEagerLoadProperties.getClients()); - } - - @Configuration - @ConditionalOnClass(HttpRequest.class) - @ConditionalOnRibbonRestClient - protected static class RibbonClientHttpRequestFactoryConfiguration { - - @Autowired - private SpringClientFactory springClientFactory; - - @Bean - public RestTemplateCustomizer restTemplateCustomizer( - final RibbonClientHttpRequestFactory ribbonClientHttpRequestFactory) { - return restTemplate -> restTemplate.setRequestFactory(ribbonClientHttpRequestFactory); - } - - @Bean - public RibbonClientHttpRequestFactory ribbonClientHttpRequestFactory() { - return new RibbonClientHttpRequestFactory(this.springClientFactory); - } - } - - //TODO: support for autoconfiguring restemplate to use apache http client or okhttp - - @Target({ ElementType.TYPE, ElementType.METHOD }) - @Retention(RetentionPolicy.RUNTIME) - @Documented - @Conditional(OnRibbonRestClientCondition.class) - @interface ConditionalOnRibbonRestClient { } - - private static class OnRibbonRestClientCondition extends AnyNestedCondition { - public OnRibbonRestClientCondition() { - super(ConfigurationPhase.REGISTER_BEAN); - } - - @Deprecated //remove in Edgware" - @ConditionalOnProperty("ribbon.http.client.enabled") - static class ZuulProperty {} - - @ConditionalOnProperty("ribbon.restclient.enabled") - static class RibbonProperty {} - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClient.java deleted file mode 100644 index 1b6e017b..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClient.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.IRule; -import com.netflix.loadbalancer.ServerListFilter; - -/** - * Declarative configuration for a ribbon client. Add this annotation to any - * @Configuration and then inject a {@link SpringClientFactory} to access the - * client that is created. - * - * @author Dave Syer - */ -@Configuration -@Import(RibbonClientConfigurationRegistrar.class) -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface RibbonClient { - - /** - * Synonym for name (the name of the client) - * - * @see #name() - */ - String value() default ""; - - /** - * The name of the ribbon client, uniquely identifying a set of client resources, - * including a load balancer. - */ - String name() default ""; - - /** - * A custom @Configuration for the ribbon client. Can contain override - * @Bean definition for the pieces that make up the client, for instance - * {@link ILoadBalancer}, {@link ServerListFilter}, {@link IRule}. - * - * @see RibbonClientConfiguration for the defaults - */ - Class[] configuration() default {}; - -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfiguration.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfiguration.java deleted file mode 100644 index dc2ff6bd..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfiguration.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.net.URI; -import javax.annotation.PostConstruct; -import org.apache.http.client.params.ClientPNames; -import org.apache.http.client.params.CookiePolicy; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; -import org.springframework.cloud.netflix.ribbon.apache.HttpClientRibbonConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpRibbonConfiguration; -import com.netflix.client.DefaultLoadBalancerRetryHandler; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ConfigurationBasedServerList; -import com.netflix.loadbalancer.DummyPing; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.IPing; -import com.netflix.loadbalancer.IRule; -import com.netflix.loadbalancer.PollingServerListUpdater; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.loadbalancer.ServerListFilter; -import com.netflix.loadbalancer.ServerListUpdater; -import com.netflix.loadbalancer.ZoneAvoidanceRule; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; -import com.netflix.niws.client.http.RestClient; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.client.apache4.ApacheHttpClient4; - -import static com.netflix.client.config.CommonClientConfigKey.DeploymentContextBasedVipAddresses; -import static org.springframework.cloud.netflix.ribbon.RibbonUtils.setRibbonProperty; -import static org.springframework.cloud.netflix.ribbon.RibbonUtils.updateToSecureConnectionIfNeeded; - -/** - * @author Dave Syer - * @author Tim Ysewyn - */ -@SuppressWarnings("deprecation") -@Configuration -@EnableConfigurationProperties -//Order is important here, last should be the default, first should be optional -// see https://github.com/spring-cloud/spring-cloud-netflix/issues/2086#issuecomment-316281653 -@Import({HttpClientConfiguration.class, OkHttpRibbonConfiguration.class, RestClientRibbonConfiguration.class, HttpClientRibbonConfiguration.class}) -public class RibbonClientConfiguration { - - public static final int DEFAULT_CONNECT_TIMEOUT = 1000; - public static final int DEFAULT_READ_TIMEOUT = 1000; - - @RibbonClientName - private String name = "client"; - - // TODO: maybe re-instate autowired load balancers: identified by name they could be - // associated with ribbon clients - - @Autowired - private PropertiesFactory propertiesFactory; - - @Bean - @ConditionalOnMissingBean - public IClientConfig ribbonClientConfig() { - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.loadProperties(this.name); - config.set(CommonClientConfigKey.ConnectTimeout, DEFAULT_CONNECT_TIMEOUT); - config.set(CommonClientConfigKey.ReadTimeout, DEFAULT_READ_TIMEOUT); - return config; - } - - @Bean - @ConditionalOnMissingBean - public IRule ribbonRule(IClientConfig config) { - if (this.propertiesFactory.isSet(IRule.class, name)) { - return this.propertiesFactory.get(IRule.class, config, name); - } - ZoneAvoidanceRule rule = new ZoneAvoidanceRule(); - rule.initWithNiwsConfig(config); - return rule; - } - - @Bean - @ConditionalOnMissingBean - public IPing ribbonPing(IClientConfig config) { - if (this.propertiesFactory.isSet(IPing.class, name)) { - return this.propertiesFactory.get(IPing.class, config, name); - } - return new DummyPing(); - } - - @Bean - @ConditionalOnMissingBean - @SuppressWarnings("unchecked") - public ServerList ribbonServerList(IClientConfig config) { - if (this.propertiesFactory.isSet(ServerList.class, name)) { - return this.propertiesFactory.get(ServerList.class, config, name); - } - ConfigurationBasedServerList serverList = new ConfigurationBasedServerList(); - serverList.initWithNiwsConfig(config); - return serverList; - } - - @Bean - @ConditionalOnMissingBean - public ServerListUpdater ribbonServerListUpdater(IClientConfig config) { - return new PollingServerListUpdater(config); - } - - @Bean - @ConditionalOnMissingBean - public ILoadBalancer ribbonLoadBalancer(IClientConfig config, - ServerList serverList, ServerListFilter serverListFilter, - IRule rule, IPing ping, ServerListUpdater serverListUpdater) { - if (this.propertiesFactory.isSet(ILoadBalancer.class, name)) { - return this.propertiesFactory.get(ILoadBalancer.class, config, name); - } - return new ZoneAwareLoadBalancer<>(config, rule, ping, serverList, - serverListFilter, serverListUpdater); - } - - @Bean - @ConditionalOnMissingBean - @SuppressWarnings("unchecked") - public ServerListFilter ribbonServerListFilter(IClientConfig config) { - if (this.propertiesFactory.isSet(ServerListFilter.class, name)) { - return this.propertiesFactory.get(ServerListFilter.class, config, name); - } - ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter(); - filter.initWithNiwsConfig(config); - return filter; - } - - @Bean - @ConditionalOnMissingBean - public RibbonLoadBalancerContext ribbonLoadBalancerContext(ILoadBalancer loadBalancer, - IClientConfig config, RetryHandler retryHandler) { - return new RibbonLoadBalancerContext(loadBalancer, config, retryHandler); - } - - @Bean - @ConditionalOnMissingBean - public RetryHandler retryHandler(IClientConfig config) { - return new DefaultLoadBalancerRetryHandler(config); - } - - @Bean - @ConditionalOnMissingBean - public ServerIntrospector serverIntrospector() { - return new DefaultServerIntrospector(); - } - - @PostConstruct - public void preprocess() { - setRibbonProperty(name, DeploymentContextBasedVipAddresses.key(), name); - } - - static class OverrideRestClient extends RestClient { - - private IClientConfig config; - private ServerIntrospector serverIntrospector; - - protected OverrideRestClient(IClientConfig config, - ServerIntrospector serverIntrospector) { - super(); - this.config = config; - this.serverIntrospector = serverIntrospector; - initWithNiwsConfig(this.config); - } - - @Override - public URI reconstructURIWithServer(Server server, URI original) { - URI uri = updateToSecureConnectionIfNeeded(original, this.config, - this.serverIntrospector, server); - return super.reconstructURIWithServer(server, uri); - } - - @Override - protected Client apacheHttpClientSpecificInitialization() { - ApacheHttpClient4 apache = (ApacheHttpClient4) super.apacheHttpClientSpecificInitialization(); - apache.getClientHandler().getHttpClient().getParams().setParameter( - ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES); - return apache; - } - - } - -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationRegistrar.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationRegistrar.java deleted file mode 100644 index b72841ca..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationRegistrar.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.util.Map; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; -import org.springframework.core.annotation.AnnotationAttributes; -import org.springframework.core.type.AnnotationMetadata; -import org.springframework.util.StringUtils; - -/** - * @author Dave Syer - */ -public class RibbonClientConfigurationRegistrar implements ImportBeanDefinitionRegistrar { - - @Override - public void registerBeanDefinitions(AnnotationMetadata metadata, - BeanDefinitionRegistry registry) { - Map attrs = metadata.getAnnotationAttributes( - RibbonClients.class.getName(), true); - if (attrs != null && attrs.containsKey("value")) { - AnnotationAttributes[] clients = (AnnotationAttributes[]) attrs.get("value"); - for (AnnotationAttributes client : clients) { - registerClientConfiguration(registry, getClientName(client), - client.get("configuration")); - } - } - if (attrs != null && attrs.containsKey("defaultConfiguration")) { - String name; - if (metadata.hasEnclosingClass()) { - name = "default." + metadata.getEnclosingClassName(); - } else { - name = "default." + metadata.getClassName(); - } - registerClientConfiguration(registry, name, - attrs.get("defaultConfiguration")); - } - Map client = metadata.getAnnotationAttributes( - RibbonClient.class.getName(), true); - String name = getClientName(client); - if (name != null) { - registerClientConfiguration(registry, name, client.get("configuration")); - } - } - - private String getClientName(Map client) { - if (client == null) { - return null; - } - String value = (String) client.get("value"); - if (!StringUtils.hasText(value)) { - value = (String) client.get("name"); - } - if (StringUtils.hasText(value)) { - return value; - } - throw new IllegalStateException( - "Either 'name' or 'value' must be provided in @RibbonClient"); - } - - private void registerClientConfiguration(BeanDefinitionRegistry registry, - Object name, Object configuration) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder - .genericBeanDefinition(RibbonClientSpecification.class); - builder.addConstructorArgValue(name); - builder.addConstructorArgValue(configuration); - registry.registerBeanDefinition(name + ".RibbonClientSpecification", - builder.getBeanDefinition()); - } - -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactory.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactory.java deleted file mode 100644 index 910206b4..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactory.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.io.IOException; -import java.net.URI; -import org.springframework.http.HttpMethod; -import org.springframework.http.client.ClientHttpRequest; -import org.springframework.http.client.ClientHttpRequestFactory; -import com.netflix.client.config.IClientConfig; -import com.netflix.client.http.HttpRequest; -import com.netflix.niws.client.http.RestClient; - -/** - * @author Spencer Gibb - */ -public class RibbonClientHttpRequestFactory implements ClientHttpRequestFactory { - - private final SpringClientFactory clientFactory; - - public RibbonClientHttpRequestFactory(SpringClientFactory clientFactory) { - this.clientFactory = clientFactory; - } - - @Override - @SuppressWarnings("deprecation") - public ClientHttpRequest createRequest(URI originalUri, HttpMethod httpMethod) - throws IOException { - String serviceId = originalUri.getHost(); - if (serviceId == null) { - throw new IOException( - "Invalid hostname in the URI [" + originalUri.toASCIIString() + "]"); - } - IClientConfig clientConfig = this.clientFactory.getClientConfig(serviceId); - RestClient client = this.clientFactory.getClient(serviceId, RestClient.class); - HttpRequest.Verb verb = HttpRequest.Verb.valueOf(httpMethod.name()); - - return new RibbonHttpRequest(originalUri, verb, client, clientConfig); - } - -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientName.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientName.java deleted file mode 100644 index 122edb62..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientName.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.springframework.cloud.netflix.ribbon; - -import org.springframework.beans.factory.annotation.Value; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Annotation at the field or method/constructor parameter level that injects the - * Ribbon Client Name that got allocated at runtime. Provides a convenient - * alternative for @Value("${ribbon.client.name}"). - * - * @author Spencer Gibb - * @since 2.0.0 - */ -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, - ElementType.ANNOTATION_TYPE }) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Value("${ribbon.client.name}") -public @interface RibbonClientName { - -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientSpecification.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientSpecification.java deleted file mode 100644 index ad1827fe..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientSpecification.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.util.Arrays; -import java.util.Objects; -import org.springframework.cloud.context.named.NamedContextFactory; - -/** - * @author Dave Syer - */ -public class RibbonClientSpecification implements NamedContextFactory.Specification { - - private String name; - - private Class[] configuration; - - public RibbonClientSpecification() { - } - - public RibbonClientSpecification(String name, Class[] configuration) { - this.name = name; - this.configuration = configuration; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Class[] getConfiguration() { - return configuration; - } - - public void setConfiguration(Class[] configuration) { - this.configuration = configuration; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - RibbonClientSpecification that = (RibbonClientSpecification) o; - return Arrays.equals(configuration, that.configuration) && - Objects.equals(name, that.name); - } - - @Override - public int hashCode() { - return Objects.hash(configuration, name); - } - - @Override - public String toString() { - return new StringBuilder("RibbonClientSpecification{") - .append("name='").append(name).append("', ") - .append("configuration=").append(Arrays.toString(configuration)) - .append("}").toString(); - } - -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClients.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClients.java deleted file mode 100644 index 32e88cc2..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClients.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -/** - * Convenience annotation that allows user to combine multiple @RibbonClient - * annotations on a single class (including in Java 7). - * - * @author Dave Syer - */ -@Configuration -@Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.TYPE }) -@Documented -@Import(RibbonClientConfigurationRegistrar.class) -public @interface RibbonClients { - - RibbonClient[] value() default {}; - - Class[] defaultConfiguration() default {}; - -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonEagerLoadProperties.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonEagerLoadProperties.java deleted file mode 100644 index f27b6b48..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonEagerLoadProperties.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.util.List; -import org.springframework.boot.context.properties.ConfigurationProperties; - -/* - * Configuration Properties to indicate which Ribbon configurations - * should be eagerly loaded up - * - * @author Biju Kunjummen - */ -@ConfigurationProperties(prefix = "ribbon.eager-load") -public class RibbonEagerLoadProperties { - private boolean enabled = false; - private List clients; - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public List getClients() { - return clients; - } - - public void setClients(List clients) { - this.clients = clients; - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpRequest.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpRequest.java deleted file mode 100644 index 803f2cb7..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpRequest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.URI; -import java.util.List; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.client.AbstractClientHttpRequest; -import org.springframework.http.client.ClientHttpResponse; -import com.netflix.client.config.IClientConfig; -import com.netflix.client.http.HttpRequest; -import com.netflix.client.http.HttpResponse; -import com.netflix.niws.client.http.RestClient; - -/** - * @author Spencer Gibb - */ -@SuppressWarnings("deprecation") -public class RibbonHttpRequest extends AbstractClientHttpRequest { - - private HttpRequest.Builder builder; - private URI uri; - private HttpRequest.Verb verb; - private RestClient client; - private IClientConfig config; - private ByteArrayOutputStream outputStream = null; - - public RibbonHttpRequest(URI uri, HttpRequest.Verb verb, RestClient client, - IClientConfig config) { - this.uri = uri; - this.verb = verb; - this.client = client; - this.config = config; - this.builder = HttpRequest.newBuilder().uri(uri).verb(verb); - } - - @Override - public HttpMethod getMethod() { - return HttpMethod.valueOf(verb.name()); - } - - @Override - public String getMethodValue() { - return getMethod().name(); - } - - @Override - public URI getURI() { - return uri; - } - - @Override - protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException { - if (outputStream == null) { - outputStream = new ByteArrayOutputStream(); - } - return outputStream; - } - - @Override - protected ClientHttpResponse executeInternal(HttpHeaders headers) - throws IOException { - try { - addHeaders(headers); - if (outputStream != null) { - outputStream.close(); - builder.entity(outputStream.toByteArray()); - } - HttpRequest request = builder.build(); - HttpResponse response = client.executeWithLoadBalancer(request, config); - return new RibbonHttpResponse(response); - } catch (Exception e) { - throw new IOException(e); - } - } - - private void addHeaders(HttpHeaders headers) { - for (String name : headers.keySet()) { - // apache http RequestContent pukes if there is a body and - // the dynamic headers are already present - if (isDynamic(name) && outputStream != null) { - continue; - } - //Don't add content-length if the output stream is null. The RibbonClient does this for us. - if (name.equals("Content-Length") && outputStream == null) { - continue; - } - List values = headers.get(name); - for (String value : values) { - builder.header(name, value); - } - } - } - - private boolean isDynamic(String name) { - return "Content-Length".equalsIgnoreCase(name) || "Transfer-Encoding".equalsIgnoreCase(name); - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpResponse.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpResponse.java deleted file mode 100644 index 12a6e192..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpResponse.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Map; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.client.AbstractClientHttpResponse; -import com.netflix.client.http.HttpResponse; - -/** - * @author Spencer Gibb - */ -public class RibbonHttpResponse extends AbstractClientHttpResponse { - - private HttpResponse response; - private HttpHeaders httpHeaders; - - public RibbonHttpResponse(HttpResponse response) { - this.response = response; - this.httpHeaders = new HttpHeaders(); - List> headers = response.getHttpHeaders() - .getAllHeaders(); - for (Map.Entry header : headers) { - this.httpHeaders.add(header.getKey(), header.getValue()); - } - } - - @Override - public InputStream getBody() throws IOException { - return response.getInputStream(); - } - - @Override - public HttpHeaders getHeaders() { - return this.httpHeaders; - } - - @Override - public int getRawStatusCode() throws IOException { - return response.getStatus(); - } - - @Override - public String getStatusText() throws IOException { - return HttpStatus.valueOf(response.getStatus()).name(); - } - - @Override - public void close() { - response.close(); - } - -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicy.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicy.java deleted file mode 100644 index 335b3b8c..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicy.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy; -import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser; -import org.springframework.http.HttpMethod; -import org.springframework.util.StringUtils; - -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.IClientConfig; -import com.netflix.client.config.IClientConfigKey; - -/** - * {@link LoadBalancedRetryPolicy} for Ribbon clients. - * @author Ryan Baxter - */ -public class RibbonLoadBalancedRetryPolicy implements LoadBalancedRetryPolicy { - - public static final IClientConfigKey RETRYABLE_STATUS_CODES = new CommonClientConfigKey("retryableStatusCodes") {}; - private static final Log log = LogFactory.getLog(RibbonLoadBalancedRetryPolicy.class); - private int sameServerCount = 0; - private int nextServerCount = 0; - private String serviceId; - private RibbonLoadBalancerContext lbContext; - private ServiceInstanceChooser loadBalanceChooser; - List retryableStatusCodes = new ArrayList<>(); - - public RibbonLoadBalancedRetryPolicy(String serviceId, RibbonLoadBalancerContext context, ServiceInstanceChooser loadBalanceChooser) { - this.serviceId = serviceId; - this.lbContext = context; - this.loadBalanceChooser = loadBalanceChooser; - } - - public RibbonLoadBalancedRetryPolicy(String serviceId, RibbonLoadBalancerContext context, ServiceInstanceChooser loadBalanceChooser, - IClientConfig clientConfig) { - this.serviceId = serviceId; - this.lbContext = context; - this.loadBalanceChooser = loadBalanceChooser; - String retryableStatusCodesProp = clientConfig.getPropertyAsString(RETRYABLE_STATUS_CODES, ""); - String[] retryableStatusCodesArray = retryableStatusCodesProp.split(","); - for(String code : retryableStatusCodesArray) { - if(!StringUtils.isEmpty(code)) { - try { - retryableStatusCodes.add(Integer.valueOf(code.trim())); - } catch (NumberFormatException e) { - log.warn("We cant add the status code because the code [ " + code + " ] could not be converted to an integer. ", e); - } - } - } - } - - public boolean canRetry(LoadBalancedRetryContext context) { - HttpMethod method = context.getRequest().getMethod(); - return HttpMethod.GET == method || lbContext.isOkToRetryOnAllOperations(); - } - - @Override - public boolean canRetrySameServer(LoadBalancedRetryContext context) { - return sameServerCount < lbContext.getRetryHandler().getMaxRetriesOnSameServer() && canRetry(context); - } - - @Override - public boolean canRetryNextServer(LoadBalancedRetryContext context) { - //this will be called after a failure occurs and we increment the counter - //so we check that the count is less than or equals to too make sure - //we try the next server the right number of times - return nextServerCount <= lbContext.getRetryHandler().getMaxRetriesOnNextServer() && canRetry(context); - } - - @Override - public void close(LoadBalancedRetryContext context) { - - } - - @Override - public void registerThrowable(LoadBalancedRetryContext context, Throwable throwable) { - //Check if we need to ask the load balancer for a new server. - //Do this before we increment the counters because the first call to this method - //is not a retry it is just an initial failure. - if(!canRetrySameServer(context) && canRetryNextServer(context)) { - context.setServiceInstance(loadBalanceChooser.choose(serviceId)); - } - //This method is called regardless of whether we are retrying or making the first request. - //Since we do not count the initial request in the retry count we don't reset the counter - //until we actually equal the same server count limit. This will allow us to make the initial - //request plus the right number of retries. - if(sameServerCount >= lbContext.getRetryHandler().getMaxRetriesOnSameServer() && canRetry(context)) { - //reset same server since we are moving to a new server - sameServerCount = 0; - nextServerCount++; - if(!canRetryNextServer(context)) { - context.setExhaustedOnly(); - } - } else { - sameServerCount++; - } - - } - - @Override - public boolean retryableStatusCode(int statusCode) { - return retryableStatusCodes.contains(statusCode); - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicyFactory.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicyFactory.java deleted file mode 100644 index f1ee0001..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicyFactory.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.cloud.netflix.ribbon; - -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicyFactory; -import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser; - -/** - * @author Ryan Baxter - */ -public class RibbonLoadBalancedRetryPolicyFactory implements LoadBalancedRetryPolicyFactory { - - private SpringClientFactory clientFactory; - - public RibbonLoadBalancedRetryPolicyFactory(SpringClientFactory clientFactory) { - this.clientFactory = clientFactory; - } - - @Override - public LoadBalancedRetryPolicy create(String serviceId, ServiceInstanceChooser loadBalanceChooser) { - RibbonLoadBalancerContext lbContext = this.clientFactory - .getLoadBalancerContext(serviceId); - return new RibbonLoadBalancedRetryPolicy(serviceId, lbContext, loadBalanceChooser, clientFactory.getClientConfig(serviceId)); - } -} - diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClient.java deleted file mode 100644 index 45bffa5e..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClient.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.io.IOException; -import java.net.URI; -import java.util.Collections; -import java.util.Map; -import org.springframework.cloud.client.DefaultServiceInstance; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; -import org.springframework.cloud.client.loadbalancer.LoadBalancerRequest; -import org.springframework.util.Assert; -import org.springframework.util.ReflectionUtils; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.Server; - -/** - * @author Spencer Gibb - * @author Dave Syer - * @author Ryan Baxter - * @author Tim Ysewyn - */ -public class RibbonLoadBalancerClient implements LoadBalancerClient { - - private SpringClientFactory clientFactory; - - public RibbonLoadBalancerClient(SpringClientFactory clientFactory) { - this.clientFactory = clientFactory; - } - - @Override - public URI reconstructURI(ServiceInstance instance, URI original) { - Assert.notNull(instance, "instance can not be null"); - String serviceId = instance.getServiceId(); - RibbonLoadBalancerContext context = this.clientFactory - .getLoadBalancerContext(serviceId); - Server server = new Server(instance.getScheme(), instance.getHost(), instance.getPort()); - IClientConfig clientConfig = clientFactory.getClientConfig(serviceId); - ServerIntrospector serverIntrospector = serverIntrospector(serviceId); - URI uri = RibbonUtils.updateToSecureConnectionIfNeeded(original, clientConfig, - serverIntrospector, server); - return context.reconstructURIWithServer(server, uri); - } - - @Override - public ServiceInstance choose(String serviceId) { - Server server = getServer(serviceId); - if (server == null) { - return null; - } - return new RibbonServer(serviceId, server, isSecure(server, serviceId), - serverIntrospector(serviceId).getMetadata(server)); - } - - @Override - public T execute(String serviceId, LoadBalancerRequest request) throws IOException { - ILoadBalancer loadBalancer = getLoadBalancer(serviceId); - Server server = getServer(loadBalancer); - if (server == null) { - throw new IllegalStateException("No instances available for " + serviceId); - } - RibbonServer ribbonServer = new RibbonServer(serviceId, server, isSecure(server, - serviceId), serverIntrospector(serviceId).getMetadata(server)); - - return execute(serviceId, ribbonServer, request); - } - - @Override - public T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest request) throws IOException { - Server server = null; - if(serviceInstance instanceof RibbonServer) { - server = ((RibbonServer)serviceInstance).getServer(); - } - if (server == null) { - throw new IllegalStateException("No instances available for " + serviceId); - } - - RibbonLoadBalancerContext context = this.clientFactory - .getLoadBalancerContext(serviceId); - RibbonStatsRecorder statsRecorder = new RibbonStatsRecorder(context, server); - - try { - T returnVal = request.apply(serviceInstance); - statsRecorder.recordStats(returnVal); - return returnVal; - } - // catch IOException and rethrow so RestTemplate behaves correctly - catch (IOException ex) { - statsRecorder.recordStats(ex); - throw ex; - } - catch (Exception ex) { - statsRecorder.recordStats(ex); - ReflectionUtils.rethrowRuntimeException(ex); - } - return null; - } - - private ServerIntrospector serverIntrospector(String serviceId) { - ServerIntrospector serverIntrospector = this.clientFactory.getInstance(serviceId, - ServerIntrospector.class); - if (serverIntrospector == null) { - serverIntrospector = new DefaultServerIntrospector(); - } - return serverIntrospector; - } - - private boolean isSecure(Server server, String serviceId) { - IClientConfig config = this.clientFactory.getClientConfig(serviceId); - ServerIntrospector serverIntrospector = serverIntrospector(serviceId); - return RibbonUtils.isSecure(config, serverIntrospector, server); - } - - protected Server getServer(String serviceId) { - return getServer(getLoadBalancer(serviceId)); - } - - protected Server getServer(ILoadBalancer loadBalancer) { - if (loadBalancer == null) { - return null; - } - return loadBalancer.chooseServer("default"); // TODO: better handling of key - } - - protected ILoadBalancer getLoadBalancer(String serviceId) { - return this.clientFactory.getLoadBalancer(serviceId); - } - - public static class RibbonServer implements ServiceInstance { - private final String serviceId; - private final Server server; - private final boolean secure; - private Map metadata; - - public RibbonServer(String serviceId, Server server) { - this(serviceId, server, false, Collections. emptyMap()); - } - - public RibbonServer(String serviceId, Server server, boolean secure, - Map metadata) { - this.serviceId = serviceId; - this.server = server; - this.secure = secure; - this.metadata = metadata; - } - - @Override - public String getServiceId() { - return this.serviceId; - } - - @Override - public String getHost() { - return this.server.getHost(); - } - - @Override - public int getPort() { - return this.server.getPort(); - } - - @Override - public boolean isSecure() { - return this.secure; - } - - @Override - public URI getUri() { - return DefaultServiceInstance.getUri(this); - } - - @Override - public Map getMetadata() { - return this.metadata; - } - - public Server getServer() { - return this.server; - } - - @Override - public String getScheme() { - return this.server.getScheme(); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("RibbonServer{"); - sb.append("serviceId='").append(serviceId).append('\''); - sb.append(", server=").append(server); - sb.append(", secure=").append(secure); - sb.append(", metadata=").append(metadata); - sb.append('}'); - return sb.toString(); - } - } - -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerContext.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerContext.java deleted file mode 100644 index 72eb2471..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerContext.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.LoadBalancerContext; -import com.netflix.loadbalancer.ServerStats; -import com.netflix.servo.monitor.Timer; - -/** - * @author Spencer Gibb - */ -public class RibbonLoadBalancerContext extends LoadBalancerContext { - public RibbonLoadBalancerContext(ILoadBalancer lb) { - super(lb); - } - - public RibbonLoadBalancerContext(ILoadBalancer lb, IClientConfig clientConfig) { - super(lb, clientConfig); - } - - public RibbonLoadBalancerContext(ILoadBalancer lb, IClientConfig clientConfig, - RetryHandler handler) { - super(lb, clientConfig, handler); - } - - @Override - public void noteOpenConnection(ServerStats serverStats) { - super.noteOpenConnection(serverStats); - } - - @Override - public Timer getExecuteTracer() { - return super.getExecuteTracer(); - } - - @Override - public void noteRequestCompletion(ServerStats stats, Object response, Throwable e, - long responseTime) { - super.noteRequestCompletion(stats, response, e, responseTime); - } - - @Override - public void noteRequestCompletion(ServerStats stats, Object response, Throwable e, - long responseTime, RetryHandler errorHandler) { - super.noteRequestCompletion(stats, response, e, responseTime, errorHandler); - } - -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonProperties.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonProperties.java deleted file mode 100644 index 5a3873b7..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonProperties.java +++ /dev/null @@ -1,187 +0,0 @@ -package org.springframework.cloud.netflix.ribbon; - -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.IClientConfig; -import com.netflix.client.config.IClientConfigKey; - -import java.util.concurrent.TimeUnit; - -import static com.netflix.client.config.CommonClientConfigKey.PoolKeepAliveTime; -import static com.netflix.client.config.CommonClientConfigKey.PoolKeepAliveTimeUnits; -import static com.netflix.client.config.CommonClientConfigKey.Port; -import static com.netflix.client.config.CommonClientConfigKey.SecurePort; -import static com.netflix.client.config.DefaultClientConfigImpl.DEFAULT_CONNECTION_IDLE_TIMERTASK_REPEAT_IN_MSECS; -import static com.netflix.client.config.DefaultClientConfigImpl.DEFAULT_CONNECT_TIMEOUT; -import static com.netflix.client.config.DefaultClientConfigImpl.DEFAULT_FOLLOW_REDIRECTS; -import static com.netflix.client.config.DefaultClientConfigImpl.DEFAULT_MAX_CONNECTIONS_PER_HOST; -import static com.netflix.client.config.DefaultClientConfigImpl.DEFAULT_MAX_TOTAL_CONNECTIONS; -import static com.netflix.client.config.DefaultClientConfigImpl.DEFAULT_OK_TO_RETRY_ON_ALL_OPERATIONS; -import static com.netflix.client.config.DefaultClientConfigImpl.DEFAULT_POOL_KEEP_ALIVE_TIME; -import static com.netflix.client.config.DefaultClientConfigImpl.DEFAULT_POOL_KEEP_ALIVE_TIME_UNITS; -import static com.netflix.client.config.DefaultClientConfigImpl.DEFAULT_PORT; -import static com.netflix.client.config.DefaultClientConfigImpl.DEFAULT_READ_TIMEOUT; - -public class RibbonProperties { - private final IClientConfig config; - - public static RibbonProperties from(IClientConfig config) { - return new RibbonProperties(config); - } - - RibbonProperties(IClientConfig config) { - this.config = config; - } - - public Integer getConnectionCleanerRepeatInterval() { - return get(CommonClientConfigKey.ConnectionCleanerRepeatInterval); - } - - public int connectionCleanerRepeatInterval() { - return get(CommonClientConfigKey.ConnectionCleanerRepeatInterval, - DEFAULT_CONNECTION_IDLE_TIMERTASK_REPEAT_IN_MSECS); - } - - public Integer getConnectTimeout() { - return get(CommonClientConfigKey.ConnectTimeout); - } - - public int connectTimeout() { - return connectTimeout(DEFAULT_CONNECT_TIMEOUT); - } - - public int connectTimeout(int defaultValue) { - return get(CommonClientConfigKey.ConnectTimeout, defaultValue); - } - - public Boolean getFollowRedirects() { - return get(CommonClientConfigKey.FollowRedirects); - } - - public boolean isFollowRedirects() { - return isFollowRedirects(DEFAULT_FOLLOW_REDIRECTS); - } - - public boolean isFollowRedirects(boolean defaultValue) { - return get(CommonClientConfigKey.FollowRedirects, defaultValue); - } - - public Integer getMaxConnectionsPerHost() { - return get(CommonClientConfigKey.MaxConnectionsPerHost); - } - - public int maxConnectionsPerHost() { - return maxConnectionsPerHost(DEFAULT_MAX_CONNECTIONS_PER_HOST); - } - - public int maxConnectionsPerHost(int defaultValue) { - return get(CommonClientConfigKey.MaxConnectionsPerHost, defaultValue); - } - - public Integer getMaxTotalConnections() { - return get(CommonClientConfigKey.MaxTotalConnections); - } - - public int maxTotalConnections() { - return maxTotalConnections(DEFAULT_MAX_TOTAL_CONNECTIONS); - } - - public int maxTotalConnections(int defaultValue) { - return get(CommonClientConfigKey.MaxTotalConnections, defaultValue); - } - - public Boolean getOkToRetryOnAllOperations() { - return get(CommonClientConfigKey.OkToRetryOnAllOperations); - } - - public boolean isOkToRetryOnAllOperations() { - return get(CommonClientConfigKey.OkToRetryOnAllOperations, - DEFAULT_OK_TO_RETRY_ON_ALL_OPERATIONS); - } - - @SuppressWarnings("deprecation") - public Long getPoolKeepAliveTime() { - Object property = this.config.getProperty(PoolKeepAliveTime); - if (property instanceof Long) { - return (Long) property; - } - return null; - } - - @SuppressWarnings("deprecation") - public long poolKeepAliveTime() { - Object property = this.config.getProperty(PoolKeepAliveTime); - if (property instanceof Long) { - return (Long) property; - } - return DEFAULT_POOL_KEEP_ALIVE_TIME; - } - - @SuppressWarnings("deprecation") - public TimeUnit getPoolKeepAliveTimeUnits() { - Object property = this.config.getProperty(PoolKeepAliveTimeUnits); - if (property instanceof TimeUnit) { - return (TimeUnit) property; - } - return DEFAULT_POOL_KEEP_ALIVE_TIME_UNITS; - } - - public Integer getPort() { - return get(Port); - } - - public int port() { - return get(Port, DEFAULT_PORT); - } - - public Integer getReadTimeout() { - return get(CommonClientConfigKey.ReadTimeout); - } - - public int readTimeout() { - return readTimeout(DEFAULT_READ_TIMEOUT); - } - - public int readTimeout(int defaultValue) { - return get(CommonClientConfigKey.ReadTimeout, defaultValue); - } - - public Boolean getSecure() { - return get(CommonClientConfigKey.IsSecure); - } - - public boolean isSecure() { - return isSecure(false); - } - - public boolean isSecure(boolean defaultValue) { - return get(CommonClientConfigKey.IsSecure, defaultValue); - } - - public Integer getSecurePort() { - return this.config.get(SecurePort); - } - - public Boolean getUseIPAddrForServer() { - return get(CommonClientConfigKey.UseIPAddrForServer); - } - - public boolean isUseIPAddrForServer() { - return isUseIPAddrForServer(false); - } - - public boolean isUseIPAddrForServer(boolean defaultValue) { - return get(CommonClientConfigKey.UseIPAddrForServer, defaultValue); - } - - public boolean has(IClientConfigKey key) { - return this.config.containsProperty(key); - } - - public T get(IClientConfigKey key) { - return this.config.get(key); - } - - public T get(IClientConfigKey key, T defaultValue) { - return this.config.get(key, defaultValue); - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonStatsRecorder.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonStatsRecorder.java deleted file mode 100644 index 4f01100f..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonStatsRecorder.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.springframework.cloud.netflix.ribbon; - -import java.util.concurrent.TimeUnit; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerStats; -import com.netflix.servo.monitor.Stopwatch; - -/** - * @author Spencer Gibb - */ -public class RibbonStatsRecorder { - - private RibbonLoadBalancerContext context; - private ServerStats serverStats; - private Stopwatch tracer; - - public RibbonStatsRecorder(RibbonLoadBalancerContext context, Server server) { - this.context = context; - if (server != null) { - serverStats = context.getServerStats(server); - context.noteOpenConnection(serverStats); - tracer = context.getExecuteTracer().start(); - } - } - - public void recordStats(Object entity) { - this.recordStats(entity, null); - } - - public void recordStats(Throwable t) { - this.recordStats(null, t); - } - - protected void recordStats(Object entity, Throwable exception) { - if (this.tracer != null && this.serverStats != null) { - this.tracer.stop(); - long duration = this.tracer.getDuration(TimeUnit.MILLISECONDS); - this.context.noteRequestCompletion(serverStats, entity, exception, duration, null/* errorHandler */); - } - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonUtils.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonUtils.java deleted file mode 100644 index beda5ce6..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonUtils.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.springframework.cloud.netflix.ribbon; - -import java.net.URI; - -import org.springframework.util.StringUtils; -import org.springframework.web.util.UriComponentsBuilder; -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.IClientConfig; -import com.netflix.config.ConfigurationManager; -import com.netflix.config.DynamicPropertyFactory; -import com.netflix.config.DynamicStringProperty; -import com.netflix.loadbalancer.Server; - -import java.util.HashMap; -import java.util.Map; - -import static com.netflix.client.config.CommonClientConfigKey.DeploymentContextBasedVipAddresses; -import static com.netflix.client.config.CommonClientConfigKey.EnableZoneAffinity; - -/** - * @author Spencer Gibb - * @author Jacques-Etienne Beaudet - * @author Tim Ysewyn - */ -public class RibbonUtils { - - public static final String VALUE_NOT_SET = "__not__set__"; - public static final String DEFAULT_NAMESPACE = "ribbon"; - - private static final Map unsecureSchemeMapping; - static - { - unsecureSchemeMapping = new HashMap<>(); - unsecureSchemeMapping.put("http", "https"); - unsecureSchemeMapping.put("ws", "wss"); - } - - public static void initializeRibbonDefaults(String serviceId) { - setRibbonProperty(serviceId, DeploymentContextBasedVipAddresses.key(), - serviceId); - setRibbonProperty(serviceId, EnableZoneAffinity.key(), "true"); - } - - public static void setRibbonProperty(String serviceId, String suffix, String value) { - // how to set the namespace properly? - String key = getRibbonKey(serviceId, suffix); - DynamicStringProperty property = getProperty(key); - if (property.get().equals(VALUE_NOT_SET)) { - ConfigurationManager.getConfigInstance().setProperty(key, value); - } - } - - public static String getRibbonKey(String serviceId, String suffix) { - return serviceId + "." + DEFAULT_NAMESPACE + "." + suffix; - } - - public static DynamicStringProperty getProperty(String key) { - return DynamicPropertyFactory.getInstance().getStringProperty(key, VALUE_NOT_SET); - } - - /** - * Determine if client is secure. If the supplied {@link IClientConfig} has the {@link CommonClientConfigKey#IsSecure} - * set, return that value. Otherwise, query the supplied {@link ServerIntrospector}. - * @param config the supplied client configuration. - * @param serverIntrospector - * @param server - * @return true if the client is secure - */ - public static boolean isSecure(IClientConfig config, ServerIntrospector serverIntrospector, Server server) { - if (config != null) { - Boolean isSecure = config.get(CommonClientConfigKey.IsSecure); - if (isSecure != null) { - return isSecure; - } - } - - return serverIntrospector.isSecure(server); - } - - /** - * Replace the scheme to https if needed. If the uri doesn't start with https and - * {@link #isSecure(IClientConfig, ServerIntrospector, Server)} is true, update the scheme. - * This assumes the uri is already encoded to avoid double encoding. - * - * @param uri - * @param config - * @param serverIntrospector - * @param server - * @return - * - * @deprecated use {@link #updateToSecureConnectionIfNeeded} - */ - public static URI updateToHttpsIfNeeded(URI uri, IClientConfig config, ServerIntrospector serverIntrospector, - Server server) { - return updateToSecureConnectionIfNeeded(uri, config, serverIntrospector, server); - } - - /** - * Replace the scheme to the secure variant if needed. If the {@link #unsecureSchemeMapping} map contains the uri - * scheme and {@link #isSecure(IClientConfig, ServerIntrospector, Server)} is true, update the scheme. - * This assumes the uri is already encoded to avoid double encoding. - * - * @param uri - * @param config - * @param serverIntrospector - * @param server - * @return - */ - public static URI updateToSecureConnectionIfNeeded(URI uri, IClientConfig config, - ServerIntrospector serverIntrospector, Server server) { - String scheme = uri.getScheme(); - - if (StringUtils.isEmpty(scheme)) { - scheme = "http"; - } - - if (!StringUtils.isEmpty(uri.toString()) - && unsecureSchemeMapping.containsKey(scheme) - && isSecure(config, serverIntrospector, server)) { - return upgradeConnection(uri, unsecureSchemeMapping.get(scheme)); - } - return uri; - } - - private static URI upgradeConnection(URI uri, String scheme) { - UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUri(uri).scheme(scheme); - if (uri.getRawQuery() != null) { - // When building the URI, UriComponentsBuilder verify the allowed characters and does not - // support the '+' so we replace it for its equivalent '%20'. - // See issue https://jira.spring.io/browse/SPR-10172 - uriComponentsBuilder.replaceQuery(uri.getRawQuery().replace("+", "%20")); - } - return uriComponentsBuilder.build(true).toUri(); - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospector.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospector.java deleted file mode 100644 index d6364178..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospector.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.util.Map; -import com.netflix.loadbalancer.Server; - -/** - * @author Spencer Gibb - */ -public interface ServerIntrospector { - - boolean isSecure(Server server); - - Map getMetadata(Server server); -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospectorProperties.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospectorProperties.java deleted file mode 100644 index ce863345..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospectorProperties.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * @author Rico Pahlisch - * @author Gregor Zurowski - */ -@ConfigurationProperties("ribbon") -public class ServerIntrospectorProperties { - - private List securePorts = Arrays.asList(443,8443); - - public List getSecurePorts() { - return securePorts; - } - - public void setSecurePorts(List securePorts) { - this.securePorts = securePorts; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ServerIntrospectorProperties that = (ServerIntrospectorProperties) o; - return Objects.equals(securePorts, that.securePorts); - } - - @Override - public int hashCode() { - return Objects.hash(securePorts); - } - - @Override - public String toString() { - return new StringBuilder("ServerIntrospectorProperties{") - .append("securePorts=").append(securePorts) - .append("}").toString(); - } - -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/SpringClientFactory.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/SpringClientFactory.java deleted file mode 100644 index d2340874..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/SpringClientFactory.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.lang.reflect.Constructor; -import org.springframework.beans.BeanUtils; -import org.springframework.cloud.context.named.NamedContextFactory; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import com.netflix.client.IClient; -import com.netflix.client.IClientConfigAware; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ILoadBalancer; - -/** - * A factory that creates client, load balancer and client configuration instances. It - * 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 extends NamedContextFactory { - - static final String NAMESPACE = "ribbon"; - - public SpringClientFactory() { - super(RibbonClientConfiguration.class, NAMESPACE, "ribbon.client.name"); - } - - /** - * Get the rest client associated with the name. - * @throws RuntimeException if any error occurs - */ - public > C getClient(String name, Class clientClass) { - return getInstance(name, clientClass); - } - - /** - * Get the load balancer associated with the name. - * @throws RuntimeException if any error occurs - */ - public ILoadBalancer getLoadBalancer(String name) { - return getInstance(name, ILoadBalancer.class); - } - - /** - * Get the client config associated with the name. - * @throws RuntimeException if any error occurs - */ - public IClientConfig getClientConfig(String name) { - return getInstance(name, IClientConfig.class); - } - - /** - * Get the load balancer context associated with the name. - * @throws RuntimeException if any error occurs - */ - public RibbonLoadBalancerContext getLoadBalancerContext(String serviceId) { - return getInstance(serviceId, RibbonLoadBalancerContext.class); - } - - static C instantiateWithConfig(Class clazz, IClientConfig config) { - return instantiateWithConfig(null, clazz, config); - } - - static C instantiateWithConfig(AnnotationConfigApplicationContext context, - Class clazz, IClientConfig config) { - C result = null; - - try { - Constructor constructor = clazz.getConstructor(IClientConfig.class); - result = constructor.newInstance(config); - } catch (Throwable e) { - // Ignored - } - - if (result == null) { - result = BeanUtils.instantiate(clazz); - - if (result instanceof IClientConfigAware) { - ((IClientConfigAware) result).initWithNiwsConfig(config); - } - - if (context != null) { - context.getAutowireCapableBeanFactory().autowireBean(result); - } - } - - return result; - } - - @Override - public C getInstance(String name, Class type) { - C instance = super.getInstance(name, type); - if (instance != null) { - return instance; - } - IClientConfig config = getInstance(name, IClientConfig.class); - return instantiateWithConfig(getContext(name), type, config); - } - - @Override - protected AnnotationConfigApplicationContext getContext(String name) { - return super.getContext(name); - } - -} - diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/StaticServerList.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/StaticServerList.java deleted file mode 100644 index 959e3f8c..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/StaticServerList.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.util.Arrays; -import java.util.List; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; - -/** - * @author Spencer Gibb - */ -public class StaticServerList implements ServerList { - - private final List servers; - - public StaticServerList(T... servers) { - this.servers = Arrays.asList(servers); - } - - @Override - public List getInitialListOfServers() { - return servers; - } - - @Override - public List getUpdatedListOfServers() { - return servers; - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilter.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilter.java deleted file mode 100644 index b0defeaa..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilter.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import com.netflix.client.config.IClientConfig; -import com.netflix.config.ConfigurationManager; -import com.netflix.config.DeploymentContext.ContextKey; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAffinityServerListFilter; - -/** - * A filter that actively prefers the local zone (as defined by the deployment context, or - * the Eureka instance metadata). - * - * @author Dave Syer - */ -public class ZonePreferenceServerListFilter extends ZoneAffinityServerListFilter { - - private String zone; - - @Override - public void initWithNiwsConfig(IClientConfig niwsClientConfig) { - super.initWithNiwsConfig(niwsClientConfig); - if (ConfigurationManager.getDeploymentContext() != null) { - this.zone = ConfigurationManager.getDeploymentContext().getValue( - ContextKey.zone); - } - } - - @Override - public List getFilteredListOfServers(List servers) { - List output = super.getFilteredListOfServers(servers); - if (this.zone != null && output.size() == servers.size()) { - List local = new ArrayList<>(); - for (Server server : output) { - if (this.zone.equalsIgnoreCase(server.getZone())) { - local.add(server); - } - } - if (!local.isEmpty()) { - return local; - } - } - return output; - } - - public String getZone() { - return zone; - } - - public void setZone(String zone) { - this.zone = zone; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ZonePreferenceServerListFilter that = (ZonePreferenceServerListFilter) o; - return Objects.equals(zone, that.zone); - } - - @Override - public int hashCode() { - return Objects.hash(zone); - } - - @Override - public String toString() { - return new StringBuilder("ZonePreferenceServerListFilter{") - .append("zone='").append(zone).append("'") - .append("}").toString(); - } - -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientRibbonConfiguration.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientRibbonConfiguration.java deleted file mode 100644 index f05ac558..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientRibbonConfiguration.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon.apache; - -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.TimeUnit; - -import javax.annotation.PreDestroy; - -import org.apache.http.client.config.RequestConfig; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.HttpClientConnectionManager; -import org.apache.http.impl.client.CloseableHttpClient; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.client.loadbalancer.LoadBalancedBackOffPolicyFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryListenerFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicyFactory; -import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory; -import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory; -import org.springframework.cloud.netflix.ribbon.RibbonClientName; -import org.springframework.cloud.netflix.ribbon.RibbonProperties; -import org.springframework.cloud.netflix.ribbon.ServerIntrospector; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.netflix.client.AbstractLoadBalancerAwareClient; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.servo.monitor.Monitors; - -/** - * @author Spencer Gibb - */ -@Configuration -@ConditionalOnClass(name = "org.apache.http.client.HttpClient") -@ConditionalOnProperty(name = "ribbon.httpclient.enabled", matchIfMissing = true) -public class HttpClientRibbonConfiguration { - @RibbonClientName - private String name = "client"; - - @Configuration - protected static class ApacheHttpClientConfiguration { - private final Timer connectionManagerTimer = new Timer( - "RibbonApacheHttpClientConfiguration.connectionManagerTimer", true); - private CloseableHttpClient httpClient; - - @Autowired(required = false) - private RegistryBuilder registryBuilder; - - @Bean - @ConditionalOnMissingBean(HttpClientConnectionManager.class) - public HttpClientConnectionManager httpClientConnectionManager( - IClientConfig config, - ApacheHttpClientConnectionManagerFactory connectionManagerFactory) { - RibbonProperties ribbon = RibbonProperties.from(config); - int maxTotalConnections = ribbon.maxTotalConnections(); - int maxConnectionsPerHost = ribbon.maxConnectionsPerHost(); - int timerRepeat = ribbon.connectionCleanerRepeatInterval(); - long timeToLive = ribbon.poolKeepAliveTime(); - TimeUnit ttlUnit = ribbon.getPoolKeepAliveTimeUnits(); - final HttpClientConnectionManager connectionManager = connectionManagerFactory - .newConnectionManager(false, maxTotalConnections, - maxConnectionsPerHost, timeToLive, ttlUnit, registryBuilder); - this.connectionManagerTimer.schedule(new TimerTask() { - @Override - public void run() { - connectionManager.closeExpiredConnections(); - } - }, 30000, timerRepeat); - return connectionManager; - } - - @Bean - @ConditionalOnMissingBean(CloseableHttpClient.class) - public CloseableHttpClient httpClient(ApacheHttpClientFactory httpClientFactory, - HttpClientConnectionManager connectionManager, IClientConfig config) { - RibbonProperties ribbon = RibbonProperties.from(config); - Boolean followRedirects = ribbon.isFollowRedirects(); - Integer connectTimeout = ribbon.connectTimeout(); - RequestConfig defaultRequestConfig = RequestConfig.custom() - .setConnectTimeout(connectTimeout) - .setRedirectsEnabled(followRedirects).build(); - this.httpClient = httpClientFactory.createBuilder(). - setDefaultRequestConfig(defaultRequestConfig). - setConnectionManager(connectionManager).build(); - return httpClient; - } - - @PreDestroy - public void destroy() throws Exception { - connectionManagerTimer.cancel(); - if(httpClient != null) { - httpClient.close(); - } - } - } - - @Bean - @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class) - @ConditionalOnMissingClass(value = "org.springframework.retry.support.RetryTemplate") - public RibbonLoadBalancingHttpClient ribbonLoadBalancingHttpClient( - IClientConfig config, ServerIntrospector serverIntrospector, - ILoadBalancer loadBalancer, RetryHandler retryHandler, CloseableHttpClient httpClient) { - RibbonLoadBalancingHttpClient client = new RibbonLoadBalancingHttpClient(httpClient, config, serverIntrospector); - client.setLoadBalancer(loadBalancer); - client.setRetryHandler(retryHandler); - Monitors.registerObject("Client_" + this.name, client); - return client; - } - - @Bean - @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class) - @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate") - public RetryableRibbonLoadBalancingHttpClient retryableRibbonLoadBalancingHttpClient( - IClientConfig config, ServerIntrospector serverIntrospector, - ILoadBalancer loadBalancer, RetryHandler retryHandler, - LoadBalancedRetryPolicyFactory loadBalancedRetryPolicyFactory, CloseableHttpClient httpClient, - LoadBalancedBackOffPolicyFactory loadBalancedBackOffPolicyFactory, - LoadBalancedRetryListenerFactory loadBalancedRetryListenerFactory) { - RetryableRibbonLoadBalancingHttpClient client = new RetryableRibbonLoadBalancingHttpClient( - httpClient, config, serverIntrospector, loadBalancedRetryPolicyFactory, - loadBalancedBackOffPolicyFactory, loadBalancedRetryListenerFactory); - client.setLoadBalancer(loadBalancer); - client.setRetryHandler(retryHandler); - Monitors.registerObject("Client_" + this.name, client); - return client; - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RetryableRibbonLoadBalancingHttpClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RetryableRibbonLoadBalancingHttpClient.java deleted file mode 100644 index 75d30101..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RetryableRibbonLoadBalancingHttpClient.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.cloud.netflix.ribbon.apache; - -import java.io.IOException; -import org.apache.commons.lang.BooleanUtils; -import org.apache.http.HttpResponse; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.impl.client.CloseableHttpClient; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.loadbalancer.LoadBalancedBackOffPolicyFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryListenerFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicyFactory; -import org.springframework.cloud.client.loadbalancer.RetryableStatusCodeException; -import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser; -import org.springframework.cloud.netflix.ribbon.RibbonProperties; -import org.springframework.cloud.netflix.ribbon.support.RibbonRetryPolicy; -import org.springframework.http.HttpRequest; -import org.springframework.retry.RetryCallback; -import org.springframework.retry.RetryListener; -import org.springframework.retry.backoff.BackOffPolicy; -import org.springframework.retry.backoff.NoBackOffPolicy; -import org.springframework.retry.policy.NeverRetryPolicy; -import org.springframework.retry.support.RetryTemplate; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient; -import org.springframework.cloud.netflix.ribbon.ServerIntrospector; -import org.springframework.web.util.UriComponentsBuilder; -import com.netflix.client.RequestSpecificRetryHandler; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.Server; - -/** - * An Apache HTTP client which leverages Spring Retry to retry failed requests. - * @author Ryan Baxter - * @author Gang Li - */ -public class RetryableRibbonLoadBalancingHttpClient extends RibbonLoadBalancingHttpClient - implements ServiceInstanceChooser { - private LoadBalancedRetryPolicyFactory loadBalancedRetryPolicyFactory = new LoadBalancedRetryPolicyFactory.NeverRetryFactory(); - private LoadBalancedBackOffPolicyFactory loadBalancedBackOffPolicyFactory = - new LoadBalancedBackOffPolicyFactory.NoBackOffPolicyFactory(); - private LoadBalancedRetryListenerFactory loadBalancedRetryListenerFactory = - new LoadBalancedRetryListenerFactory.DefaultRetryListenerFactory(); - - @Deprecated - //TODO remove in 2.0.x - public RetryableRibbonLoadBalancingHttpClient(IClientConfig config, - ServerIntrospector serverIntrospector, - LoadBalancedRetryPolicyFactory loadBalancedRetryPolicyFactory) { - super(config, serverIntrospector); - this.loadBalancedRetryPolicyFactory = loadBalancedRetryPolicyFactory; - } - - @Deprecated - //TODO remove in 2.0.x - public RetryableRibbonLoadBalancingHttpClient(CloseableHttpClient delegate, - IClientConfig config, ServerIntrospector serverIntrospector, - LoadBalancedRetryPolicyFactory loadBalancedRetryPolicyFactory) { - super(delegate, config, serverIntrospector); - this.loadBalancedRetryPolicyFactory = loadBalancedRetryPolicyFactory; - } - - @Deprecated - //TODO remove in 2.0.x - public RetryableRibbonLoadBalancingHttpClient(CloseableHttpClient delegate, - IClientConfig config, ServerIntrospector serverIntrospector, - LoadBalancedRetryPolicyFactory loadBalancedRetryPolicyFactory, - LoadBalancedBackOffPolicyFactory loadBalancedBackOffPolicyFactory) { - super(delegate, config, serverIntrospector); - this.loadBalancedRetryPolicyFactory = loadBalancedRetryPolicyFactory; - this.loadBalancedBackOffPolicyFactory = loadBalancedBackOffPolicyFactory; - } - - public RetryableRibbonLoadBalancingHttpClient(CloseableHttpClient delegate, - IClientConfig config, ServerIntrospector serverIntrospector, - LoadBalancedRetryPolicyFactory loadBalancedRetryPolicyFactory, - LoadBalancedBackOffPolicyFactory loadBalancedBackOffPolicyFactory, - LoadBalancedRetryListenerFactory loadBalancedRetryListenerFactory) { - super(delegate, config, serverIntrospector); - this.loadBalancedRetryPolicyFactory = loadBalancedRetryPolicyFactory; - this.loadBalancedBackOffPolicyFactory = loadBalancedBackOffPolicyFactory; - this.loadBalancedRetryListenerFactory = loadBalancedRetryListenerFactory; - } - - @Override - public RibbonApacheHttpResponse execute(final RibbonApacheHttpRequest request, final IClientConfig configOverride) throws Exception { - final RequestConfig.Builder builder = RequestConfig.custom(); - IClientConfig config = configOverride != null ? configOverride : this.config; - RibbonProperties ribbon = RibbonProperties.from(config); - builder.setConnectTimeout(ribbon.connectTimeout(this.connectTimeout)); - builder.setSocketTimeout(ribbon.readTimeout(this.readTimeout)); - builder.setRedirectsEnabled(ribbon.isFollowRedirects(this.followRedirects)); - - final RequestConfig requestConfig = builder.build(); - final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryPolicyFactory.create(this.getClientName(), this); - RetryCallback retryCallback = context -> { - //on retries the policy will choose the server and set it in the context - //extract the server and update the request being made - RibbonApacheHttpRequest newRequest = request; - if(context instanceof LoadBalancedRetryContext) { - ServiceInstance service = ((LoadBalancedRetryContext)context).getServiceInstance(); - if(service != null) { - //Reconstruct the request URI using the host and port set in the retry context - newRequest = newRequest.withNewUri(UriComponentsBuilder.newInstance().host(service.getHost()) - .scheme(service.getUri().getScheme()).userInfo(newRequest.getURI().getUserInfo()) - .port(service.getPort()).path(newRequest.getURI().getPath()) - .query(newRequest.getURI().getQuery()).fragment(newRequest.getURI().getFragment()) - .build().encode().toUri()); - } - } - newRequest = getSecureRequest(newRequest, configOverride); - HttpUriRequest httpUriRequest = newRequest.toRequest(requestConfig); - final HttpResponse httpResponse = RetryableRibbonLoadBalancingHttpClient.this.delegate.execute(httpUriRequest); - if(retryPolicy.retryableStatusCode(httpResponse.getStatusLine().getStatusCode())) { - if(CloseableHttpResponse.class.isInstance(httpResponse)) { - ((CloseableHttpResponse)httpResponse).close(); - } - throw new RetryableStatusCodeException(RetryableRibbonLoadBalancingHttpClient.this.clientName, - httpResponse.getStatusLine().getStatusCode()); - } - return new RibbonApacheHttpResponse(httpResponse, httpUriRequest.getURI()); - }; - return this.executeWithRetry(request, retryPolicy, retryCallback); - } - - private RibbonApacheHttpResponse executeWithRetry(RibbonApacheHttpRequest request, LoadBalancedRetryPolicy retryPolicy, RetryCallback callback) throws Exception { - RetryTemplate retryTemplate = new RetryTemplate(); - boolean retryable = request.getContext() == null ? true : - BooleanUtils.toBooleanDefaultIfNull(request.getContext().getRetryable(), true); - retryTemplate.setRetryPolicy(retryPolicy == null || !retryable ? new NeverRetryPolicy() - : new RetryPolicy(request, retryPolicy, this, this.getClientName())); - BackOffPolicy backOffPolicy = loadBalancedBackOffPolicyFactory.createBackOffPolicy(this.getClientName()); - retryTemplate.setBackOffPolicy(backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy); - RetryListener[] retryListeners = this.loadBalancedRetryListenerFactory.createRetryListeners(this.getClientName()); - if (retryListeners != null && retryListeners.length != 0) { - retryTemplate.setListeners(retryListeners); - } - return retryTemplate.execute(callback); - } - - @Override - public ServiceInstance choose(String serviceId) { - Server server = this.getLoadBalancer().chooseServer(serviceId); - return new RibbonLoadBalancerClient.RibbonServer(serviceId, server); - } - - @Override - public RequestSpecificRetryHandler getRequestSpecificRetryHandler(RibbonApacheHttpRequest request, IClientConfig requestConfig) { - return new RequestSpecificRetryHandler(false, false, RetryHandler.DEFAULT, null); - } - - static class RetryPolicy extends RibbonRetryPolicy { - public RetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy, ServiceInstanceChooser serviceInstanceChooser, String serviceName) { - super(request, policy, serviceInstanceChooser, serviceName); - } - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequest.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequest.java deleted file mode 100644 index ed11f8f6..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.apache; - -import java.net.URI; -import java.util.List; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.methods.RequestBuilder; -import org.apache.http.entity.BasicHttpEntity; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.ribbon.support.ContextAwareRequest; - -import static org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer.Runner.customize; - -/** - * @author Christian Lohmann - */ -public class RibbonApacheHttpRequest extends ContextAwareRequest implements Cloneable { - - public RibbonApacheHttpRequest(RibbonCommandContext context) { - super(context); - } - - public HttpUriRequest toRequest(final RequestConfig requestConfig) { - final RequestBuilder builder = RequestBuilder.create(this.context.getMethod()); - builder.setUri(this.uri); - for (final String name : this.context.getHeaders().keySet()) { - final List values = this.context.getHeaders().get(name); - for (final String value : values) { - builder.addHeader(name, value); - } - } - - for (final String name : this.context.getParams().keySet()) { - final List values = this.context.getParams().get(name); - for (final String value : values) { - builder.addParameter(name, value); - } - } - - if (this.context.getRequestEntity() != null) { - final BasicHttpEntity entity; - entity = new BasicHttpEntity(); - entity.setContent(this.context.getRequestEntity()); - // if the entity contentLength isn't set, transfer-encoding will be set - // to chunked in org.apache.http.protocol.RequestContent. See gh-1042 - Long contentLength = this.context.getContentLength(); - if ("GET".equals(this.context.getMethod()) && (contentLength == null || contentLength < 0)) { - entity.setContentLength(0); - } else if (contentLength != null) { - entity.setContentLength(contentLength); - } - builder.setEntity(entity); - } - - customize(this.context.getRequestCustomizers(), builder); - - builder.setConfig(requestConfig); - return builder.build(); - } - - public RibbonApacheHttpRequest withNewUri(URI uri) { - return new RibbonApacheHttpRequest(newContext(uri)); - } - -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponse.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponse.java deleted file mode 100644 index 689fff08..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponse.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.apache; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Type; -import java.net.URI; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.http.Header; -import org.apache.http.HttpResponse; -import org.springframework.http.HttpStatus; -import org.springframework.util.Assert; -import com.google.common.reflect.TypeToken; -import com.netflix.client.ClientException; -import com.netflix.client.http.CaseInsensitiveMultiMap; -import com.netflix.client.http.HttpHeaders; - -/** - * @author Christian Lohmann - */ -public class RibbonApacheHttpResponse implements com.netflix.client.http.HttpResponse { - - private HttpResponse httpResponse; - private URI uri; - - public RibbonApacheHttpResponse(final HttpResponse httpResponse, final URI uri) { - Assert.notNull(httpResponse, "httpResponse can not be null"); - this.httpResponse = httpResponse; - this.uri = uri; - } - - @Override - public Object getPayload() throws ClientException { - try { - if (!hasPayload()) { - return null; - } - return this.httpResponse.getEntity().getContent(); - } - catch (final IOException e) { - throw new ClientException(e.getMessage(), e); - } - } - - @Override - public boolean hasPayload() { - return this.httpResponse.getEntity() != null; - } - - @Override - public boolean isSuccess() { - return HttpStatus.valueOf(this.httpResponse.getStatusLine().getStatusCode()).is2xxSuccessful(); - } - - @Override - public URI getRequestedURI() { - return this.uri; - } - - public int getStatus() { - return httpResponse.getStatusLine().getStatusCode(); - } - - public String getStatusLine() { - return httpResponse.getStatusLine().toString(); - } - - @Override - public Map> getHeaders() { - final Map> headers = new HashMap<>(); - for (final Header header : this.httpResponse.getAllHeaders()) { - if (headers.containsKey(header.getName())) { - headers.get(header.getName()).add(header.getValue()); - } - else { - final List values = new ArrayList<>(); - values.add(header.getValue()); - headers.put(header.getName(), values); - } - } - - return headers; - } - - @Override - public HttpHeaders getHttpHeaders() { - final CaseInsensitiveMultiMap headers = new CaseInsensitiveMultiMap(); - for (final Header header : httpResponse.getAllHeaders()) { - headers.addHeader(header.getName(), header.getValue()); - } - - return headers; - } - - @Override - public void close() { - if (this.httpResponse != null && this.httpResponse.getEntity() != null) { - try { - this.httpResponse.getEntity().getContent().close(); - } - catch (final IOException e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - } - - @Override - public InputStream getInputStream() { - try { - if (!hasPayload()) { - return null; - } - return this.httpResponse.getEntity().getContent(); - } - catch (final IOException e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - @Override - public boolean hasEntity() { - return hasPayload(); - } - - /** - * Not used - */ - @Override - public T getEntity(final Class type) throws Exception { - return null; - } - - /** - * Not used - */ - @Override - public T getEntity(final Type type) throws Exception { - return null; - } - - /** - * Not used - */ - @Override - public T getEntity(final TypeToken type) throws Exception { - return null; - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClient.java deleted file mode 100644 index faa156a0..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClient.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.apache; - -import java.net.URI; - -import org.apache.http.HttpResponse; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.springframework.cloud.netflix.ribbon.RibbonProperties; -import org.springframework.cloud.netflix.ribbon.ServerIntrospector; -import org.springframework.cloud.netflix.ribbon.support.AbstractLoadBalancingClient; -import org.springframework.web.util.UriComponentsBuilder; - -import com.netflix.client.RequestSpecificRetryHandler; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.Server; - -import static org.springframework.cloud.netflix.ribbon.RibbonUtils.updateToSecureConnectionIfNeeded; - -/** - * @author Christian Lohmann - * @author Ryan Baxter - * @author Tim Ysewyn - */ -// TODO: rename (ie new class that extends this in Dalston) to ApacheHttpLoadBalancingClient -public class RibbonLoadBalancingHttpClient extends - AbstractLoadBalancingClient { - - public RibbonLoadBalancingHttpClient(IClientConfig config, - ServerIntrospector serverIntrospector) { - super(config, serverIntrospector); - } - - public RibbonLoadBalancingHttpClient(CloseableHttpClient delegate, - IClientConfig config, ServerIntrospector serverIntrospector) { - super(delegate, config, serverIntrospector); - } - - protected CloseableHttpClient createDelegate(IClientConfig config) { - RibbonProperties ribbon = RibbonProperties.from(config); - return HttpClientBuilder.create() - // already defaults to 0 in builder, so resetting to 0 won't hurt - .setMaxConnTotal(ribbon.maxTotalConnections(0)) - // already defaults to 0 in builder, so resetting to 0 won't hurt - .setMaxConnPerRoute(ribbon.maxConnectionsPerHost(0)) - .disableCookieManagement().useSystemProperties() // for proxy - .build(); - } - - @Override - public RibbonApacheHttpResponse execute(RibbonApacheHttpRequest request, - final IClientConfig configOverride) throws Exception { - IClientConfig config = configOverride != null ? configOverride : this.config; - RibbonProperties ribbon = RibbonProperties.from(config); - RequestConfig requestConfig = RequestConfig.custom() - .setConnectTimeout(ribbon.connectTimeout(this.connectTimeout)) - .setSocketTimeout(ribbon.readTimeout(this.readTimeout)) - .setRedirectsEnabled(ribbon.isFollowRedirects(this.followRedirects)) - .build(); - - request = getSecureRequest(request, configOverride); - final HttpUriRequest httpUriRequest = request.toRequest(requestConfig); - final HttpResponse httpResponse = this.delegate.execute(httpUriRequest); - return new RibbonApacheHttpResponse(httpResponse, httpUriRequest.getURI()); - } - - @Override - public URI reconstructURIWithServer(Server server, URI original) { - URI uri = updateToSecureConnectionIfNeeded(original, this.config, this.serverIntrospector, - server); - return super.reconstructURIWithServer(server, uri); - } - - @Override - public RequestSpecificRetryHandler getRequestSpecificRetryHandler( - RibbonApacheHttpRequest request, IClientConfig requestConfig) { - return new RequestSpecificRetryHandler(false, false, RetryHandler.DEFAULT, - requestConfig); - } - - protected RibbonApacheHttpRequest getSecureRequest(RibbonApacheHttpRequest request, IClientConfig configOverride) { - if (isSecure(configOverride)) { - final URI secureUri = UriComponentsBuilder.fromUri(request.getUri()) - .scheme("https").build(true).toUri(); - return request.withNewUri(secureUri); - } - return request; - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClient.java deleted file mode 100644 index b488f8e1..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClient.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.okhttp; - -import java.net.URI; -import java.util.concurrent.TimeUnit; - -import org.springframework.cloud.netflix.ribbon.RibbonProperties; -import org.springframework.cloud.netflix.ribbon.ServerIntrospector; -import org.springframework.cloud.netflix.ribbon.support.AbstractLoadBalancingClient; -import org.springframework.web.util.UriComponentsBuilder; - -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.Server; - -import static org.springframework.cloud.netflix.ribbon.RibbonUtils.updateToSecureConnectionIfNeeded; - -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; - -/** - * @author Spencer Gibb - * @author Ryan Baxter - * @author Tim Ysewyn - */ -public class OkHttpLoadBalancingClient - extends AbstractLoadBalancingClient { - - public OkHttpLoadBalancingClient(IClientConfig config, - ServerIntrospector serverIntrospector) { - super(config, serverIntrospector); - } - - public OkHttpLoadBalancingClient(OkHttpClient delegate, IClientConfig config, - ServerIntrospector serverIntrospector) { - super(delegate, config, serverIntrospector); - } - - @Override - protected OkHttpClient createDelegate(IClientConfig config) { - return new OkHttpClient(); - } - - @Override - public OkHttpRibbonResponse execute(OkHttpRibbonRequest ribbonRequest, - final IClientConfig configOverride) throws Exception { - boolean secure = isSecure(configOverride); - if (secure) { - final URI secureUri = UriComponentsBuilder.fromUri(ribbonRequest.getUri()) - .scheme("https").build().toUri(); - ribbonRequest = ribbonRequest.withNewUri(secureUri); - } - - OkHttpClient httpClient = getOkHttpClient(configOverride, secure); - final Request request = ribbonRequest.toRequest(); - Response response = httpClient.newCall(request).execute(); - return new OkHttpRibbonResponse(response, ribbonRequest.getUri()); - } - - OkHttpClient getOkHttpClient(IClientConfig configOverride, boolean secure) { - IClientConfig config = configOverride != null ? configOverride : this.config; - RibbonProperties ribbon = RibbonProperties.from(config); - OkHttpClient.Builder builder = this.delegate.newBuilder() - .connectTimeout(ribbon.connectTimeout(this.connectTimeout), TimeUnit.MILLISECONDS) - .readTimeout(ribbon.readTimeout(this.readTimeout), TimeUnit.MILLISECONDS) - .followRedirects(ribbon.isFollowRedirects(this.followRedirects)); - if (secure) { - builder.followSslRedirects(ribbon.isFollowRedirects(this.followRedirects)); - } - - return builder.build(); - } - - @Override - public URI reconstructURIWithServer(Server server, URI original) { - URI uri = updateToSecureConnectionIfNeeded(original, this.config, this.serverIntrospector, - server); - return super.reconstructURIWithServer(server, uri); - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonConfiguration.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonConfiguration.java deleted file mode 100644 index d3e5d3fb..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonConfiguration.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon.okhttp; - -import java.util.concurrent.TimeUnit; - -import javax.annotation.PreDestroy; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.client.loadbalancer.LoadBalancedBackOffPolicyFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryListenerFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicyFactory; -import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory; -import org.springframework.cloud.commons.httpclient.OkHttpClientFactory; -import org.springframework.cloud.netflix.ribbon.RibbonClientName; -import org.springframework.cloud.netflix.ribbon.RibbonProperties; -import org.springframework.cloud.netflix.ribbon.ServerIntrospector; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.netflix.client.AbstractLoadBalancerAwareClient; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.servo.monitor.Monitors; - -import okhttp3.ConnectionPool; -import okhttp3.OkHttpClient; - -/** - * @author Spencer Gibb - */ -@Configuration -@ConditionalOnProperty("ribbon.okhttp.enabled") -@ConditionalOnClass(name = "okhttp3.OkHttpClient") -public class OkHttpRibbonConfiguration { - @RibbonClientName - private String name = "client"; - - @Configuration - protected static class OkHttpClientConfiguration { - private OkHttpClient httpClient; - - @Bean - @ConditionalOnMissingBean(ConnectionPool.class) - public ConnectionPool httpClientConnectionPool(IClientConfig config, - OkHttpClientConnectionPoolFactory connectionPoolFactory) { - RibbonProperties ribbon = RibbonProperties.from(config); - int maxTotalConnections = ribbon.maxTotalConnections(); - long timeToLive = ribbon.poolKeepAliveTime(); - TimeUnit ttlUnit = ribbon.getPoolKeepAliveTimeUnits(); - return connectionPoolFactory.create(maxTotalConnections, timeToLive, ttlUnit); - } - - @Bean - @ConditionalOnMissingBean(OkHttpClient.class) - public OkHttpClient client(OkHttpClientFactory httpClientFactory, - ConnectionPool connectionPool, IClientConfig config) { - RibbonProperties ribbon = RibbonProperties.from(config); - this.httpClient = httpClientFactory.createBuilder(false) - .connectTimeout(ribbon.connectTimeout(), TimeUnit.MILLISECONDS) - .readTimeout(ribbon.readTimeout(), TimeUnit.MILLISECONDS) - .followRedirects(ribbon.isFollowRedirects()) - .connectionPool(connectionPool) - .build(); - return this.httpClient; - } - - @PreDestroy - public void destroy() { - if(httpClient != null) { - httpClient.dispatcher().executorService().shutdown(); - httpClient.connectionPool().evictAll(); - } - } - } - - @Bean - @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class) - @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate") - public RetryableOkHttpLoadBalancingClient okHttpLoadBalancingClient( - IClientConfig config, - ServerIntrospector serverIntrospector, - ILoadBalancer loadBalancer, - RetryHandler retryHandler, - LoadBalancedRetryPolicyFactory loadBalancedRetryPolicyFactory, - OkHttpClient delegate, - LoadBalancedBackOffPolicyFactory loadBalancedBackOffPolicyFactory, - LoadBalancedRetryListenerFactory loadBalancedRetryListenerFactory) { - RetryableOkHttpLoadBalancingClient client = new RetryableOkHttpLoadBalancingClient(delegate, config, - serverIntrospector, loadBalancedRetryPolicyFactory, loadBalancedBackOffPolicyFactory, loadBalancedRetryListenerFactory); - client.setLoadBalancer(loadBalancer); - client.setRetryHandler(retryHandler); - Monitors.registerObject("Client_" + this.name, client); - return client; - } - - @Bean - @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class) - @ConditionalOnMissingClass(value = "org.springframework.retry.support.RetryTemplate") - public OkHttpLoadBalancingClient retryableOkHttpLoadBalancingClient( - IClientConfig config, - ServerIntrospector serverIntrospector, ILoadBalancer loadBalancer, - RetryHandler retryHandler, OkHttpClient delegate) { - OkHttpLoadBalancingClient client = new OkHttpLoadBalancingClient(delegate, config, - serverIntrospector); - client.setLoadBalancer(loadBalancer); - client.setRetryHandler(retryHandler); - Monitors.registerObject("Client_" + this.name, client); - return client; - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequest.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequest.java deleted file mode 100644 index 7df4c8a5..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequest.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.okhttp; - -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.MediaType; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.internal.http.HttpMethod; -import okio.BufferedSink; -import okio.Okio; -import okio.Source; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.util.List; -import org.springframework.cloud.netflix.ribbon.support.ContextAwareRequest; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; - -import static org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer.Runner.customize; - -/** - * @author Spencer Gibb - */ -public class OkHttpRibbonRequest extends ContextAwareRequest implements Cloneable { - - public OkHttpRibbonRequest(RibbonCommandContext context) { - super(context); - } - - public Request toRequest() { - Headers.Builder headers = new Headers.Builder(); - for (String name : this.context.getHeaders().keySet()) { - List values = this.context.getHeaders().get(name); - for (String value : values) { - headers.add(name, value); - } - } - - HttpUrl.Builder url = HttpUrl.get(this.uri).newBuilder(); - for (String name : this.context.getParams().keySet()) { - List values = this.context.getParams().get(name); - for (String value : values) { - url.addQueryParameter(name, value); - } - } - - RequestBody requestBody = null; - - if (this.context.getRequestEntity() != null && HttpMethod.permitsRequestBody(this.context.getMethod())) { - MediaType mediaType = null; - if (headers.get("Content-Type") != null) { - mediaType = MediaType.parse(headers.get("Content-Type")); - } - requestBody = new InputStreamRequestBody(this.context.getRequestEntity(), mediaType, this.context.getContentLength()); - } - - Request.Builder builder = new Request.Builder() - .url(url.build()) - .headers(headers.build()) - .method(this.context.getMethod(), requestBody); - - customize(this.context.getRequestCustomizers(), builder); - - return builder.build(); - } - - public OkHttpRibbonRequest withNewUri(final URI uri) { - return new OkHttpRibbonRequest(newContext(uri)); - } - - static class InputStreamRequestBody extends RequestBody { - - private InputStream inputStream; - private MediaType mediaType; - private Long contentLength; - - InputStreamRequestBody(InputStream inputStream, MediaType mediaType, Long contentLength) { - this.inputStream = inputStream; - this.mediaType = mediaType; - this.contentLength = contentLength; - } - - @Override - public MediaType contentType() { - return mediaType; - } - - @Override - public long contentLength() { - if (contentLength != null) { - return contentLength; - } - try { - return inputStream.available(); - } catch (IOException e) { - return 0; - } - } - - @Override - public void writeTo(BufferedSink sink) throws IOException { - Source source = null; - try { - source = Okio.source(inputStream); - sink.writeAll(source); - } finally { - if (source != null) { - source.close(); - } - } - } - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponse.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponse.java deleted file mode 100644 index 6fcfdc15..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponse.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.okhttp; - -import okhttp3.Response; -import okhttp3.ResponseBody; - -import java.io.InputStream; -import java.lang.reflect.Type; -import java.net.URI; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.springframework.util.Assert; -import com.google.common.reflect.TypeToken; -import com.netflix.client.ClientException; -import com.netflix.client.http.CaseInsensitiveMultiMap; -import com.netflix.client.http.HttpHeaders; - -/** - * @author Spencer Gibb - */ -public class OkHttpRibbonResponse implements com.netflix.client.http.HttpResponse { - - private final ResponseBody body; - private URI uri; - private Response response; - - public OkHttpRibbonResponse(Response response, URI uri) { - Assert.notNull(response, "response can not be null"); - this.response = response; - this.body = response.body(); - this.uri = uri; - } - - - @Override - public int getStatus() { - return this.response.code(); - } - - @Override - public String getStatusLine() { - return this.response.message(); - } - - @Override - public Object getPayload() throws ClientException { - if (!hasPayload()) { - return null; - } - return this.body.byteStream(); - } - - @Override - public boolean hasPayload() { - return this.body != null; - } - - @Override - public boolean isSuccess() { - return this.response.isSuccessful(); - } - - @Override - public URI getRequestedURI() { - return this.uri; - } - - @Override - public Map> getHeaders() { - final Map> headers = new HashMap<>(); - for (Map.Entry> entry : this.response.headers().toMultimap().entrySet()) { - String name = entry.getKey(); - for (String value : entry.getValue()) { - if (headers.containsKey(name)) { - headers.get(name).add(value); - } else { - final List values = new ArrayList<>(); - values.add(value); - headers.put(name, values); - } - } - } - - return headers; - } - - @Override - public HttpHeaders getHttpHeaders() { - final CaseInsensitiveMultiMap headers = new CaseInsensitiveMultiMap(); - for (Map.Entry> entry : this.response.headers().toMultimap().entrySet()) { - for (String value : entry.getValue()) { - headers.addHeader(entry.getKey(), value); - } - } - - return headers; - } - - @Override - public void close() { - this.response.close(); - } - - @Override - public InputStream getInputStream() { - if (this.body == null) { - return null; - } - return this.body.byteStream(); - } - - @Override - public boolean hasEntity() { - return hasPayload(); - } - - @Override - public T getEntity(Class type) throws Exception { - return null; - } - - @Override - public T getEntity(Type type) throws Exception { - return null; - } - - @Override - public T getEntity(TypeToken type) throws Exception { - return null; - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/RetryableOkHttpLoadBalancingClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/RetryableOkHttpLoadBalancingClient.java deleted file mode 100644 index 3895e425..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/RetryableOkHttpLoadBalancingClient.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.cloud.netflix.ribbon.okhttp; - -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; - -import java.net.URI; -import org.apache.commons.lang.BooleanUtils; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.loadbalancer.LoadBalancedBackOffPolicyFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryListenerFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicyFactory; -import org.springframework.cloud.client.loadbalancer.RetryableStatusCodeException; -import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser; -import org.springframework.cloud.netflix.ribbon.support.RibbonRetryPolicy; -import org.springframework.http.HttpRequest; -import org.springframework.retry.RetryCallback; -import org.springframework.retry.RetryContext; -import org.springframework.retry.RetryListener; -import org.springframework.retry.backoff.BackOffPolicy; -import org.springframework.retry.backoff.NoBackOffPolicy; -import org.springframework.retry.policy.NeverRetryPolicy; -import org.springframework.retry.support.RetryTemplate; -import org.springframework.web.util.UriComponentsBuilder; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient; -import org.springframework.cloud.netflix.ribbon.ServerIntrospector; -import com.netflix.client.RequestSpecificRetryHandler; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.Server; - -/** - * An OK HTTP client which leverages Spring Retry to retry failed request. - * @author Ryan Baxter - * @author Gang Li - */ -public class RetryableOkHttpLoadBalancingClient extends OkHttpLoadBalancingClient implements ServiceInstanceChooser { - - private LoadBalancedRetryPolicyFactory loadBalancedRetryPolicyFactory; - private LoadBalancedBackOffPolicyFactory loadBalancedBackOffPolicyFactory = - new LoadBalancedBackOffPolicyFactory.NoBackOffPolicyFactory(); - private LoadBalancedRetryListenerFactory loadBalancedRetryListenerFactory = - new LoadBalancedRetryListenerFactory.DefaultRetryListenerFactory(); - - @Deprecated - //TODO remove in 2.0.x - public RetryableOkHttpLoadBalancingClient(OkHttpClient delegate, IClientConfig config, ServerIntrospector serverIntrospector, - LoadBalancedRetryPolicyFactory loadBalancedRetryPolicyFactory) { - super(delegate, config, serverIntrospector); - this.loadBalancedRetryPolicyFactory = loadBalancedRetryPolicyFactory; - } - - @Deprecated - //TODO remove in 2.0.x - public RetryableOkHttpLoadBalancingClient(OkHttpClient delegate, IClientConfig config, ServerIntrospector serverIntrospector, - LoadBalancedRetryPolicyFactory loadBalancedRetryPolicyFactory, - LoadBalancedBackOffPolicyFactory loadBalancedBackOffPolicyFactory) { - super(delegate, config, serverIntrospector); - this.loadBalancedRetryPolicyFactory = loadBalancedRetryPolicyFactory; - this.loadBalancedBackOffPolicyFactory = loadBalancedBackOffPolicyFactory; - } - - public RetryableOkHttpLoadBalancingClient(OkHttpClient delegate, IClientConfig config, ServerIntrospector serverIntrospector, - LoadBalancedRetryPolicyFactory loadBalancedRetryPolicyFactory, - LoadBalancedBackOffPolicyFactory loadBalancedBackOffPolicyFactory, - LoadBalancedRetryListenerFactory loadBalancedRetryListenerFactory) { - super(delegate, config, serverIntrospector); - this.loadBalancedRetryPolicyFactory = loadBalancedRetryPolicyFactory; - this.loadBalancedBackOffPolicyFactory = loadBalancedBackOffPolicyFactory; - this.loadBalancedRetryListenerFactory = loadBalancedRetryListenerFactory; - } - - private OkHttpRibbonResponse executeWithRetry(OkHttpRibbonRequest request, LoadBalancedRetryPolicy retryPolicy, - RetryCallback callback) throws Exception { - RetryTemplate retryTemplate = new RetryTemplate(); - BackOffPolicy backOffPolicy = loadBalancedBackOffPolicyFactory.createBackOffPolicy(this.getClientName()); - retryTemplate.setBackOffPolicy(backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy); - RetryListener[] retryListeners = this.loadBalancedRetryListenerFactory.createRetryListeners(this.getClientName()); - if (retryListeners != null && retryListeners.length != 0) { - retryTemplate.setListeners(retryListeners); - } - boolean retryable = request.getContext() == null ? true : - BooleanUtils.toBooleanDefaultIfNull(request.getContext().getRetryable(), true); - retryTemplate.setRetryPolicy(retryPolicy == null || !retryable ? new NeverRetryPolicy() - : new RetryPolicy(request, retryPolicy, this, this.getClientName())); - return retryTemplate.execute(callback); - } - - @Override - public OkHttpRibbonResponse execute(final OkHttpRibbonRequest ribbonRequest, - final IClientConfig configOverride) throws Exception { - final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryPolicyFactory.create(this.getClientName(), this); - RetryCallback retryCallback = new RetryCallback() { - @Override - public OkHttpRibbonResponse doWithRetry(RetryContext context) throws Exception { - //on retries the policy will choose the server and set it in the context - //extract the server and update the request being made - OkHttpRibbonRequest newRequest = ribbonRequest; - if(context instanceof LoadBalancedRetryContext) { - ServiceInstance service = ((LoadBalancedRetryContext)context).getServiceInstance(); - if(service != null) { - //Reconstruct the request URI using the host and port set in the retry context - newRequest = newRequest.withNewUri(new URI(service.getUri().getScheme(), - newRequest.getURI().getUserInfo(), service.getHost(), service.getPort(), - newRequest.getURI().getPath(), newRequest.getURI().getQuery(), - newRequest.getURI().getFragment())); - } - } - if (isSecure(configOverride)) { - final URI secureUri = UriComponentsBuilder.fromUri(newRequest.getUri()) - .scheme("https").build().toUri(); - newRequest = newRequest.withNewUri(secureUri); - } - OkHttpClient httpClient = getOkHttpClient(configOverride, secure); - - final Request request = newRequest.toRequest(); - Response response = httpClient.newCall(request).execute(); - if(retryPolicy.retryableStatusCode(response.code())) { - response.close(); - throw new RetryableStatusCodeException(RetryableOkHttpLoadBalancingClient.this.clientName, response.code()); - } - return new OkHttpRibbonResponse(response, newRequest.getUri()); - } - }; - return this.executeWithRetry(ribbonRequest, retryPolicy, retryCallback); - } - - @Override - public ServiceInstance choose(String serviceId) { - Server server = this.getLoadBalancer().chooseServer(serviceId); - return new RibbonLoadBalancerClient.RibbonServer(serviceId, - server); - } - - @Override - public RequestSpecificRetryHandler getRequestSpecificRetryHandler(OkHttpRibbonRequest request, IClientConfig requestConfig) { - return new RequestSpecificRetryHandler(false, false, RetryHandler.DEFAULT, null); - } - - static class RetryPolicy extends RibbonRetryPolicy { - public RetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy, ServiceInstanceChooser serviceInstanceChooser, String serviceName) { - super(request, policy, serviceInstanceChooser, serviceName); - } - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/AbstractLoadBalancingClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/AbstractLoadBalancingClient.java deleted file mode 100644 index 0a647397..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/AbstractLoadBalancingClient.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon.support; - -import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector; -import org.springframework.cloud.netflix.ribbon.RibbonProperties; -import org.springframework.cloud.netflix.ribbon.ServerIntrospector; - -import com.netflix.client.AbstractLoadBalancerAwareClient; -import com.netflix.client.IResponse; -import com.netflix.client.RequestSpecificRetryHandler; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.reactive.LoadBalancerCommand; - -import static org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration.DEFAULT_CONNECT_TIMEOUT; -import static org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration.DEFAULT_READ_TIMEOUT; - -/** - * @author Spencer Gibb - */ -public abstract class AbstractLoadBalancingClient extends - AbstractLoadBalancerAwareClient { - - protected int connectTimeout; - - protected int readTimeout; - - protected boolean secure; - - protected boolean followRedirects; - - protected boolean okToRetryOnAllOperations; - - protected final D delegate; - protected final IClientConfig config; - protected final ServerIntrospector serverIntrospector; - - @Deprecated - public AbstractLoadBalancingClient() { - super(null); - this.config = new DefaultClientConfigImpl(); - this.delegate = createDelegate(this.config); - this.serverIntrospector = new DefaultServerIntrospector(); - this.setRetryHandler(RetryHandler.DEFAULT); - initWithNiwsConfig(config); - } - - @Deprecated - public AbstractLoadBalancingClient(final ILoadBalancer lb) { - super(lb); - this.config = new DefaultClientConfigImpl(); - this.delegate = createDelegate(config); - this.serverIntrospector = new DefaultServerIntrospector(); - this.setRetryHandler(RetryHandler.DEFAULT); - initWithNiwsConfig(config); - } - - protected AbstractLoadBalancingClient(IClientConfig config, ServerIntrospector serverIntrospector) { - super(null); - this.delegate = createDelegate(config); - this.config = config; - this.serverIntrospector = serverIntrospector; - this.setRetryHandler(RetryHandler.DEFAULT); - initWithNiwsConfig(config); - } - - protected AbstractLoadBalancingClient(D delegate, IClientConfig config, ServerIntrospector serverIntrospector) { - super(null); - this.delegate = delegate; - this.config = config; - this.serverIntrospector = serverIntrospector; - this.setRetryHandler(RetryHandler.DEFAULT); - initWithNiwsConfig(config); - } - - @Override - public void initWithNiwsConfig(IClientConfig clientConfig) { - super.initWithNiwsConfig(clientConfig); - RibbonProperties ribbon = RibbonProperties.from(clientConfig); - this.connectTimeout = ribbon.connectTimeout(DEFAULT_CONNECT_TIMEOUT); - this.readTimeout = ribbon.readTimeout(DEFAULT_READ_TIMEOUT); - this.secure = ribbon.isSecure(); - this.followRedirects = ribbon.isFollowRedirects(); - this.okToRetryOnAllOperations = ribbon.isOkToRetryOnAllOperations(); - } - - protected abstract D createDelegate(IClientConfig config); - - public D getDelegate() { - return this.delegate; - } - - @Override - public RequestSpecificRetryHandler getRequestSpecificRetryHandler( - final S request, final IClientConfig requestConfig) { - if (this.okToRetryOnAllOperations) { - return new RequestSpecificRetryHandler(true, true, this.getRetryHandler(), - requestConfig); - } - - if (!request.getContext().getMethod().equals("GET")) { - return new RequestSpecificRetryHandler(true, false, this.getRetryHandler(), - requestConfig); - } - else { - return new RequestSpecificRetryHandler(true, true, this.getRetryHandler(), - requestConfig); - } - } - - protected boolean isSecure(final IClientConfig config) { - if(config != null) { - return RibbonProperties.from(config).isSecure(this.secure); - } - return this.secure; - } - - @Override - protected void customizeLoadBalancerCommandBuilder(S request, IClientConfig config, LoadBalancerCommand.Builder builder) { - if (request.getLoadBalancerKey() != null) { - builder.withServerLocator(request.getLoadBalancerKey()); - } - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/ContextAwareRequest.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/ContextAwareRequest.java deleted file mode 100644 index 9258d51c..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/ContextAwareRequest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon.support; - -import java.net.URI; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpRequest; -import org.springframework.util.MultiValueMap; -import com.netflix.client.ClientRequest; - -/** - * @author Spencer Gibb - * @author Ryan Baxter - */ -public abstract class ContextAwareRequest extends ClientRequest implements HttpRequest { - protected final RibbonCommandContext context; - private HttpHeaders httpHeaders; - - public ContextAwareRequest(RibbonCommandContext context) { - this.context = context; - MultiValueMap headers = context.getHeaders(); - this.httpHeaders = new HttpHeaders(); - for(String key : headers.keySet()) { - this.httpHeaders.put(key, headers.get(key)); - } - this.uri = context.uri(); - this.isRetriable = context.getRetryable(); - this.loadBalancerKey = context.getLoadBalancerKey(); - } - - public RibbonCommandContext getContext() { - return context; - } - - @Override - public HttpMethod getMethod() { - return HttpMethod.valueOf(context.getMethod()); - } - - @Override - public String getMethodValue() { - return getMethod().name(); - } - - @Override - public URI getURI() { - return this.getUri(); - } - - @Override - public HttpHeaders getHeaders() { - return httpHeaders; - } - - protected RibbonCommandContext newContext(URI uri) { - RibbonCommandContext commandContext = new RibbonCommandContext(this.context.getServiceId(), - this.context.getMethod(), uri.toString(), this.context.getRetryable(), - this.context.getHeaders(), this.context.getParams(), this.context.getRequestEntity(), - this.context.getRequestCustomizers(), this.context.getContentLength(), - this.context.getLoadBalancerKey()); - return commandContext; - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/ResettableServletInputStreamWrapper.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/ResettableServletInputStreamWrapper.java deleted file mode 100644 index 11d5b93c..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/ResettableServletInputStreamWrapper.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.cloud.netflix.ribbon.support; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import javax.servlet.ReadListener; -import javax.servlet.ServletInputStream; - -public class ResettableServletInputStreamWrapper extends ServletInputStream { - private final ByteArrayInputStream input; - - public ResettableServletInputStreamWrapper(byte[] data) { - this.input = new ByteArrayInputStream(data); - } - - @Override - public boolean isFinished() { - return false; - } - - @Override - public boolean isReady() { - return false; - } - - @Override - public void setReadListener(ReadListener listener) { - } - - @Override - public int read() throws IOException { - return input.read(); - } - - @Override - public synchronized void reset() throws IOException { - input.reset(); - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContext.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContext.java deleted file mode 100644 index 05796e60..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContext.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.support; - -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import org.springframework.util.Assert; -import org.springframework.util.MultiValueMap; -import org.springframework.util.ReflectionUtils; -import org.springframework.util.StreamUtils; - -/** - * @author Spencer Gibb - * @author Yongsung Yoon - */ -public class RibbonCommandContext { - private final String serviceId; - private final String method; - private final String uri; - private final Boolean retryable; - private final MultiValueMap headers; - private final MultiValueMap params; - private final List requestCustomizers; - private InputStream requestEntity; - private Long contentLength; - private Object loadBalancerKey; - - /** - * Kept for backwards compatibility with Spring Cloud Sleuth 1.x versions - */ - @Deprecated - public RibbonCommandContext(String serviceId, String method, - String uri, Boolean retryable, MultiValueMap headers, - MultiValueMap params, InputStream requestEntity) { - this(serviceId, method, uri, retryable, headers, params, requestEntity, - new ArrayList(), null, null); - } - - public RibbonCommandContext(String serviceId, String method, String uri, - Boolean retryable, MultiValueMap headers, - MultiValueMap params, InputStream requestEntity, - List requestCustomizers) { - this(serviceId, method, uri, retryable, headers, params, requestEntity, - requestCustomizers, null, null); - } - - public RibbonCommandContext(String serviceId, String method, String uri, - Boolean retryable, MultiValueMap headers, - MultiValueMap params, InputStream requestEntity, - List requestCustomizers, Long contentLength) { - this(serviceId, method, uri, retryable, headers, params, requestEntity, - requestCustomizers, contentLength, null); - } - - public RibbonCommandContext(String serviceId, String method, String uri, - Boolean retryable, MultiValueMap headers, - MultiValueMap params, InputStream requestEntity, - List requestCustomizers, Long contentLength, - Object loadBalancerKey) { - Assert.notNull(serviceId, "serviceId may not be null"); - Assert.notNull(method, "method may not be null"); - Assert.notNull(uri, "uri may not be null"); - Assert.notNull(headers, "headers may not be null"); - Assert.notNull(params, "params may not be null"); - Assert.notNull(requestCustomizers, "requestCustomizers may not be null"); - this.serviceId = serviceId; - this.method = method; - this.uri = uri; - this.retryable = retryable; - this.headers = headers; - this.params = params; - this.requestEntity = requestEntity; - this.requestCustomizers = requestCustomizers; - this.contentLength = contentLength; - this.loadBalancerKey = loadBalancerKey; - } - - public URI uri() { - try { - return new URI(this.uri); - } catch (URISyntaxException e) { - ReflectionUtils.rethrowRuntimeException(e); - } - return null; - } - - /** - * Use getMethod() - * - * @return - */ - @Deprecated - public String getVerb() { - return this.method; - } - - public String getServiceId() { - return serviceId; - } - - public String getMethod() { - return method; - } - - public String getUri() { - return uri; - } - - public Boolean getRetryable() { - return retryable; - } - - public MultiValueMap getHeaders() { - return headers; - } - - public MultiValueMap getParams() { - return params; - } - - public InputStream getRequestEntity() { - if (requestEntity == null) { - return null; - } - - try { - if (!(requestEntity instanceof ResettableServletInputStreamWrapper)) { - requestEntity = new ResettableServletInputStreamWrapper( - StreamUtils.copyToByteArray(requestEntity)); - } - requestEntity.reset(); - } finally { - return requestEntity; - } - } - - public List getRequestCustomizers() { - return requestCustomizers; - } - - public Long getContentLength() { - return contentLength; - } - - public void setContentLength(Long contentLength) { - this.contentLength = contentLength; - } - - public Object getLoadBalancerKey() { - return loadBalancerKey; - } - - public void setLoadBalancerKey(Object loadBalancerKey) { - this.loadBalancerKey = loadBalancerKey; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - RibbonCommandContext that = (RibbonCommandContext) o; - return Objects.equals(serviceId, that.serviceId) && Objects - .equals(method, that.method) && Objects.equals(uri, that.uri) - && Objects.equals(retryable, that.retryable) && Objects - .equals(headers, that.headers) && Objects - .equals(params, that.params) && Objects - .equals(requestEntity, that.requestEntity) && Objects - .equals(requestCustomizers, that.requestCustomizers) && Objects - .equals(contentLength, that.contentLength) && Objects - .equals(loadBalancerKey, that.loadBalancerKey); - } - - @Override - public int hashCode() { - return Objects.hash(serviceId, method, uri, retryable, headers, params, - requestEntity, requestCustomizers, contentLength, loadBalancerKey); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("RibbonCommandContext{"); - sb.append("serviceId='").append(serviceId).append('\''); - sb.append(", method='").append(method).append('\''); - sb.append(", uri='").append(uri).append('\''); - sb.append(", retryable=").append(retryable); - sb.append(", headers=").append(headers); - sb.append(", params=").append(params); - sb.append(", requestEntity=").append(requestEntity); - sb.append(", requestCustomizers=").append(requestCustomizers); - sb.append(", contentLength=").append(contentLength); - sb.append(", loadBalancerKey=").append(loadBalancerKey); - sb.append('}'); - return sb.toString(); - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRequestCustomizer.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRequestCustomizer.java deleted file mode 100644 index 4e416a1b..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRequestCustomizer.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon.support; - -import java.util.List; - -/** - * @author Spencer Gibb - */ -public interface RibbonRequestCustomizer { - boolean accepts(Class builderClass); - void customize(B builder); - - class Runner { - - @SuppressWarnings("unchecked") - public static void customize(List customizers, Object builder) { - for (RibbonRequestCustomizer customizer : customizers) { - if (customizer.accepts(builder.getClass())) { - customizer.customize(builder); - } - } - } - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRetryPolicy.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRetryPolicy.java deleted file mode 100644 index 157ce501..00000000 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRetryPolicy.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.springframework.cloud.netflix.ribbon.support; - -import java.net.URI; -import java.util.HashMap; -import java.util.Map; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.loadbalancer.InterceptorRetryPolicy; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy; -import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser; -import org.springframework.http.HttpRequest; -import org.springframework.retry.RetryContext; - -/** - * @author Ryan Baxter - */ -public class RibbonRetryPolicy extends InterceptorRetryPolicy { - private HttpRequest request; - private String serviceId; - public RibbonRetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy, ServiceInstanceChooser serviceInstanceChooser, String serviceName) { - super(request, policy, serviceInstanceChooser, serviceName); - this.request = request; - this.serviceId = serviceName; - } - - @Override - public boolean canRetry(RetryContext context) { - /* - * In InterceptorRetryPolicy.canRetry we ask the LoadBalancer to choose a server if one is not - * set in the retry context and then return true. RetryTemplat calls the canRetry method of - * the policy even on its first execution. So the fact that we didnt have a service instance set - * in the RetryContext signaled that it was the first execution and we should return true. - * - */ - if(context.getRetryCount() == 0) { - return true; - } - return super.canRetry(context); - } - - @Override - public RetryContext open(RetryContext parent) { - LoadBalancedRetryContext context = new LoadBalancedRetryContext(parent, this.request); - context.setServiceInstance(new RibbonRetryPolicyServiceInstance(serviceId, request)); - return context; - } - - class RibbonRetryPolicyServiceInstance implements ServiceInstance { - - private String serviceId; - private HttpRequest request; - private Map metadata; - - RibbonRetryPolicyServiceInstance(String serviceId, HttpRequest request) { - this.serviceId = serviceId; - this.request = request; - this.metadata = new HashMap<>(); - } - - @Override - public String getServiceId() { - return serviceId; - } - - @Override - public String getHost() { - return request.getURI().getHost(); - } - - @Override - public int getPort() { - return request.getURI().getPort(); - } - - @Override - public boolean isSecure() { - return "https".equals(request.getURI().getScheme()); - } - - @Override - public URI getUri() { - return request.getURI(); - } - - @Override - public Map getMetadata() { - return metadata; - } - } -} diff --git a/spring-cloud-netflix-ribbon/src/main/resources/META-INF/spring.factories b/spring-cloud-netflix-ribbon/src/main/resources/META-INF/spring.factories deleted file mode 100644 index be8c8c7b..00000000 --- a/spring-cloud-netflix-ribbon/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration \ No newline at end of file diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospectorDefaultTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospectorDefaultTests.java deleted file mode 100644 index caa1f915..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospectorDefaultTests.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.loadbalancer.Server; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * @author Rico Pahlisch - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = DefaultServerIntrospectorDefaultTests.TestConfiguration.class) -public class DefaultServerIntrospectorDefaultTests { - - @Autowired - private ServerIntrospector serverIntrospector; - - @Test - public void testDefaultSslPorts(){ - Server serverMock = mock(Server.class); - when(serverMock.getPort()).thenReturn(443); - Assert.assertTrue(serverIntrospector.isSecure(serverMock)); - when(serverMock.getPort()).thenReturn(8443); - Assert.assertTrue(serverIntrospector.isSecure(serverMock)); - - when(serverMock.getPort()).thenReturn(16443); - Assert.assertFalse(serverIntrospector.isSecure(serverMock)); - } - - @Configuration - @EnableConfigurationProperties(ServerIntrospectorProperties.class) - protected static class TestConfiguration { - @Bean - public DefaultServerIntrospector defaultServerIntrospector(){ - return new DefaultServerIntrospector(); - } - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospectorTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospectorTests.java deleted file mode 100644 index 4e614df6..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospectorTests.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.loadbalancer.Server; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * @author Rico Pahlisch - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = DefaultServerIntrospectorTests.TestConfiguration.class) -@TestPropertySource(properties = { "ribbon.securePorts=12345,556" }) -public class DefaultServerIntrospectorTests { - - @Autowired - private ServerIntrospector serverIntrospector; - - @Test - public void testSecurePortConfiguration(){ - Server serverMock = mock(Server.class); - when(serverMock.getPort()).thenReturn(12345); - Assert.assertTrue(serverIntrospector.isSecure(serverMock)); - when(serverMock.getPort()).thenReturn(556); - Assert.assertTrue(serverIntrospector.isSecure(serverMock)); - when(serverMock.getPort()).thenReturn(443); - Assert.assertFalse(serverIntrospector.isSecure(serverMock)); - } - - @Configuration - @EnableConfigurationProperties(ServerIntrospectorProperties.class) - protected static class TestConfiguration { - @Bean - public DefaultServerIntrospector defaultServerIntrospector(){ - return new DefaultServerIntrospector(); - } - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/PlainRibbonClientPreprocessorIntegrationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/PlainRibbonClientPreprocessorIntegrationTests.java deleted file mode 100644 index 14e39602..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/PlainRibbonClientPreprocessorIntegrationTests.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.PlainRibbonClientPreprocessorIntegrationTests.TestConfiguration; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.loadbalancer.ConfigurationBasedServerList; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; - -/** - * @author Dave Syer - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = TestConfiguration.class) -@DirtiesContext -public class PlainRibbonClientPreprocessorIntegrationTests { - - @Autowired - private SpringClientFactory factory; - - @Test - public void serverListIsConfigured() throws Exception { - @SuppressWarnings("unchecked") - ZoneAwareLoadBalancer loadBalancer = (ZoneAwareLoadBalancer) this.factory - .getLoadBalancer("foo"); - ConfigurationBasedServerList.class.cast(loadBalancer.getServerListImpl()); - } - - @Configuration - @RibbonClient("foo") - @Import({ PropertyPlaceholderAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class}) - protected static class TestConfiguration { - } - -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializerTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializerTests.java deleted file mode 100644 index 690cbc7a..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializerTests.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.util.Arrays; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Biju Kunjummen - */ - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = {RibbonAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonApplicationContextInitializerTests.RibbonInitializerConfig.class}) -@DirtiesContext -public class RibbonApplicationContextInitializerTests { - - @Autowired - private SpringClientFactory springClientFactory; - - @Test - public void testContextShouldInitalizeChildContexts() { - - // Context should have been initialized and an instance of Foo created - assertThat(Foo.getInstanceCount()).isEqualTo(1); - ApplicationContext ctx = springClientFactory.getContext("testspec"); - - assertThat(Foo.getInstanceCount()).isEqualTo(1); - Foo foo = ctx.getBean("foo", Foo.class); - assertThat(foo).isNotNull(); - } - - static class FooConfig { - - @Bean - public Foo foo() { - return new Foo(); - } - - } - - @Configuration - @RibbonClient(name="testspec", configuration = FooConfig.class) - static class RibbonInitializerConfig { - - @Bean - public RibbonApplicationContextInitializer ribbonApplicationContextInitializer( - SpringClientFactory springClientFactory) { - return new RibbonApplicationContextInitializer(springClientFactory, - Arrays.asList("testspec")); - } - - } - - static class Foo { - private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger(); - - public Foo() { - INSTANCE_COUNT.incrementAndGet(); - } - - public static int getInstanceCount() { - return INSTANCE_COUNT.get(); - } - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfigurationIntegrationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfigurationIntegrationTests.java deleted file mode 100644 index e1699839..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfigurationIntegrationTests.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonAutoConfigurationIntegrationTests.TestConfiguration; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.IClientConfig; - -import static org.junit.Assert.assertEquals; - -/** - * @author Dave Syer - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = TestConfiguration.class, value = {"ribbon.ConnectTimeout=25000"}) -@DirtiesContext -public class RibbonAutoConfigurationIntegrationTests { - - @Autowired - private SpringClientFactory factory; - - @Test - public void serverListIsConfigured() throws Exception { - IClientConfig config = this.factory.getClientConfig("client"); - assertEquals(25000, - config.getPropertyAsInteger(CommonClientConfigKey.ConnectTimeout, 3000)); - } - - @Configuration - @RibbonClient("client") - @Import({ PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class, - RibbonAutoConfiguration.class }) - protected static class TestConfiguration { - } - -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationIntegrationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationIntegrationTests.java deleted file mode 100644 index f4c16a3d..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationIntegrationTests.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.util.ReflectionTestUtils; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.PollingServerListUpdater; -import com.netflix.loadbalancer.ServerListUpdater; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; - -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; - -/** - * @author Dave Syer - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = RibbonClientConfigurationIntegrationTests.TestLBConfig.class, - properties = "test.ribbon.ServerListRefreshInterval=999") -@DirtiesContext -public class RibbonClientConfigurationIntegrationTests { - - @Autowired - private SpringClientFactory clientFactory; - - @Test - public void testLoadBalancerConstruction() { - ILoadBalancer loadBalancer = clientFactory.getInstance("test", ILoadBalancer.class); - assertThat(loadBalancer, is(instanceOf(ZoneAwareLoadBalancer.class))); - ZoneAwareLoadBalancer lb = (ZoneAwareLoadBalancer) loadBalancer; - ServerListUpdater serverListUpdater = (PollingServerListUpdater) ReflectionTestUtils.getField(loadBalancer, "serverListUpdater"); - Long refreshIntervalMs = (Long) ReflectionTestUtils.getField(serverListUpdater, "refreshIntervalMs"); - // assertThat(refreshIntervalMs, equalTo(999L)); - - ServerListUpdater updater = clientFactory.getInstance("test", ServerListUpdater.class); - assertThat(updater, is(sameInstance(serverListUpdater))); - } - - @Configuration - @EnableAutoConfiguration - protected static class TestLBConfig { } - -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationTests.java deleted file mode 100644 index 8b77275c..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationTests.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.net.URI; -import java.util.ArrayList; -import java.util.List; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.springframework.beans.factory.BeanFactoryUtils; -import org.springframework.beans.factory.ListableBeanFactory; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.util.EnvironmentTestUtils; -import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration.OverrideRestClient; -import org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient; -import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpLoadBalancingClient; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Configuration; -import com.netflix.client.AbstractLoadBalancerAwareClient; -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.Server; -import com.netflix.niws.client.http.RestClient; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.when; - -/** - * @author Spencer Gibb - */ -public class RibbonClientConfigurationTests { - - private CountingConfig config; - - @Mock - private ServerIntrospector inspector; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - this.config = new CountingConfig(); - this.config.setProperty(CommonClientConfigKey.ConnectTimeout, "1"); - this.config.setProperty(CommonClientConfigKey.ReadTimeout, "1"); - this.config.setProperty(CommonClientConfigKey.MaxHttpConnectionsPerHost, "1"); - this.config.setClientName("testClient"); - } - - @Test - public void restClientInitCalledOnce() { - new TestRestClient(this.config); - assertThat(this.config.count, is(1)); - } - - @Test - public void restClientWithSecureServer() throws Exception { - CountingConfig config = new CountingConfig(); - config.setProperty(CommonClientConfigKey.ConnectTimeout, "1"); - config.setProperty(CommonClientConfigKey.ReadTimeout, "1"); - config.setProperty(CommonClientConfigKey.MaxHttpConnectionsPerHost, "1"); - config.setClientName("bar"); - Server server = new Server("example.com", 443); - URI uri = new TestRestClient(config).reconstructURIWithServer(server, - new URI("/foo")); - assertThat(uri.getScheme(), is("https")); - assertThat(uri.getHost(), is("example.com")); - } - - static class CountingConfig extends DefaultClientConfigImpl { - int count = 0; - } - - @Test - public void testSecureUriFromClientConfig() throws Exception { - Server server = new Server("foo", 7777); - when(this.inspector.isSecure(server)).thenReturn(true); - - for (AbstractLoadBalancerAwareClient client : clients()) { - URI uri = client.reconstructURIWithServer(server, - new URI("http://foo/")); - assertThat(getReason(client), uri, is(new URI("https://foo:7777/"))); - } - } - - @Test - public void testInSecureUriFromClientConfig() throws Exception { - Server server = new Server("foo", 7777); - when(this.inspector.isSecure(server)).thenReturn(false); - - for (AbstractLoadBalancerAwareClient client : clients()) { - URI uri = client.reconstructURIWithServer(server, - new URI("http://foo/")); - assertThat(getReason(client), uri, is(new URI("http://foo:7777/"))); - } - } - - String getReason(AbstractLoadBalancerAwareClient client) { - return client.getClass().getSimpleName()+" failed"; - } - - @Test - public void testNotDoubleEncodedWhenSecure() throws Exception { - Server server = new Server("foo", 7777); - when(this.inspector.isSecure(server)).thenReturn(true); - - for (AbstractLoadBalancerAwareClient client : clients()) { - URI uri = client.reconstructURIWithServer(server, - new URI("http://foo/%20bar")); - assertThat(getReason(client), uri, is(new URI("https://foo:7777/%20bar"))); - } - } - - @Test - public void testPlusInQueryStringGetsRewrittenWhenServerIsSecure() throws Exception { - Server server = new Server("foo", 7777); - when(this.inspector.isSecure(server)).thenReturn(true); - - for (AbstractLoadBalancerAwareClient client : clients()) { - URI uri = client.reconstructURIWithServer(server, new URI("http://foo/%20bar?hello=1+2")); - assertThat(uri, is(new URI("https://foo:7777/%20bar?hello=1%202"))); - } - } - - private List clients() { - ArrayList clients = new ArrayList<>(); - clients.add(new OverrideRestClient(this.config, this.inspector)); - clients.add(new RibbonLoadBalancingHttpClient(this.config, this.inspector)); - clients.add(new OkHttpLoadBalancingClient(this.config, this.inspector)); - return clients; - } - - @SuppressWarnings("deprecation") - @Test - public void testDefaultsToApacheHttpClient() { - testClient(RibbonLoadBalancingHttpClient.class, null, RestClient.class, OkHttpLoadBalancingClient.class); - testClient(RibbonLoadBalancingHttpClient.class, new String[]{"ribbon.httpclient.enabled"}, RestClient.class, OkHttpLoadBalancingClient.class); - } - - @SuppressWarnings("deprecation") - @Test - public void testEnableRestClient() { - testClient(RestClient.class, new String[]{"ribbon.restclient.enabled"}, RibbonLoadBalancingHttpClient.class, - OkHttpLoadBalancingClient.class); - } - - @SuppressWarnings("deprecation") - @Test - public void testEnableOkHttpClient() { - testClient(OkHttpLoadBalancingClient.class, new String[]{"ribbon.okhttp.enabled"}, RibbonLoadBalancingHttpClient.class, - RestClient.class); - } - - void testClient(Class clientType, String[] properties, Class... excludedTypes) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - context.register(HttpClientConfiguration.class, RibbonAutoConfiguration.class, - RibbonClientConfiguration.class); - if (properties != null) { - EnvironmentTestUtils.addEnvironment(context, properties); - } - context.refresh(); - context.getBean(clientType); - for (Class excludedType : excludedTypes) { - assertThat("has "+excludedType.getSimpleName()+ " instance", hasInstance(context, excludedType), is(false)); - } - context.close(); - } - - private boolean hasInstance(ListableBeanFactory lbf, Class requiredType) { - return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(lbf, - requiredType).length > 0; - } - - @Configuration - @EnableAutoConfiguration - protected static class TestLBConfig { } - - static class TestRestClient extends OverrideRestClient { - - private TestRestClient(IClientConfig ncc) { - super(ncc, new DefaultServerIntrospector()); - } - - @Override - public void initWithNiwsConfig(IClientConfig clientConfig) { - ((CountingConfig) clientConfig).count++; - super.initWithNiwsConfig(clientConfig); - } - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactoryTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactoryTests.java deleted file mode 100644 index 1708c6d9..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactoryTests.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.net.URI; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.loadbalancer.LoadBalanced; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpStatus; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.http.client.ClientHttpRequestFactory; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.ResourceAccessException; -import org.springframework.web.client.RestTemplate; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author Spencer Gibb - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = RibbonClientHttpRequestFactoryTests.App.class, webEnvironment = RANDOM_PORT, value = { - "spring.application.name=ribbonclienttest", "spring.jmx.enabled=true", - "spring.cloud.netflix.metrics.enabled=false", "ribbon.restclient.enabled=true", "debug=true" }) -@DirtiesContext -public class RibbonClientHttpRequestFactoryTests { - - @Rule - public final ExpectedException exceptionRule = ExpectedException.none(); - - @LoadBalanced - @Autowired - protected RestTemplate restTemplate; - - @Test - public void requestFactoryIsRibbon() { - ClientHttpRequestFactory requestFactory = this.restTemplate.getRequestFactory(); - assertThat(requestFactory).isInstanceOf(RibbonClientHttpRequestFactory.class); - } - - @Test - public void vanillaRequestWorks() { - ResponseEntity response = this.restTemplate.getForEntity("http://simple/", - String.class); - assertEquals("wrong response code", HttpStatus.OK, response.getStatusCode()); - assertEquals("wrong response body", "hello", response.getBody()); - } - - @Test - public void requestWithPathParamWorks() { - ResponseEntity response = this.restTemplate - .getForEntity("http://simple/path/{param}", String.class, "world"); - assertEquals("wrong response code", HttpStatus.OK, response.getStatusCode()); - assertEquals("wrong response body", "hello world", response.getBody()); - } - - @Test - public void requestWithEncodedPathParamWorks() { - ResponseEntity response = this.restTemplate.getForEntity( - "http://simple/path/{param}", String.class, "world & everyone else"); - assertEquals("wrong response code", HttpStatus.OK, response.getStatusCode()); - assertEquals("wrong response body", "hello world & everyone else", - response.getBody()); - } - - @Test - public void requestWithRequestParamWorks() { - ResponseEntity response = this.restTemplate.getForEntity( - "http://simple/request?param={param}", String.class, "world"); - assertEquals("wrong response code", HttpStatus.OK, response.getStatusCode()); - assertEquals("wrong response body", "hello world", response.getBody()); - } - - @Test - public void requestWithPostWorks() { - ResponseEntity response = this.restTemplate - .postForEntity("http://simple/post", "world", String.class); - assertEquals("wrong response code", HttpStatus.OK, response.getStatusCode()); - assertEquals("wrong response body", "hello world", response.getBody()); - } - - @Test - public void requestWithEmptyPostWorks() { - ResponseEntity response = this.restTemplate - .postForEntity("http://simple/emptypost", "", String.class); - assertEquals("wrong response code", HttpStatus.OK, response.getStatusCode()); - assertEquals("wrong response body", "hello empty", response.getBody()); - } - - @Test - public void requestWithHeaderWorks() throws Exception { - RequestEntity entity = RequestEntity.get(new URI("http://simple/header")) - .header("X-Param", "world").build(); - ResponseEntity response = this.restTemplate.exchange(entity, - String.class); - assertEquals("wrong response code", HttpStatus.OK, response.getStatusCode()); - assertEquals("wrong response body", "hello world", response.getBody()); - } - - @Test - public void invalidHostNameError() { - this.exceptionRule.expect(ResourceAccessException.class); - this.exceptionRule.expectMessage("Invalid hostname"); - this.restTemplate.getForEntity("http://simple_bad", String.class); - } - - @Configuration - @EnableAutoConfiguration - @RestController - @RibbonClient(value = "simple", configuration = SimpleRibbonClientConfiguration.class) - public static class App { - - @LoadBalanced - @Bean - RestTemplate restTemplate() { - return new RestTemplate(); - } - - @RequestMapping("/") - public String hi() { - return "hello"; - } - - @RequestMapping("/path/{param}") - public String hiParam(@PathVariable("param") String param) { - return "hello " + param; - } - - @RequestMapping("/request") - public String hiRequest(@RequestParam("param") String param) { - return "hello " + param; - } - - @RequestMapping(value = "/post", method = RequestMethod.POST) - public String hiPost(@RequestBody String param) { - return "hello " + param; - } - - @RequestMapping(value = "/emptypost", method = RequestMethod.POST) - public String hiPostEmpty() { - return "hello empty"; - } - - @RequestMapping("/header") - public String hiHeader(@RequestHeader("X-Param") String param) { - return "hello " + param; - } - } - - @Configuration - static class SimpleRibbonClientConfiguration { - - @Value("${local.server.port}") - private int port = 0; - - @Bean - public ServerList ribbonServerList() { - return new StaticServerList<>(new Server("localhost", this.port)); - } - - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorIntegrationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorIntegrationTests.java deleted file mode 100644 index 26633866..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorIntegrationTests.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonClientPreprocessorIntegrationTests.PlainConfiguration; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.loadbalancer.ConfigurationBasedServerList; -import com.netflix.loadbalancer.DummyPing; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAvoidanceRule; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; - -/** - * @author Dave Syer - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = PlainConfiguration.class) -@DirtiesContext -public class RibbonClientPreprocessorIntegrationTests { - - @Autowired - private SpringClientFactory factory; - - @Test - public void ruleDefaultsToZoneAvoidance() throws Exception { - ZoneAvoidanceRule.class.cast(getLoadBalancer().getRule()); - } - - @Test - public void serverListFilterDefaultsToZonePreference() throws Exception { - ZonePreferenceServerListFilter.class.cast(getLoadBalancer().getFilter()); - } - - @Test - public void pingDefaultsToDummy() throws Exception { - DummyPing.class.cast(getLoadBalancer().getPing()); - } - - @Test - public void serverListDefaultsToConfigurationBased() throws Exception { - ConfigurationBasedServerList.class.cast(getLoadBalancer().getServerListImpl()); - } - - @SuppressWarnings("unchecked") - private ZoneAwareLoadBalancer getLoadBalancer() { - return (ZoneAwareLoadBalancer) this.factory.getLoadBalancer("foo"); - } - - @Configuration - @RibbonClient(name = "foo") - @Import({ PropertyPlaceholderAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class }) - protected static class PlainConfiguration { - } - -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorOverridesIntegrationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorOverridesIntegrationTests.java deleted file mode 100644 index 0fdf5734..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorOverridesIntegrationTests.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.commons.util.UtilAutoConfiguration; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ConfigurationBasedServerList; -import com.netflix.loadbalancer.DummyPing; -import com.netflix.loadbalancer.IPing; -import com.netflix.loadbalancer.IRule; -import com.netflix.loadbalancer.PingConstant; -import com.netflix.loadbalancer.RandomRule; -import com.netflix.loadbalancer.RoundRobinRule; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.loadbalancer.ServerListFilter; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; - -import static org.junit.Assert.assertEquals; - -/** - * @author Dave Syer - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = RibbonClientPreprocessorOverridesIntegrationTests.TestConfiguration.class) -@DirtiesContext -public class RibbonClientPreprocessorOverridesIntegrationTests { - - @Autowired - private SpringClientFactory factory; - - @Test - public void ruleOverridesToRandom() throws Exception { - RandomRule.class.cast(getLoadBalancer("foo").getRule()); - RoundRobinRule.class.cast(getLoadBalancer("bar").getRule()); - } - - @Test - public void pingOverridesToDummy() throws Exception { - DummyPing.class.cast(getLoadBalancer("foo").getPing()); - PingConstant.class.cast(getLoadBalancer("bar").getPing()); - } - - @Test - public void serverListOverridesToMy() throws Exception { - FooServiceList.class.cast(getLoadBalancer("foo").getServerListImpl()); - BarServiceList.class.cast(getLoadBalancer("bar").getServerListImpl()); - } - - @SuppressWarnings("unchecked") - private ZoneAwareLoadBalancer getLoadBalancer(String name) { - return (ZoneAwareLoadBalancer) this.factory.getLoadBalancer(name); - } - - @Test - public void serverListFilterOverride() throws Exception { - ServerListFilter filter = getLoadBalancer("foo").getFilter(); - assertEquals("FooTestZone", - ZonePreferenceServerListFilter.class.cast(filter) - .getZone()); - } - - @Configuration - @RibbonClients({ - @RibbonClient(name = "foo", configuration = FooConfiguration.class), - @RibbonClient(name = "bar", configuration = BarConfiguration.class) - }) - @Import({ UtilAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class}) - protected static class TestConfiguration { - } - - @Configuration - public static class FooConfiguration { - @Bean - public IRule ribbonRule() { - return new RandomRule(); - } - - @Bean - public IPing ribbonPing() { - return new DummyPing(); - } - - @Bean - public ServerList ribbonServerList(IClientConfig config) { - return new FooServiceList(config); - } - - @Bean - public ZonePreferenceServerListFilter serverListFilter() { - ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter(); - filter.setZone("FooTestZone"); - return filter; - } - } - - public static class FooServiceList extends ConfigurationBasedServerList { - public FooServiceList(IClientConfig config) { - super.initWithNiwsConfig(config); - } - } - - @Configuration - public static class BarConfiguration { - - @Bean - public IRule ribbonRule() { - return new RoundRobinRule(); - } - - @Bean - public IPing ribbonPing() { - return new PingConstant(); - } - - @Bean - public ServerList ribbonServerList(IClientConfig config) { - return new BarServiceList(config); - } - - @Bean - public ZonePreferenceServerListFilter serverListFilter() { - ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter(); - filter.setZone("BarTestZone"); - return filter; - } - } - - public static class BarServiceList extends ConfigurationBasedServerList { - public BarServiceList(IClientConfig config) { - super.initWithNiwsConfig(config); - } - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorOverridesRetryTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorOverridesRetryTests.java deleted file mode 100644 index 9fa5f137..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorOverridesRetryTests.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.net.ConnectException; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.util.Assert; -import com.netflix.client.DefaultLoadBalancerRetryHandler; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; - -/** - * @author Tyler Van Gorder - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = RibbonClientPreprocessorOverridesRetryTests.TestConfiguration.class, value = { - "customRetry.ribbon.MaxAutoRetries=0", - "customRetry.ribbon.MaxAutoRetriesNextServer=1", - "customRetry.ribbon.OkToRetryOnAllOperations=true" }) -@DirtiesContext -public class RibbonClientPreprocessorOverridesRetryTests { - - @Autowired - private SpringClientFactory factory; - - @Test - public void customRetryIsConfigured() throws Exception { - RibbonLoadBalancerContext context = (RibbonLoadBalancerContext) this.factory - .getLoadBalancerContext("customRetry"); - Assert.isInstanceOf(RetryRibbonConfiguration.CustomRetryHandler.class, - context.getRetryHandler()); - Assert.isTrue(context.getRetryHandler().getMaxRetriesOnSameServer() == 0); - Assert.isTrue(context.getRetryHandler().getMaxRetriesOnNextServer() == 1); - Assert.isTrue(context.getRetryHandler() - .isCircuitTrippingException(new UnknownHostException("Unknown Host"))); - } - - @Configuration - @RibbonClient(name = "customRetry", configuration = RetryRibbonConfiguration.class) - @Import({ PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class, - RibbonAutoConfiguration.class }) - protected static class TestConfiguration { - } - -} - -@Configuration -class RetryRibbonConfiguration { - @Bean - public RetryHandler retryHandler(IClientConfig config) { - return new CustomRetryHandler(config); - } - - class CustomRetryHandler extends DefaultLoadBalancerRetryHandler { - - @SuppressWarnings("unchecked") - private List> retriable = new ArrayList() { - { - add(UnknownHostException.class); - add(ConnectException.class); - add(SocketTimeoutException.class); - } - }; - - @SuppressWarnings("unchecked") - private List> circuitRelated = new ArrayList() { - { - add(UnknownHostException.class); - add(SocketException.class); - add(SocketTimeoutException.class); - } - }; - - CustomRetryHandler(IClientConfig config) { - super(config); - } - - @Override - protected List> getRetriableExceptions() { - return retriable; - } - - @Override - protected List> getCircuitRelatedExceptions() { - return circuitRelated; - } - - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorPropertiesOverridesIntegrationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorPropertiesOverridesIntegrationTests.java deleted file mode 100644 index b894cc19..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorPropertiesOverridesIntegrationTests.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; -import org.springframework.cloud.commons.util.UtilAutoConfiguration; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.test.TestLoadBalancer; -import org.springframework.cloud.netflix.ribbon.test.TestServerList; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.loadbalancer.ConfigurationBasedServerList; -import com.netflix.loadbalancer.DummyPing; -import com.netflix.loadbalancer.NoOpPing; -import com.netflix.loadbalancer.RandomRule; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerListSubsetFilter; -import com.netflix.loadbalancer.ZoneAvoidanceRule; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.Assume.assumeThat; - -/** - * @author Spencer Gibb - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = RibbonClientPreprocessorPropertiesOverridesIntegrationTests.TestConfiguration.class) -@DirtiesContext -public class RibbonClientPreprocessorPropertiesOverridesIntegrationTests { - - @Autowired - private SpringClientFactory factory; - - @Test - public void ruleOverridesToRandom() throws Exception { - assumeNotTravis(); - RandomRule.class.cast(getLoadBalancer("foo2").getRule()); - ZoneAvoidanceRule.class.cast(getLoadBalancer("bar").getRule()); - } - - // TODO: why do these tests fail in travis? - void assumeNotTravis() { - assumeThat("running in travis, skipping", System.getenv("TRAVIS"), - is(not(equalTo("true")))); - } - - @Test - public void pingOverridesToNoOp() throws Exception { - NoOpPing.class.cast(getLoadBalancer("foo2").getPing()); - DummyPing.class.cast(getLoadBalancer("bar").getPing()); - } - - @Test - public void serverListOverridesToTest() throws Exception { - assumeNotTravis(); - TestServerList.class.cast(getLoadBalancer("foo2").getServerListImpl()); - ConfigurationBasedServerList.class - .cast(getLoadBalancer("bar").getServerListImpl()); - } - - @Test - public void loadBalancerOverridesToTest() throws Exception { - TestLoadBalancer.class.cast(getLoadBalancer("foo2")); - ZoneAwareLoadBalancer.class.cast(getLoadBalancer("bar")); - } - - @Test - public void serverListFilterOverride() throws Exception { - assumeNotTravis(); - ServerListSubsetFilter.class.cast(getLoadBalancer("foo2").getFilter()); - ZonePreferenceServerListFilter.class.cast(getLoadBalancer("bar").getFilter()); - } - - @SuppressWarnings("unchecked") - private ZoneAwareLoadBalancer getLoadBalancer(String name) { - return (ZoneAwareLoadBalancer) this.factory.getLoadBalancer(name); - } - - @Configuration - @RibbonClients - @Import({ UtilAutoConfiguration.class, HttpClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class }) - protected static class TestConfiguration { - } - -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientsEagerInitializationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientsEagerInitializationTests.java deleted file mode 100644 index 53ece37f..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientsEagerInitializationTests.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Biju Kunjummen - */ - -@RunWith(SpringRunner.class) -@SpringBootTest(properties = { - "ribbon.eager-load.enabled=true", - "ribbon.eager-load.clients=testspec1,testspec2" -}) -@DirtiesContext -public class RibbonClientsEagerInitializationTests { - - @Test - public void contextsShouldBeInitialized() { - assertThat(Foo1.getInstanceCount()).isEqualTo(2); - } - - static class FooConfig { - @Bean - public Foo1 foo() { - return new Foo1(); - } - } - - @Configuration - @EnableAutoConfiguration - @RibbonClients( - value = { - @RibbonClient(name="testspec1", configuration = FooConfig.class), - @RibbonClient(name="testspec2", configuration = FooConfig.class), - @RibbonClient(name="testspec3", configuration = FooConfig.class), - }) - static class RibbonConfig { - } - - static class Foo1 { - private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger(); - - public Foo1() { - INSTANCE_COUNT.incrementAndGet(); - } - - public static int getInstanceCount() { - return INSTANCE_COUNT.get(); - } - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientsPreprocessorIntegrationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientsPreprocessorIntegrationTests.java deleted file mode 100644 index 2ac7a27e..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientsPreprocessorIntegrationTests.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; -import org.springframework.cloud.commons.util.UtilAutoConfiguration; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonClientsPreprocessorIntegrationTests.TestConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.loadbalancer.IPing; -import com.netflix.loadbalancer.PingUrl; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAvoidanceRule; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Dave Syer - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = TestConfiguration.class) -@DirtiesContext -public class RibbonClientsPreprocessorIntegrationTests { - - @Autowired - private SpringClientFactory factory; - - @Test - public void ruleDefaultsToZoneAvoidance() throws Exception { - ZoneAvoidanceRule.class.cast(getLoadBalancer().getRule()); - } - - @SuppressWarnings("unchecked") - private ZoneAwareLoadBalancer getLoadBalancer() { - return (ZoneAwareLoadBalancer) this.factory.getLoadBalancer("foo"); - } - - @Test - public void serverListFilterOverride() throws Exception { - assertThat(ZonePreferenceServerListFilter.class - .cast(getLoadBalancer().getFilter()).getZone()).isEqualTo("myTestZone"); - } - - @Test - public void pingOverride() throws Exception { - assertThat(getLoadBalancer().getPing()).isInstanceOf(PingUrl.class); - } - - @Configuration - @RibbonClients(@RibbonClient(name = "foo", configuration = FooConfiguration.class)) - @Import({ UtilAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class, HttpClientConfiguration.class}) - protected static class TestConfiguration { - } - - // tag::sample_override_ribbon_config[] - @Configuration - protected static class FooConfiguration { - @Bean - public ZonePreferenceServerListFilter serverListFilter() { - ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter(); - filter.setZone("myTestZone"); - return filter; - } - - @Bean - public IPing ribbonPing() { - return new PingUrl(); - } - } - // end::sample_override_ribbon_config[] - -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonDisabledTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonDisabledTests.java deleted file mode 100644 index 9ee37bc2..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonDisabledTests.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.cloud.test.ClassPathExclusions; -import org.springframework.cloud.test.ModifiedClassPathRunner; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -/** - * @author Ryan Baxter - * @author Biju Kunjummen - */ -@RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions({ "ribbon-{version:\\d.*}.jar" }) -public class RibbonDisabledTests { - @Test - public void testRibbonDisabled() { - assertThatThrownBy(() -> new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RibbonAutoConfiguration.class)) - .run(context -> { - assertThat(context.getBeanNamesForType(SpringClientFactory.class)) - .hasSize(0); - })).hasCauseExactlyInstanceOf(ArrayStoreException.class); - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonInterceptorTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonInterceptorTests.java deleted file mode 100644 index aa9bb89e..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonInterceptorTests.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.io.IOException; -import java.net.URI; -import java.net.URL; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; -import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor; -import org.springframework.cloud.client.loadbalancer.LoadBalancerRequest; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonServer; -import org.springframework.http.HttpRequest; -import org.springframework.http.client.ClientHttpRequestExecution; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.http.client.support.HttpRequestWrapper; -import org.springframework.util.ReflectionUtils; -import org.springframework.web.util.UriComponentsBuilder; -import com.netflix.loadbalancer.Server; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.verify; - -/** - * @author Spencer Gibb - */ -public class RibbonInterceptorTests { - - @Mock - private HttpRequest request; - - @Mock - private ClientHttpRequestExecution execution; - - @Mock - private ClientHttpResponse response; - - @Before - public void init() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testIntercept() throws Exception { - RibbonServer server = new RibbonServer("myservice", new Server("myhost", 8080)); - LoadBalancerInterceptor interceptor = new LoadBalancerInterceptor(new MyClient(server)); - given(this.request.getURI()).willReturn(new URL("http://myservice").toURI()); - given(this.execution.execute(isA(HttpRequest.class), isA(byte[].class))) - .willReturn(this.response); - ArgumentCaptor argument = ArgumentCaptor - .forClass(HttpRequestWrapper.class); - ClientHttpResponse response = interceptor.intercept(this.request, new byte[0], - this.execution); - assertNotNull("response was null", response); - verify(this.execution).execute(argument.capture(), isA(byte[].class)); - HttpRequestWrapper wrapper = argument.getValue(); - assertEquals("wrong constructed uri", new URL("http://myhost:8080").toURI(), - wrapper.getURI()); - } - - protected static class MyClient implements LoadBalancerClient { - - private ServiceInstance instance; - - public MyClient(ServiceInstance instance) { - this.instance = instance; - } - - @Override - public ServiceInstance choose(String serviceId) { - return this.instance; - } - - @Override - public T execute(String serviceId, LoadBalancerRequest request) { - try { - return request.apply(this.instance); - } - catch (Exception ex) { - ReflectionUtils.rethrowRuntimeException(ex); - } - return null; - } - - @Override - public T execute(String s, ServiceInstance serviceInstance, LoadBalancerRequest request) throws IOException { - try { - return request.apply(this.instance); - } - catch (Exception ex) { - ReflectionUtils.rethrowRuntimeException(ex); - } - return null; - } - - @Override - public URI reconstructURI(ServiceInstance instance, URI original) { - return UriComponentsBuilder.fromUri(original).host(instance.getHost()) - .port(instance.getPort()).build().toUri(); - } - - } - -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicyFactoryTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicyFactoryTests.java deleted file mode 100644 index bfaee124..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicyFactoryTests.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.io.IOException; -import java.util.Collections; -import java.util.Map; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonServer; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpRequest; -import com.netflix.client.DefaultLoadBalancerRetryHandler; -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.BaseLoadBalancer; -import com.netflix.loadbalancer.LoadBalancerStats; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerStats; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.anyString; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -/** - * @author Ryan Baxter - */ -public class RibbonLoadBalancedRetryPolicyFactoryTests { - - @Mock - private SpringClientFactory clientFactory; - - @Mock - private BaseLoadBalancer loadBalancer; - - @Mock - private LoadBalancerStats loadBalancerStats; - - @Mock - private ServerStats serverStats; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - given(this.clientFactory.getLoadBalancerContext(anyString())).willReturn( - new RibbonLoadBalancerContext(this.loadBalancer)); - given(this.clientFactory.getInstance(anyString(), eq(ServerIntrospector.class))) - .willReturn(new DefaultServerIntrospector() { - @Override - public Map getMetadata(Server server) { - return Collections.singletonMap("mykey", "myvalue"); - } - }); - - } - - @After - public void tearDown() throws Exception {} - - @Test - public void testGetRetryPolicyNoRetry() throws Exception { - int sameServer = 0; - int nextServer = 0; - boolean retryOnAllOps = false; - RibbonServer server = getRibbonServer(); - IClientConfig config = mock(IClientConfig.class); - doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(sameServer).when(config).getPropertyAsInteger(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(nextServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(nextServer).when(config).getPropertyAsInteger(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(retryOnAllOps).when(config).get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); - doReturn(retryOnAllOps).when(config).getPropertyAsBoolean(eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); - doReturn("").when(config).getPropertyAsString(eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES),eq("")); - doReturn(server.getServiceId()).when(config).getClientName(); - doReturn(config).when(clientFactory).getClientConfig(eq(server.getServiceId())); - clientFactory.getLoadBalancerContext(server.getServiceId()).setRetryHandler(new DefaultLoadBalancerRetryHandler(config)); - RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - RibbonLoadBalancedRetryPolicyFactory factory = new RibbonLoadBalancedRetryPolicyFactory(clientFactory); - LoadBalancedRetryPolicy policy = factory.create(server.getServiceId(), client); - HttpRequest request = mock(HttpRequest.class); - doReturn(HttpMethod.GET).when(request).getMethod(); - LoadBalancedRetryContext context = new LoadBalancedRetryContext(null, request); - assertThat(policy.canRetryNextServer(context), is(true)); - assertThat(policy.canRetrySameServer(context), is(false)); - assertThat(policy.retryableStatusCode(400), is(false)); - } - - @Test - public void testGetRetryPolicyNotGet() throws Exception { - int sameServer = 3; - int nextServer = 3; - boolean retryOnAllOps = false; - RibbonServer server = getRibbonServer(); - IClientConfig config = mock(IClientConfig.class); - doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(sameServer).when(config).getPropertyAsInteger(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(nextServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(nextServer).when(config).getPropertyAsInteger(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(retryOnAllOps).when(config).get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); - doReturn(retryOnAllOps).when(config).getPropertyAsBoolean(eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); - doReturn("").when(config).getPropertyAsString(eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES),eq("")); - doReturn(server.getServiceId()).when(config).getClientName(); - doReturn(config).when(clientFactory).getClientConfig(eq(server.getServiceId())); - clientFactory.getLoadBalancerContext(server.getServiceId()).setRetryHandler(new DefaultLoadBalancerRetryHandler(config)); - RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - RibbonLoadBalancedRetryPolicyFactory factory = new RibbonLoadBalancedRetryPolicyFactory(clientFactory); - LoadBalancedRetryPolicy policy = factory.create(server.getServiceId(), client); - HttpRequest request = mock(HttpRequest.class); - doReturn(HttpMethod.POST).when(request).getMethod(); - LoadBalancedRetryContext context = new LoadBalancedRetryContext(null, request); - assertThat(policy.canRetryNextServer(context), is(false)); - assertThat(policy.canRetrySameServer(context), is(false)); - assertThat(policy.retryableStatusCode(400), is(false)); - } - - @Test - public void testGetRetryPolicyRetryOnNonGet() throws Exception { - int sameServer = 3; - int nextServer = 3; - boolean retryOnAllOps = true; - RibbonServer server = getRibbonServer(); - IClientConfig config = mock(IClientConfig.class); - doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(sameServer).when(config).getPropertyAsInteger(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(nextServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(nextServer).when(config).getPropertyAsInteger(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(retryOnAllOps).when(config).get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); - doReturn(retryOnAllOps).when(config).getPropertyAsBoolean(eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); - doReturn("").when(config).getPropertyAsString(eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES),eq("")); - doReturn(server.getServiceId()).when(config).getClientName(); - doReturn(config).when(clientFactory).getClientConfig(eq(server.getServiceId())); - clientFactory.getLoadBalancerContext(server.getServiceId()).initWithNiwsConfig(config); - RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - RibbonLoadBalancedRetryPolicyFactory factory = new RibbonLoadBalancedRetryPolicyFactory(clientFactory); - LoadBalancedRetryPolicy policy = factory.create(server.getServiceId(), client); - HttpRequest request = mock(HttpRequest.class); - doReturn(HttpMethod.POST).when(request).getMethod(); - LoadBalancedRetryContext context = new LoadBalancedRetryContext(null, request); - assertThat(policy.canRetryNextServer(context), is(true)); - assertThat(policy.canRetrySameServer(context), is(true)); - assertThat(policy.retryableStatusCode(400), is(false)); - } - - @Test - public void testGetRetryPolicyRetryCount() throws Exception { - int sameServer = 3; - int nextServer = 3; - RibbonServer server = getRibbonServer(); - IClientConfig config = mock(IClientConfig.class); - doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(nextServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(false).when(config).get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false)); - doReturn(config).when(clientFactory).getClientConfig(eq(server.getServiceId())); - doReturn("").when(config).getPropertyAsString(eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES),eq("")); - clientFactory.getLoadBalancerContext(server.getServiceId()).setRetryHandler(new DefaultLoadBalancerRetryHandler(config)); - RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - RibbonLoadBalancedRetryPolicyFactory factory = new RibbonLoadBalancedRetryPolicyFactory(clientFactory); - LoadBalancedRetryPolicy policy = factory.create(server.getServiceId(), client); - HttpRequest request = mock(HttpRequest.class); - doReturn(HttpMethod.GET).when(request).getMethod(); - LoadBalancedRetryContext context = spy(new LoadBalancedRetryContext(null, request)); - //Loop through as if we are retrying a request until we exhaust the number of retries - //outer loop is for next server retries - //inner loop is for same server retries - for(int i = 0; i < nextServer + 1; i++) { - //iterate once time beyond the same server retry limit to cause us to reset - //the same sever counter and increment the next server counter - for(int j = 0; j < sameServer + 1; j++) { - if(j < 3) { - assertThat(policy.canRetrySameServer(context), is(true)); - } else { - assertThat(policy.canRetrySameServer(context), is(false)); - } - policy.registerThrowable(context, new IOException()); - } - if(i < 3) { - assertThat(policy.canRetryNextServer(context), is(true)); - } else { - assertThat(policy.canRetryNextServer(context), is(false)); - } - } - assertThat(context.isExhaustedOnly(), is(true)); - assertThat(policy.retryableStatusCode(400), is(false)); - verify(context, times(4)).setServiceInstance(any(ServiceInstance.class)); - } - - @Test - public void testRetryableStatusCodes() throws Exception { - int sameServer = 3; - int nextServer = 3; - RibbonServer server = getRibbonServer(); - IClientConfig config = mock(IClientConfig.class); - doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(nextServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(false).when(config).get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false)); - doReturn(config).when(clientFactory).getClientConfig(eq(server.getServiceId())); - doReturn("404, 418,502,foo, ,").when(config).getPropertyAsString(eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES),eq("")); - clientFactory.getLoadBalancerContext(server.getServiceId()).setRetryHandler(new DefaultLoadBalancerRetryHandler(config)); - RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - RibbonLoadBalancedRetryPolicyFactory factory = new RibbonLoadBalancedRetryPolicyFactory(clientFactory); - LoadBalancedRetryPolicy policy = factory.create(server.getServiceId(), client); - HttpRequest request = mock(HttpRequest.class); - doReturn(HttpMethod.GET).when(request).getMethod(); - assertThat(policy.retryableStatusCode(400), is(false)); - assertThat(policy.retryableStatusCode(404), is(true)); - assertThat(policy.retryableStatusCode(418), is(true)); - assertThat(policy.retryableStatusCode(502), is(true)); - } - - protected RibbonLoadBalancerClient getRibbonLoadBalancerClient( - RibbonServer ribbonServer) { - given(this.loadBalancer.getName()).willReturn(ribbonServer.getServiceId()); - given(this.loadBalancer.chooseServer(anyObject())).willReturn( - ribbonServer.getServer()); - given(this.loadBalancer.getLoadBalancerStats()) - .willReturn(this.loadBalancerStats); - given(this.loadBalancerStats.getSingleServerStat(ribbonServer.getServer())) - .willReturn(this.serverStats); - given(this.clientFactory.getLoadBalancer(this.loadBalancer.getName())) - .willReturn(this.loadBalancer); - return new RibbonLoadBalancerClient(this.clientFactory); - } - - protected RibbonServer getRibbonServer() { - return new RibbonServer("testService", new Server("myhost", 9080), false, - Collections.singletonMap("mykey", "myvalue")); - } - -} \ No newline at end of file diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClientTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClientTests.java deleted file mode 100644 index 8f4c5cde..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClientTests.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.io.IOException; -import java.net.URI; -import java.net.URL; -import java.util.Collections; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.loadbalancer.LoadBalancerRequest; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonServer; -import org.springframework.web.util.DefaultUriBuilderFactory; - -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.BaseLoadBalancer; -import com.netflix.loadbalancer.LoadBalancerStats; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerStats; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.anyDouble; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * @author Spencer Gibb - */ -public class RibbonLoadBalancerClientTests { - - @Mock - private SpringClientFactory clientFactory; - - @Mock - private BaseLoadBalancer loadBalancer; - - @Mock - private LoadBalancerStats loadBalancerStats; - - @Mock - private ServerStats serverStats; - - @Before - public void init() { - MockitoAnnotations.initMocks(this); - given(this.clientFactory.getLoadBalancerContext(anyString())).willReturn( - new RibbonLoadBalancerContext(this.loadBalancer)); - given(this.clientFactory.getInstance(anyString(), eq(ServerIntrospector.class))) - .willReturn(new DefaultServerIntrospector() { - @Override - public Map getMetadata(Server server) { - return Collections.singletonMap("mykey", "myvalue"); - } - }); - } - - @Test - public void reconstructURI() throws Exception { - testReconstructURI("http"); - } - - @Test - public void reconstructSecureURI() throws Exception { - testReconstructURI("https"); - } - - private void testReconstructURI(String scheme) throws Exception { - RibbonServer server = getRibbonServer(); - RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - ServiceInstance serviceInstance = client.choose(server.getServiceId()); - URI uri = client.reconstructURI(serviceInstance, - new URL(scheme + "://" + server.getServiceId()).toURI()); - assertThat(uri).hasScheme(scheme) - .hasHost(serviceInstance.getHost()) - .hasPort(serviceInstance.getPort()); - } - - @Test - public void testReconstructSecureUriWithSpecialCharsPath() { - testReconstructUriWithPath("https", "/foo=|"); - } - - @Test - public void testReconstructUnsecureUriWithSpecialCharsPath() { - testReconstructUriWithPath("http", "/foo=|"); - } - - private void testReconstructUriWithPath(String scheme, String path) { - RibbonServer server = getRibbonServer(); - IClientConfig config = mock(IClientConfig.class); - when(config.get(CommonClientConfigKey.IsSecure)).thenReturn(true); - when(clientFactory.getClientConfig(server.getServiceId())).thenReturn(config); - - RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - ServiceInstance serviceInstance = client.choose(server.getServiceId()); - - URI expanded = new DefaultUriBuilderFactory() - .expand(scheme + "://" + server.getServiceId() + path); - URI reconstructed = client.reconstructURI(serviceInstance, expanded); - assertThat(reconstructed).hasPath(path); - } - - @Test - public void testReconstructHonorsRibbonServerScheme() { - RibbonServer server = new RibbonServer("testService", - new Server("ws", "myhost", 9080), false, - Collections.singletonMap("mykey", "myvalue")); - - IClientConfig config = mock(IClientConfig.class); - when(config.get(CommonClientConfigKey.IsSecure)).thenReturn(false); - when(clientFactory.getClientConfig(server.getServiceId())).thenReturn(config); - - RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - ServiceInstance serviceInstance = client.choose(server.getServiceId()); - URI uri = client.reconstructURI(serviceInstance, URI.create("http://testService")); - - assertThat(uri).hasScheme("ws").hasHost("myhost").hasPort(9080); - } - - @Test - public void testReconstructUriWithSecureClientConfig() throws Exception { - RibbonServer server = getRibbonServer(); - IClientConfig config = mock(IClientConfig.class); - when(config.get(CommonClientConfigKey.IsSecure)).thenReturn(true); - when(clientFactory.getClientConfig(server.getServiceId())).thenReturn(config); - - RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - ServiceInstance serviceInstance = client.choose(server.getServiceId()); - URI uri = client.reconstructURI(serviceInstance, - new URL("http://" + server.getServiceId()).toURI()); - assertEquals(server.getHost(), uri.getHost()); - assertEquals(server.getPort(), uri.getPort()); - assertEquals("https", uri.getScheme()); - } - - @Test - public void testReconstructSecureUriWithoutScheme() throws Exception { - testReconstructSchemelessUriWithoutClientConfig(getSecureRibbonServer(), "https"); - } - - @Test - public void testReconstructUnsecureSchemelessUri() throws Exception { - testReconstructSchemelessUriWithoutClientConfig(getRibbonServer(), "http"); - } - - public void testReconstructSchemelessUriWithoutClientConfig(RibbonServer server, String expectedScheme) - throws Exception { - IClientConfig config = mock(IClientConfig.class); - when(config.get(CommonClientConfigKey.IsSecure)).thenReturn(null); - when(clientFactory.getClientConfig(server.getServiceId())).thenReturn(config); - - RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - ServiceInstance serviceInstance = client.choose(server.getServiceId()); - URI uri = client.reconstructURI(serviceInstance, - new URI("//" + server.getServiceId())); - assertEquals(server.getHost(), uri.getHost()); - assertEquals(server.getPort(), uri.getPort()); - assertEquals(expectedScheme, uri.getScheme()); - } - - @Test - public void testChoose() { - RibbonServer server = getRibbonServer(); - RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - ServiceInstance serviceInstance = client.choose(server.getServiceId()); - assertServiceInstance(server, serviceInstance); - } - - @Test - public void testChooseMissing() { - given(this.clientFactory.getLoadBalancer(this.loadBalancer.getName())) - .willReturn(null); - given(this.loadBalancer.getName()).willReturn("missingservice"); - RibbonLoadBalancerClient client = new RibbonLoadBalancerClient(this.clientFactory); - ServiceInstance instance = client.choose("missingservice"); - assertNull("instance wasn't null", instance); - } - - @Test - public void testExecute() throws IOException { - final RibbonServer server = getRibbonServer(); - RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - final String returnVal = "myval"; - Object actualReturn = client.execute(server.getServiceId(), - (LoadBalancerRequest) instance -> { - assertServiceInstance(server, instance); - return returnVal; - }); - verifyServerStats(); - assertEquals("retVal was wrong", returnVal, actualReturn); - } - - @Test - public void testExecuteException() { - final RibbonServer ribbonServer = getRibbonServer(); - RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(ribbonServer); - try { - client.execute(ribbonServer.getServiceId(), - instance -> { - assertServiceInstance(ribbonServer, instance); - throw new RuntimeException(); - }); - fail("Should have thrown exception"); - } - catch (Exception ex) { - assertNotNull(ex); - } - verifyServerStats(); - } - - @Test - public void testExecuteIOException() { - final RibbonServer ribbonServer = getRibbonServer(); - RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(ribbonServer); - try { - client.execute(ribbonServer.getServiceId(), - instance -> { - assertServiceInstance(ribbonServer, instance); - throw new IOException(); - }); - fail("Should have thrown exception"); - } - catch (Exception ex) { - assertThat(ex).isInstanceOf(IOException.class); - } - verifyServerStats(); - } - - protected RibbonServer getRibbonServer() { - return new RibbonServer("testService", new Server("myhost", 9080), false, - Collections.singletonMap("mykey", "myvalue")); - } - - protected RibbonServer getSecureRibbonServer() { - return new RibbonServer("testService", new Server("myhost", 8443), false, - Collections.singletonMap("mykey", "myvalue")); - } - - protected void verifyServerStats() { - verify(this.serverStats).incrementActiveRequestsCount(); - verify(this.serverStats).decrementActiveRequestsCount(); - verify(this.serverStats).incrementNumRequests(); - verify(this.serverStats).noteResponseTime(anyDouble()); - } - - protected void assertServiceInstance(RibbonServer ribbonServer, - ServiceInstance instance) { - assertNotNull("instance was null", instance); - assertEquals("serviceId was wrong", ribbonServer.getServiceId(), - instance.getServiceId()); - assertEquals("host was wrong", ribbonServer.getHost(), instance.getHost()); - assertEquals("port was wrong", ribbonServer.getPort(), instance.getPort()); - assertEquals("missing metadata", ribbonServer.getMetadata().get("mykey"), - instance.getMetadata().get("mykey")); - } - - protected RibbonLoadBalancerClient getRibbonLoadBalancerClient( - RibbonServer ribbonServer) { - given(this.loadBalancer.getName()).willReturn(ribbonServer.getServiceId()); - given(this.loadBalancer.chooseServer(anyObject())).willReturn( - ribbonServer.getServer()); - given(this.loadBalancer.getLoadBalancerStats()) - .willReturn(this.loadBalancerStats); - given(this.loadBalancerStats.getSingleServerStat(ribbonServer.getServer())) - .willReturn(this.serverStats); - given(this.clientFactory.getLoadBalancer(this.loadBalancer.getName())) - .willReturn(this.loadBalancer); - return new RibbonLoadBalancerClient(this.clientFactory); - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonUtilsTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonUtilsTests.java deleted file mode 100644 index 13051356..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonUtilsTests.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Map; -import org.junit.Assert; -import org.junit.Test; -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.loadbalancer.Server; - -import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.netflix.ribbon.RibbonUtils.isSecure; -import static org.springframework.cloud.netflix.ribbon.RibbonUtils.updateToSecureConnectionIfNeeded; - -/** - * @author Spencer Gibb - * @author Jacques-Etienne Beaudet - * @author Tim Ysewyn - */ -public class RibbonUtilsTests { - - private static final ServerIntrospector NON_SECURE_INTROSPECTOR = new StaticServerIntrospector(false); - private static final ServerIntrospector SECURE_INTROSPECTOR = new StaticServerIntrospector(true); - private static final Server SERVER = new Server("localhost", 8080); - private static final DefaultClientConfigImpl SECURE_CONFIG = getConfig(true); - private static final DefaultClientConfigImpl NON_SECURE_CONFIG = getConfig(false); - private static final DefaultClientConfigImpl NO_IS_SECURE_CONFIG = new DefaultClientConfigImpl(); - - @Test - public void noRibbonPropSecureIntrospector() { - boolean secure = isSecure(NO_IS_SECURE_CONFIG, SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("isSecure was wrong", secure, is(true)); - } - - @Test - public void noRibbonPropNonSecureIntrospector() { - boolean secure = isSecure(NO_IS_SECURE_CONFIG, NON_SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("isSecure was wrong", secure, is(false)); - } - - @Test - public void isSecureRibbonPropSecureIntrospector() { - boolean secure = isSecure(SECURE_CONFIG, SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("isSecure was wrong", secure, is(true)); - } - - @Test - public void nonSecureRibbonPropNonSecureIntrospector() { - boolean secure = isSecure(NON_SECURE_CONFIG, NON_SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("isSecure was wrong", secure, is(false)); - } - - @Test - public void isSecureRibbonPropNonSecureIntrospector() { - boolean secure = isSecure(SECURE_CONFIG, NON_SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("isSecure was wrong", secure, is(true)); - } - - @Test - public void nonSecureRibbonPropSecureIntrospector() { - boolean secure = isSecure(NON_SECURE_CONFIG, SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("isSecure was wrong", secure, is(false)); - } - - @Test - public void uriIsNotChangedWhenServerIsNotSecured() throws URISyntaxException { - URI original = new URI("http://foo"); - URI updated = updateToSecureConnectionIfNeeded(original, NON_SECURE_CONFIG, NON_SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("URI should not have been updated since server is not secured.", original, is(updated)); - } - - @Test - public void uriIsNotChangedWhenServerIsSecuredAndUriAlreadyInHttps() throws URISyntaxException { - URI original = new URI("https://foo"); - URI updated = updateToSecureConnectionIfNeeded(original, SECURE_CONFIG, SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("URI should not have been updated since uri is already in https.", original, is(updated)); - } - - @Test - public void shouldUpgradeUriToHttpsWhenServerIsSecureAndUriNotInHttps() throws URISyntaxException { - URI original = new URI("http://foo"); - URI updated = updateToSecureConnectionIfNeeded(original, SECURE_CONFIG, SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("URI should have been updated to https.", updated, is(new URI("https://foo"))); - } - - @Test - public void shouldUpgradeUriToWssWhenServerIsSecureAndUriNotInWss() throws URISyntaxException { - URI original = new URI("ws://foo"); - URI updated = updateToSecureConnectionIfNeeded(original, SECURE_CONFIG, SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("URI should have been updated to wss.", updated, is(new URI("wss://foo"))); - } - - @Test - public void shouldSubstitutePlusInQueryParam() throws URISyntaxException { - URI original = new URI("http://foo/%20bar?hello=1+2"); - URI updated = updateToSecureConnectionIfNeeded(original, SECURE_CONFIG, SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("URI should have had its plus sign replaced in query string.", updated, is(new URI( - "https://foo/%20bar?hello=1%202"))); - } - - @Test - public void emptyStringUri() throws URISyntaxException { - URI original = new URI(""); - URI updated = updateToSecureConnectionIfNeeded(original, SECURE_CONFIG, SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("URI should be the emptry string", updated, is(new URI( - ""))); - } - - static DefaultClientConfigImpl getConfig(boolean value) { - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.setProperty(CommonClientConfigKey.IsSecure, value); - return config; - } - - static class StaticServerIntrospector implements ServerIntrospector { - - final boolean secure; - - public StaticServerIntrospector(boolean secure) { - this.secure = secure; - } - - @Override - public boolean isSecure(Server server) { - return this.secure; - } - - @Override - public Map getMetadata(Server server) { - return null; - } - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringClientFactoryTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringClientFactoryTests.java deleted file mode 100644 index 44070a9e..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringClientFactoryTests.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import org.apache.http.client.params.ClientPNames; -import org.apache.http.client.params.CookiePolicy; -import org.junit.Test; -import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import com.netflix.client.DefaultLoadBalancerRetryHandler; -import com.netflix.client.IClientConfigAware; -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; -import com.netflix.niws.client.http.RestClient; -import com.sun.jersey.client.apache4.ApacheHttpClient4; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.springframework.boot.test.util.EnvironmentTestUtils.addEnvironment; - -/** - * @author Dave Syer - * - */ -public class SpringClientFactoryTests { - - public static class ClientConfigInjectedByConstructor { - - private IClientConfig clientConfig; - - public ClientConfigInjectedByConstructor(IClientConfig clientConfig) { - this.clientConfig = clientConfig; - } - } - - public static class ClientConfigInjectedByInitMethod implements IClientConfigAware { - - private IClientConfig clientConfig; - - @Override - public void initWithNiwsConfig(IClientConfig clientConfig) { - this.clientConfig = clientConfig; - } - } - - public static class NoClientConfigAware { - - public NoClientConfigAware() { - // no client config - } - } - - @Test - public void testConfigureRetry() { - SpringClientFactory factory = new SpringClientFactory(); - AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext( - RibbonAutoConfiguration.class, ArchaiusAutoConfiguration.class, HttpClientConfiguration.class); - addEnvironment(parent, "foo.ribbon.MaxAutoRetries:2"); - factory.setApplicationContext(parent); - DefaultLoadBalancerRetryHandler retryHandler = (DefaultLoadBalancerRetryHandler) factory - .getLoadBalancerContext("foo").getRetryHandler(); - assertEquals(2, retryHandler.getMaxRetriesOnSameServer()); - parent.close(); - factory.destroy(); - } - - @SuppressWarnings("deprecation") - @Test - public void testCookiePolicy() { - SpringClientFactory factory = new SpringClientFactory(); - AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(); - addEnvironment(parent, "ribbon.restclient.enabled=true"); - parent.register(RibbonAutoConfiguration.class, ArchaiusAutoConfiguration.class); - parent.refresh(); - factory.setApplicationContext(parent); - RestClient client = factory.getClient("foo", RestClient.class); - ApacheHttpClient4 jerseyClient = (ApacheHttpClient4) client.getJerseyClient(); - assertEquals(CookiePolicy.IGNORE_COOKIES, jerseyClient.getClientHandler() - .getHttpClient().getParams().getParameter(ClientPNames.COOKIE_POLICY)); - parent.close(); - factory.destroy(); - } - - @Test - public void testInstantiateWithConfigInjectByConstructor() { - IClientConfig clientConfig = new DefaultClientConfigImpl(); - ClientConfigInjectedByConstructor instance = SpringClientFactory.instantiateWithConfig(ClientConfigInjectedByConstructor.class, clientConfig); - assertThat(instance.clientConfig).isSameAs(clientConfig); - } - - @Test - public void testInstantiateWithConfigInjectedByInitMethod() { - IClientConfig clientConfig = new DefaultClientConfigImpl(); - ClientConfigInjectedByInitMethod instance = SpringClientFactory.instantiateWithConfig(ClientConfigInjectedByInitMethod.class, clientConfig); - assertThat(instance.clientConfig).isSameAs(clientConfig); - } - - @Test - public void testInstantiateWithoutConfig() { - IClientConfig clientConfig = new DefaultClientConfigImpl(); - NoClientConfigAware instance = SpringClientFactory.instantiateWithConfig(NoClientConfigAware.class, clientConfig); - assertThat(instance).isNotNull(); - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringRetryDisabledTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringRetryDisabledTests.java deleted file mode 100644 index 05fa3441..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringRetryDisabledTests.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.util.Map; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicyFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient; -import org.springframework.cloud.test.ClassPathExclusions; -import org.springframework.cloud.test.ModifiedClassPathRunner; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.instanceOf; - -/** - * @author Ryan Baxter - * @author Biju Kunjummen - */ -@RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions({"spring-retry-*.jar", "spring-boot-starter-aop-*.jar"}) -public class SpringRetryDisabledTests { - - @Test - public void testLoadBalancedRetryFactoryBean() { - new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RibbonAutoConfiguration.class, - LoadBalancerAutoConfiguration.class, - RibbonClientConfiguration.class)) - .run(context -> { - Map factories = context.getBeansOfType(LoadBalancedRetryPolicyFactory.class); - assertThat(factories.values(), hasSize(1)); - assertThat(factories.values().toArray()[0], instanceOf(LoadBalancedRetryPolicyFactory.NeverRetryFactory.class)); - Map clients = context.getBeansOfType(RibbonLoadBalancingHttpClient.class); - assertThat(clients.values(), hasSize(1)); - assertThat(clients.values().toArray()[0], instanceOf(RibbonLoadBalancingHttpClient.class)); - }); - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringRetryEnabledTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringRetryEnabledTests.java deleted file mode 100644 index 1c66f951..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringRetryEnabledTests.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.BeansException; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicyFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration; -import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; -import org.springframework.cloud.netflix.ribbon.apache.RetryableRibbonLoadBalancingHttpClient; -import org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.collection.IsCollectionWithSize.hasSize; - -/** - * @author Ryan Baxter - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {RibbonAutoConfiguration.class, RibbonClientConfiguration.class, LoadBalancerAutoConfiguration.class, - HttpClientConfiguration.class}) -public class SpringRetryEnabledTests implements ApplicationContextAware { - - private ApplicationContext context; - - @Test - public void testLoadBalancedRetryFactoryBean() throws Exception { - Map factories = context.getBeansOfType(LoadBalancedRetryPolicyFactory.class); - assertThat(factories.values(), hasSize(1)); - assertThat(factories.values().toArray()[0], instanceOf(RibbonLoadBalancedRetryPolicyFactory.class)); - Map clients = context.getBeansOfType(RibbonLoadBalancingHttpClient.class); - assertThat(clients.values(), hasSize(1)); - assertThat(clients.values().toArray()[0], instanceOf(RetryableRibbonLoadBalancingHttpClient.class)); - } - - @Override - public void setApplicationContext(ApplicationContext context) throws BeansException { - this.context = context; - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilterTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilterTests.java deleted file mode 100644 index 6dfefc59..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilterTests.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon; - -import java.util.Arrays; -import java.util.List; -import org.junit.Before; -import org.junit.Test; -import org.springframework.test.util.ReflectionTestUtils; -import com.netflix.loadbalancer.Server; - -import static org.junit.Assert.assertEquals; - -/** - * @author Dave Syer - */ -public class ZonePreferenceServerListFilterTests { - - private Server dsyer = new Server("dsyer", 8080); - private Server localhost = new Server("localhost", 8080); - - @Before - public void init() { - this.dsyer.setZone("dsyer"); - this.localhost.setZone("localhost"); - } - - @Test - public void noZoneSet() { - ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter(); - List result = filter.getFilteredListOfServers(Arrays - .asList(this.localhost)); - assertEquals(1, result.size()); - } - - @Test - public void withZoneSetAndNoMatches() { - ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter(); - ReflectionTestUtils.setField(filter, "zone", "dsyer"); - List result = filter.getFilteredListOfServers(Arrays - .asList(this.localhost)); - assertEquals(1, result.size()); - } - - @Test - public void withZoneSetAndMatches() { - ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter(); - ReflectionTestUtils.setField(filter, "zone", "dsyer"); - List result = filter.getFilteredListOfServers(Arrays.asList(this.dsyer, - this.localhost)); - assertEquals(1, result.size()); - } - -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequestTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequestTests.java deleted file mode 100644 index c1662126..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequestTests.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon.apache; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.net.URI; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Collections; -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.methods.RequestBuilder; -import org.junit.Test; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.StreamUtils; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; - -/** - * @author Spencer Gibb - */ -public class RibbonApacheHttpRequestTests { - - @Test - public void testNullEntity() throws Exception { - String uri = "http://example.com"; - LinkedMultiValueMap headers = new LinkedMultiValueMap<>(); - headers.add("my-header", "my-value"); - headers.add("content-length", "5192"); - LinkedMultiValueMap params = new LinkedMultiValueMap<>(); - params.add("myparam", "myparamval"); - RibbonApacheHttpRequest httpRequest = - new RibbonApacheHttpRequest( - new RibbonCommandContext("example", "GET", uri, false, headers, params, null, new ArrayList())); - - HttpUriRequest request = httpRequest.toRequest(RequestConfig.custom().build()); - - assertThat("request is wrong type", request, is(not(instanceOf(HttpEntityEnclosingRequest.class)))); - assertThat("uri is wrong", request.getURI().toString(), startsWith(uri)); - assertThat("my-header is missing", request.getFirstHeader("my-header"), is(notNullValue())); - assertThat("my-header is wrong", request.getFirstHeader("my-header").getValue(), is(equalTo("my-value"))); - assertThat("Content-Length is wrong", request.getFirstHeader("content-length").getValue(), is(equalTo("5192"))); - assertThat("myparam is missing", request.getURI().getQuery(), is(equalTo("myparam=myparamval"))); - - } - - @Test - // this situation happens, see https://github.com/spring-cloud/spring-cloud-netflix/issues/1042#issuecomment-227723877 - public void testEmptyEntityGet() throws Exception { - String entityValue = ""; - testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), false, "GET"); - } - - @Test - public void testNonEmptyEntityPost() throws Exception { - String entityValue = "abcd"; - testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), true, "POST"); - } - - void testEntity(String entityValue, ByteArrayInputStream requestEntity, boolean addContentLengthHeader, String method) throws IOException { - String lengthString = String.valueOf(entityValue.length()); - Long length = null; - URI uri = URI.create("http://example.com"); - LinkedMultiValueMap headers = new LinkedMultiValueMap<>(); - if (addContentLengthHeader) { - headers.add("Content-Length", lengthString); - length = (long) entityValue.length(); - } - - RibbonRequestCustomizer requestCustomizer = new RibbonRequestCustomizer() { - @Override - public boolean accepts(Class builderClass) { - return builderClass == RequestBuilder.class; - } - - @Override - public void customize(RequestBuilder builder) { - builder.addHeader("from-customizer", "foo"); - } - }; - RibbonCommandContext context = new RibbonCommandContext("example", method, - uri.toString(), false, headers, new LinkedMultiValueMap(), - requestEntity, Collections.singletonList(requestCustomizer)); - context.setContentLength(length); - RibbonApacheHttpRequest httpRequest = new RibbonApacheHttpRequest(context); - - HttpUriRequest request = httpRequest.toRequest(RequestConfig.custom().build()); - - assertThat("request is wrong type", request, is(instanceOf(HttpEntityEnclosingRequest.class))); - assertThat("uri is wrong", request.getURI().toString(), startsWith(uri.toString())); - if (addContentLengthHeader) { - assertThat("Content-Length is missing", request.getFirstHeader("Content-Length"), is(notNullValue())); - assertThat("Content-Length is wrong", request.getFirstHeader("Content-Length").getValue(), - is(equalTo(lengthString))); - } - assertThat("from-customizer is missing", request.getFirstHeader("from-customizer"), is(notNullValue())); - assertThat("from-customizer is wrong", request.getFirstHeader("from-customizer").getValue(), - is(equalTo("foo"))); - - HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - assertThat("entity is missing", entityRequest.getEntity(), is(notNullValue())); - HttpEntity entity = entityRequest.getEntity(); - assertThat("contentLength is wrong", entity.getContentLength(), is(equalTo((long)entityValue.length()))); - assertThat("content is missing", entity.getContent(), is(notNullValue())); - String string = StreamUtils.copyToString(entity.getContent(), Charset.forName("UTF-8")); - assertThat("content is wrong", string, is(equalTo(entityValue))); - } -} - diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponseTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponseTests.java deleted file mode 100644 index 0611dd0b..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponseTests.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.apache; - -import java.io.ByteArrayInputStream; -import java.net.URI; -import org.apache.http.HttpResponse; -import org.apache.http.StatusLine; -import org.apache.http.entity.BasicHttpEntity; -import org.junit.Test; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.mock; - -/** - * @author Spencer Gibb - */ -public class RibbonApacheHttpResponseTests { - - @Test - public void testNullEntity() throws Exception { - StatusLine statusLine = mock(StatusLine.class); - given(statusLine.getStatusCode()).willReturn(204); - HttpResponse response = mock(HttpResponse.class); - given(response.getStatusLine()).willReturn(statusLine); - - RibbonApacheHttpResponse httpResponse = new RibbonApacheHttpResponse(response, URI.create("http://example.com")); - - assertThat(httpResponse.isSuccess(), is(true)); - assertThat(httpResponse.hasPayload(), is(false)); - assertThat(httpResponse.getPayload(), is(nullValue())); - assertThat(httpResponse.getInputStream(), is(nullValue())); - } - - - @Test - public void testNotNullEntity() throws Exception { - StatusLine statusLine = mock(StatusLine.class); - given(statusLine.getStatusCode()).willReturn(204); - HttpResponse response = mock(HttpResponse.class); - given(response.getStatusLine()).willReturn(statusLine); - BasicHttpEntity entity = new BasicHttpEntity(); - entity.setContent(new ByteArrayInputStream(new byte[0])); - given(response.getEntity()).willReturn(entity); - - RibbonApacheHttpResponse httpResponse = new RibbonApacheHttpResponse(response, URI.create("http://example.com")); - - assertThat(httpResponse.isSuccess(), is(true)); - assertThat(httpResponse.hasPayload(), is(true)); - assertThat(httpResponse.getPayload(), is(notNullValue())); - assertThat(httpResponse.getInputStream(), is(notNullValue())); - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClientTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClientTests.java deleted file mode 100644 index f72d4bc7..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClientTests.java +++ /dev/null @@ -1,844 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon.apache; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.net.URI; -import java.util.ArrayList; -import org.apache.http.HttpResponse; -import org.apache.http.StatusLine; -import org.apache.http.client.HttpClient; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.ArgumentMatcher; -import org.springframework.cloud.client.loadbalancer.LoadBalancedBackOffPolicyFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryListenerFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicyFactory; -import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancedRetryPolicy; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancedRetryPolicyFactory; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerContext; -import org.springframework.cloud.netflix.ribbon.ServerIntrospector; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -import org.springframework.retry.RetryCallback; -import org.springframework.retry.RetryContext; -import org.springframework.retry.RetryListener; -import org.springframework.retry.TerminatedRetryException; -import org.springframework.retry.backoff.BackOffContext; -import org.springframework.retry.backoff.BackOffInterruptedException; -import org.springframework.retry.backoff.BackOffPolicy; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.util.LinkedMultiValueMap; -import com.netflix.client.DefaultLoadBalancerRetryHandler; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.AbstractLoadBalancer; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.Server; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.argThat; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * @author Sébastien Nussbaumer - * @author Ryan Baxter - * @author Gang Li - */ -public class RibbonLoadBalancingHttpClientTests { - - private ILoadBalancer loadBalancer; - private LoadBalancedBackOffPolicyFactory loadBalancedBackOffPolicyFactory = new LoadBalancedBackOffPolicyFactory.NoBackOffPolicyFactory(); - private LoadBalancedRetryListenerFactory loadBalancedRetryListenerFactory = new LoadBalancedRetryListenerFactory.DefaultRetryListenerFactory(); - - @Before - public void setup() { - loadBalancer = mock(AbstractLoadBalancer.class); - doReturn(new Server("foo.com", 8000)).when(loadBalancer).chooseServer(eq("default")); - doReturn(new Server("foo.com", 8000)).when(loadBalancer).chooseServer(eq("service")); - } - - @After - public void teardown() { - loadBalancer = null; - } - - @Test - public void testRequestConfigUseDefaultsNoOverride() throws Exception { - RequestConfig result = getBuiltRequestConfig(UseDefaults.class, null); - - assertThat(result.isRedirectsEnabled(), is(false)); - } - - @Test - public void testRequestConfigDoNotFollowRedirectsNoOverride() throws Exception { - RequestConfig result = getBuiltRequestConfig(DoNotFollowRedirects.class, null); - - assertThat(result.isRedirectsEnabled(), is(false)); - } - - @Test - public void testRequestConfigFollowRedirectsNoOverride() throws Exception { - RequestConfig result = getBuiltRequestConfig(FollowRedirects.class, null); - - assertThat(result.isRedirectsEnabled(), is(true)); - } - - @Test - public void testTimeouts() throws Exception { - RequestConfig result = getBuiltRequestConfig(Timeouts.class, null); - assertThat(result.getConnectTimeout(), is(60000)); - assertThat(result.getSocketTimeout(), is (50000)); - } - - @Test - public void testDefaultTimeouts() throws Exception { - RequestConfig result = getBuiltRequestConfig(UseDefaults.class, null); - assertThat(result.getConnectTimeout(), is(1000)); - assertThat(result.getSocketTimeout(), is (1000)); - } - - @Test - public void testConnections() throws Exception { - SpringClientFactory factory = new SpringClientFactory(); - factory.setApplicationContext(new AnnotationConfigApplicationContext( - RibbonAutoConfiguration.class, Connections.class)); - RetryableRibbonLoadBalancingHttpClient client = factory.getClient("service", - RetryableRibbonLoadBalancingHttpClient.class); - - HttpClient delegate = client.getDelegate(); - PoolingHttpClientConnectionManager connManager = (PoolingHttpClientConnectionManager) ReflectionTestUtils.getField(delegate, "connManager"); - assertThat(connManager.getMaxTotal(), is(101)); - assertThat(connManager.getDefaultMaxPerRoute(), is(201)); - } - - @Test - public void testRequestConfigDoNotFollowRedirectsOverrideWithFollowRedirects() - throws Exception { - - DefaultClientConfigImpl override = new DefaultClientConfigImpl(); - override.set(CommonClientConfigKey.FollowRedirects, true); - override.set(CommonClientConfigKey.IsSecure, false); - - RequestConfig result = getBuiltRequestConfig(DoNotFollowRedirects.class, override); - - assertThat(result.isRedirectsEnabled(), is(true)); - } - - @Test - public void testRequestConfigFollowRedirectsOverrideWithDoNotFollowRedirects() - throws Exception { - - DefaultClientConfigImpl override = new DefaultClientConfigImpl(); - override.set(CommonClientConfigKey.FollowRedirects, false); - override.set(CommonClientConfigKey.IsSecure, false); - - RequestConfig result = getBuiltRequestConfig(FollowRedirects.class, override); - - assertThat(result.isRedirectsEnabled(), is(false)); - } - - @Test - public void testUpdatedTimeouts() - throws Exception { - SpringClientFactory factory = new SpringClientFactory(); - RequestConfig result = getBuiltRequestConfig(Timeouts.class, null, factory); - assertThat(result.getConnectTimeout(), is(60000)); - assertThat(result.getSocketTimeout(), is (50000)); - IClientConfig config = factory.getClientConfig("service"); - config.set(CommonClientConfigKey.ConnectTimeout, 60); - config.set(CommonClientConfigKey.ReadTimeout, 50); - result = getBuiltRequestConfig(Timeouts.class, null, factory); - assertThat(result.getConnectTimeout(), is(60)); - assertThat(result.getSocketTimeout(), is (50)); - } - - @Test - public void testNeverRetry() throws Exception { - ServerIntrospector introspector = mock(ServerIntrospector.class); - CloseableHttpClient delegate = mock(CloseableHttpClient.class); - HttpResponse response = mock(HttpResponse.class); - doThrow(new IOException("boom")).when(delegate).execute(any(HttpUriRequest.class)); - DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); - clientConfig.setClientName("foo"); - RibbonLoadBalancingHttpClient client = new RibbonLoadBalancingHttpClient(delegate, clientConfig, - introspector); - RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); - when(request.toRequest(any(RequestConfig.class))).thenReturn(mock(HttpUriRequest.class)); - try { - client.execute(request, null); - fail("Expected IOException"); - } catch(IOException e) {} finally { - verify(delegate, times(1)).execute(any(HttpUriRequest.class)); - } - } - - private RetryableRibbonLoadBalancingHttpClient setupClientForRetry(int retriesNextServer, int retriesSameServer, - boolean retryable, boolean retryOnAllOps, - String serviceName, String host, int port, - CloseableHttpClient delegate, ILoadBalancer lb, String statusCodes, - LoadBalancedBackOffPolicyFactory loadBalancedBackOffPolicyFactory) throws Exception { - return setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, serviceName, host, port, - delegate, lb, statusCodes, loadBalancedBackOffPolicyFactory, false); - } - - private RetryableRibbonLoadBalancingHttpClient setupClientForRetry(int retriesNextServer, int retriesSameServer, - boolean retryable, boolean retryOnAllOps, - String serviceName, String host, int port, - CloseableHttpClient delegate, ILoadBalancer lb, String statusCodes, - LoadBalancedBackOffPolicyFactory loadBalancedBackOffPolicyFactory, - boolean isSecure) throws Exception { - ServerIntrospector introspector = mock(ServerIntrospector.class); - RetryHandler retryHandler = new DefaultLoadBalancerRetryHandler(retriesSameServer, retriesNextServer, retryable); - doReturn(new Server(host, port)).when(lb).chooseServer(eq(serviceName)); - DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); - clientConfig.set(CommonClientConfigKey.OkToRetryOnAllOperations, retryOnAllOps); - clientConfig.set(CommonClientConfigKey.MaxAutoRetriesNextServer, retriesNextServer); - clientConfig.set(CommonClientConfigKey.MaxAutoRetries, retriesSameServer); - clientConfig.set(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES, statusCodes); - clientConfig.set(CommonClientConfigKey.IsSecure, isSecure); - clientConfig.setClientName(serviceName); - RibbonLoadBalancerContext context = new RibbonLoadBalancerContext(lb, clientConfig, retryHandler); - SpringClientFactory clientFactory = mock(SpringClientFactory.class); - doReturn(context).when(clientFactory).getLoadBalancerContext(eq(serviceName)); - doReturn(clientConfig).when(clientFactory).getClientConfig(eq(serviceName)); - LoadBalancedRetryPolicyFactory factory = new RibbonLoadBalancedRetryPolicyFactory(clientFactory); - RetryableRibbonLoadBalancingHttpClient client = new RetryableRibbonLoadBalancingHttpClient(delegate, clientConfig, - introspector, factory, loadBalancedBackOffPolicyFactory); - client.setLoadBalancer(lb); - ReflectionTestUtils.setField(client, "delegate", delegate); - return client; - } - - private RetryableRibbonLoadBalancingHttpClient setupClientForRetry(int retriesNextServer, int retriesSameServer, - boolean retryable, boolean retryOnAllOps, - String serviceName, String host, int port, - CloseableHttpClient delegate, ILoadBalancer lb, String statusCodes, - LoadBalancedBackOffPolicyFactory loadBalancedBackOffPolicyFactory, - boolean isSecure, LoadBalancedRetryListenerFactory loadBalancedRetryListenerFactory) throws Exception { - ServerIntrospector introspector = mock(ServerIntrospector.class); - RetryHandler retryHandler = new DefaultLoadBalancerRetryHandler(retriesSameServer, retriesNextServer, retryable); - doReturn(new Server(host, port)).when(lb).chooseServer(eq(serviceName)); - DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); - clientConfig.set(CommonClientConfigKey.OkToRetryOnAllOperations, retryOnAllOps); - clientConfig.set(CommonClientConfigKey.MaxAutoRetriesNextServer, retriesNextServer); - clientConfig.set(CommonClientConfigKey.MaxAutoRetries, retriesSameServer); - clientConfig.set(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES, statusCodes); - clientConfig.set(CommonClientConfigKey.IsSecure, isSecure); - clientConfig.setClientName(serviceName); - RibbonLoadBalancerContext context = new RibbonLoadBalancerContext(lb, clientConfig, retryHandler); - SpringClientFactory clientFactory = mock(SpringClientFactory.class); - doReturn(context).when(clientFactory).getLoadBalancerContext(eq(serviceName)); - doReturn(clientConfig).when(clientFactory).getClientConfig(eq(serviceName)); - LoadBalancedRetryPolicyFactory factory = new RibbonLoadBalancedRetryPolicyFactory(clientFactory); - RetryableRibbonLoadBalancingHttpClient client = new RetryableRibbonLoadBalancingHttpClient(delegate, clientConfig, - introspector, factory, loadBalancedBackOffPolicyFactory, loadBalancedRetryListenerFactory); - client.setLoadBalancer(lb); - ReflectionTestUtils.setField(client, "delegate", delegate); - return client; - } - - @Test - public void testRetrySameServerOnly() throws Exception { - int retriesNextServer = 0; - int retriesSameServer = 1; - boolean retryable = true; - boolean retryOnAllOps = false; - String serviceName = "foo"; - String host = serviceName; - int port = 80; - HttpMethod method = HttpMethod.GET; - URI uri = new URI("http://" + host + ":" + port); - CloseableHttpClient delegate = mock(CloseableHttpClient.class); - final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); - doReturn(200).when(statusLine).getStatusCode(); - doReturn(statusLine).when(response).getStatusLine(); - doThrow(new IOException("boom")).doReturn(response).when(delegate).execute(any(HttpUriRequest.class)); - ILoadBalancer lb = mock(ILoadBalancer.class); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, - serviceName, host, port, delegate, lb, "", loadBalancedBackOffPolicyFactory); - RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); - doReturn(uri).when(request).getURI(); - doReturn(method).when(request).getMethod(); - doReturn(request).when(request).withNewUri(any(URI.class)); - HttpUriRequest uriRequest = mock(HttpUriRequest.class); - doReturn(uri).when(uriRequest).getURI(); - doReturn(uriRequest).when(request).toRequest(any(RequestConfig.class)); - RibbonApacheHttpResponse returnedResponse = client.execute(request, null); - verify(delegate, times(2)).execute(any(HttpUriRequest.class)); - verify(lb, times(0)).chooseServer(eq(serviceName)); - } - - @Test - public void testRetryNextServer() throws Exception { - int retriesNextServer = 1; - int retriesSameServer = 1; - boolean retryable = true; - boolean retryOnAllOps = false; - String serviceName = "foo"; - String host = serviceName; - int port = 80; - HttpMethod method = HttpMethod.GET; - URI uri = new URI("http://" + host + ":" + port); - CloseableHttpClient delegate = mock(CloseableHttpClient.class); - final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); - doReturn(200).when(statusLine).getStatusCode(); - doReturn(statusLine).when(response).getStatusLine(); - doThrow(new IOException("boom")).doThrow(new IOException("boom again")).doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); - ILoadBalancer lb = mock(ILoadBalancer.class); - MyBackOffPolicyFactory myBackOffPolicyFactory = new MyBackOffPolicyFactory(); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, - serviceName, host, port, delegate, lb, "", myBackOffPolicyFactory); - RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); - doReturn(uri).when(request).getURI(); - doReturn(method).when(request).getMethod(); - doReturn(request).when(request).withNewUri(any(URI.class)); - HttpUriRequest uriRequest = mock(HttpUriRequest.class); - doReturn(uri).when(uriRequest).getURI(); - doReturn(uriRequest).when(request).toRequest(any(RequestConfig.class)); - RibbonApacheHttpResponse returnedResponse = client.execute(request, null); - verify(delegate, times(3)).execute(any(HttpUriRequest.class)); - verify(lb, times(1)).chooseServer(eq(serviceName)); - assertEquals(2, myBackOffPolicyFactory.getCount()); - } - - @Test - public void testRetryOnPost() throws Exception { - int retriesNextServer = 1; - int retriesSameServer = 1; - boolean retryable = true; - boolean retryOnAllOps = true; - String serviceName = "foo"; - String host = serviceName; - int port = 80; - HttpMethod method = HttpMethod.POST; - URI uri = new URI("http://" + host + ":" + port); - CloseableHttpClient delegate = mock(CloseableHttpClient.class); - final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); - doReturn(200).when(statusLine).getStatusCode(); - doReturn(statusLine).when(response).getStatusLine(); - doThrow(new IOException("boom")).doThrow(new IOException("boom again")).doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); - ILoadBalancer lb = mock(ILoadBalancer.class); - MyBackOffPolicyFactory myBackOffPolicyFactory = new MyBackOffPolicyFactory(); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, - serviceName, host, port, delegate, lb, "", myBackOffPolicyFactory); - RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); - doReturn(method).when(request).getMethod(); - doReturn(uri).when(request).getURI(); - doReturn(request).when(request).withNewUri(any(URI.class)); - HttpUriRequest uriRequest = mock(HttpUriRequest.class); - doReturn(uriRequest).when(request).toRequest(any(RequestConfig.class)); - RibbonApacheHttpResponse returnedResponse = client.execute(request, null); - verify(response, times(0)).close(); - verify(delegate, times(3)).execute(any(HttpUriRequest.class)); - verify(lb, times(1)).chooseServer(eq(serviceName)); - assertEquals(2, myBackOffPolicyFactory.getCount()); - } - - @Test - public void testDoubleEncoding() throws Exception { - String serviceName = "foo"; - String host = serviceName; - int port = 80; - HttpMethod method = HttpMethod.GET; - final URI uri = new URI("https://" + host + ":" + port + "/a%2Bb"); - DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); - clientConfig.setClientName(serviceName); - ServerIntrospector introspector = mock(ServerIntrospector.class); - RibbonCommandContext context = new RibbonCommandContext(serviceName, method.toString(), uri.toString(), false, - new LinkedMultiValueMap(), new LinkedMultiValueMap(), - new ByteArrayInputStream(new String("bar").getBytes()), - new ArrayList()); - RibbonApacheHttpRequest request = new RibbonApacheHttpRequest(context); - CloseableHttpClient delegate = mock(CloseableHttpClient.class); - final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); - doReturn(200).when(statusLine).getStatusCode(); - doReturn(statusLine).when(response).getStatusLine(); - doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); - RibbonLoadBalancingHttpClient client = new RibbonLoadBalancingHttpClient(delegate, clientConfig, introspector); - RibbonApacheHttpResponse returnedResponse = client.execute(request, null); - verify(response, times(0)).close(); - verify(delegate, times(1)).execute(argThat(new ArgumentMatcher() { - @Override - public boolean matches(HttpUriRequest argument) { - if(argument instanceof HttpUriRequest) { - HttpUriRequest arg = (HttpUriRequest)argument; - return arg.getURI().equals(uri); - } - return false; - } - })); - } - - @Test - public void testDoubleEncodingWithRetry() throws Exception { - int retriesNextServer = 0; - int retriesSameServer = 0; - boolean retryable = true; - boolean retryOnAllOps = true; - String serviceName = "foo"; - String host = serviceName; - int port = 80; - HttpMethod method = HttpMethod.GET; - final URI uri = new URI("https://" + host + ":" + port + "/a%20b"); - RibbonCommandContext context = new RibbonCommandContext(serviceName, method.toString(), uri.toString(), true, - new LinkedMultiValueMap(), new LinkedMultiValueMap(), - new ByteArrayInputStream(new String("bar").getBytes()), - new ArrayList()); - RibbonApacheHttpRequest request = new RibbonApacheHttpRequest(context); - CloseableHttpClient delegate = mock(CloseableHttpClient.class); - final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); - doReturn(200).when(statusLine).getStatusCode(); - doReturn(statusLine).when(response).getStatusLine(); - doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); - ILoadBalancer lb = mock(ILoadBalancer.class); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, - serviceName, host, port, delegate, lb, "", loadBalancedBackOffPolicyFactory,true); - client.execute(request, null); - verify(response, times(0)).close(); - verify(delegate, times(1)).execute(argThat(new ArgumentMatcher() { - @Override - public boolean matches(HttpUriRequest argument) { - if(argument instanceof HttpUriRequest) { - HttpUriRequest arg = (HttpUriRequest)argument; - return arg.getURI().equals(uri); - } - return false; - } - })); - } - - @Test - public void testNoRetryOnPost() throws Exception { - int retriesNextServer = 1; - int retriesSameServer = 1; - boolean retryable = true; - boolean retryOnAllOps = false; - String serviceName = "foo"; - String host = serviceName; - int port = 80; - HttpMethod method = HttpMethod.POST; - URI uri = new URI("http://" + host + ":" + port); - CloseableHttpClient delegate = mock(CloseableHttpClient.class); - final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - doThrow(new IOException("boom")).doThrow(new IOException("boom again")).doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); - ILoadBalancer lb = mock(ILoadBalancer.class); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, - serviceName, host, port, delegate, lb, "", loadBalancedBackOffPolicyFactory); - RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); - doReturn(method).when(request).getMethod(); - doReturn(uri).when(request).getURI(); - doReturn(request).when(request).withNewUri(any(URI.class)); - HttpUriRequest uriRequest = mock(HttpUriRequest.class); - doReturn(uri).when(uriRequest).getURI(); - doReturn(uriRequest).when(request).toRequest(any(RequestConfig.class)); - try { - client.execute(request, null); - fail("Expected IOException"); - } catch(IOException e) {} finally { - verify(response, times(0)).close(); - verify(delegate, times(1)).execute(any(HttpUriRequest.class)); - verify(lb, times(0)).chooseServer(eq(serviceName)); - } - } - - @Test - public void testRetryOnStatusCode() throws Exception { - int retriesNextServer = 0; - int retriesSameServer = 1; - boolean retryable = true; - boolean retryOnAllOps = false; - String serviceName = "foo"; - String host = serviceName; - int port = 80; - HttpMethod method = HttpMethod.GET; - URI uri = new URI("http://" + host + ":" + port); - CloseableHttpClient delegate = mock(CloseableHttpClient.class); - final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); - doReturn(200).when(statusLine).getStatusCode(); - doReturn(statusLine).when(response).getStatusLine(); - final CloseableHttpResponse fourOFourResponse = mock(CloseableHttpResponse.class); - StatusLine fourOFourStatusLine = mock(StatusLine.class); - doReturn(404).when(fourOFourStatusLine).getStatusCode(); - doReturn(fourOFourStatusLine).when(fourOFourResponse).getStatusLine(); - doReturn(fourOFourResponse).doReturn(response).when(delegate).execute(any(HttpUriRequest.class)); - ILoadBalancer lb = mock(ILoadBalancer.class); - MyBackOffPolicyFactory myBackOffPolicyFactory = new MyBackOffPolicyFactory(); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, - serviceName, host, port, delegate, lb, "404", myBackOffPolicyFactory); - RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); - doReturn(uri).when(request).getURI(); - doReturn(method).when(request).getMethod(); - doReturn(request).when(request).withNewUri(any(URI.class)); - HttpUriRequest uriRequest = mock(HttpUriRequest.class); - doReturn(uri).when(uriRequest).getURI(); - doReturn(uriRequest).when(request).toRequest(any(RequestConfig.class)); - RibbonApacheHttpResponse returnedResponse = client.execute(request, null); - verify(fourOFourResponse, times(1)).close(); - verify(delegate, times(2)).execute(any(HttpUriRequest.class)); - verify(lb, times(0)).chooseServer(eq(serviceName)); - assertEquals(1, myBackOffPolicyFactory.getCount()); - } - - @Test - public void retryListenerTest() throws Exception { - int retriesNextServer = 1; - int retriesSameServer = 1; - boolean retryable = true; - boolean retryOnAllOps = true; - String serviceName = "listener"; - String host = serviceName; - int port = 80; - HttpMethod method = HttpMethod.POST; - URI uri = new URI("http://" + host + ":" + port); - CloseableHttpClient delegate = mock(CloseableHttpClient.class); - final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); - doReturn(200).when(statusLine).getStatusCode(); - doReturn(statusLine).when(response).getStatusLine(); - doThrow(new IOException("boom")).doThrow(new IOException("boom again")).doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); - ILoadBalancer lb = mock(ILoadBalancer.class); - MyBackOffPolicyFactory myBackOffPolicyFactory = new MyBackOffPolicyFactory(); - MyRetryListeners myRetryListeners = new MyRetryListeners(); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, - serviceName, host, port, delegate, lb, "", myBackOffPolicyFactory, false, myRetryListeners); - RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); - doReturn(method).when(request).getMethod(); - doReturn(uri).when(request).getURI(); - doReturn(request).when(request).withNewUri(any(URI.class)); - HttpUriRequest uriRequest = mock(HttpUriRequest.class); - doReturn(uriRequest).when(request).toRequest(any(RequestConfig.class)); - RibbonApacheHttpResponse returnedResponse = client.execute(request, null); - verify(response, times(0)).close(); - verify(delegate, times(3)).execute(any(HttpUriRequest.class)); - verify(lb, times(1)).chooseServer(eq(serviceName)); - assertEquals(2, myBackOffPolicyFactory.getCount()); - assertEquals(2, myRetryListeners.getOnError()); - } - - @Test - public void retryDefaultListenerTest() throws Exception { - int retriesNextServer = 1; - int retriesSameServer = 1; - boolean retryable = true; - boolean retryOnAllOps = true; - String serviceName = "listener"; - String host = serviceName; - int port = 80; - HttpMethod method = HttpMethod.POST; - URI uri = new URI("http://" + host + ":" + port); - CloseableHttpClient delegate = mock(CloseableHttpClient.class); - final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); - doReturn(200).when(statusLine).getStatusCode(); - doReturn(statusLine).when(response).getStatusLine(); - doThrow(new IOException("boom")).doThrow(new IOException("boom again")).doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); - ILoadBalancer lb = mock(ILoadBalancer.class); - MyBackOffPolicyFactory myBackOffPolicyFactory = new MyBackOffPolicyFactory(); - MyRetryListeners myRetryListeners = new MyRetryListeners(); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, - serviceName, host, port, delegate, lb, "", myBackOffPolicyFactory, false, loadBalancedRetryListenerFactory); - RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); - doReturn(method).when(request).getMethod(); - doReturn(uri).when(request).getURI(); - doReturn(request).when(request).withNewUri(any(URI.class)); - HttpUriRequest uriRequest = mock(HttpUriRequest.class); - doReturn(uriRequest).when(request).toRequest(any(RequestConfig.class)); - RibbonApacheHttpResponse returnedResponse = client.execute(request, null); - verify(response, times(0)).close(); - verify(delegate, times(3)).execute(any(HttpUriRequest.class)); - verify(lb, times(1)).chooseServer(eq(serviceName)); - assertEquals(2, myBackOffPolicyFactory.getCount()); - assertEquals(0, myRetryListeners.getOnError()); - } - - @Test(expected = TerminatedRetryException.class) - public void retryListenerTestNoRetry() throws Exception { - int retriesNextServer = 1; - int retriesSameServer = 1; - boolean retryable = true; - boolean retryOnAllOps = true; - String serviceName = "listener"; - String host = serviceName; - int port = 80; - HttpMethod method = HttpMethod.POST; - URI uri = new URI("http://" + host + ":" + port); - CloseableHttpClient delegate = mock(CloseableHttpClient.class); - final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); - doReturn(200).when(statusLine).getStatusCode(); - doReturn(statusLine).when(response).getStatusLine(); - doThrow(new IOException("boom")).doThrow(new IOException("boom again")).doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); - ILoadBalancer lb = mock(ILoadBalancer.class); - MyBackOffPolicyFactory myBackOffPolicyFactory = new MyBackOffPolicyFactory(); - MyRetryListenersNotRetry myRetryListenersNotRetry = new MyRetryListenersNotRetry(); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, - serviceName, host, port, delegate, lb, "", myBackOffPolicyFactory, false, myRetryListenersNotRetry); - RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); - doReturn(method).when(request).getMethod(); - doReturn(uri).when(request).getURI(); - doReturn(request).when(request).withNewUri(any(URI.class)); - HttpUriRequest uriRequest = mock(HttpUriRequest.class); - doReturn(uriRequest).when(request).toRequest(any(RequestConfig.class)); - RibbonApacheHttpResponse returnedResponse = client.execute(request, null); - - } - - @Test - public void retryWithOriginalConstructorTest() throws Exception { - int retriesNextServer = 1; - int retriesSameServer = 1; - boolean retryable = true; - boolean retryOnAllOps = true; - String serviceName = "listener"; - String host = serviceName; - int port = 80; - HttpMethod method = HttpMethod.POST; - URI uri = new URI("http://" + host + ":" + port); - CloseableHttpClient delegate = mock(CloseableHttpClient.class); - final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); - doReturn(200).when(statusLine).getStatusCode(); - doReturn(statusLine).when(response).getStatusLine(); - doThrow(new IOException("boom")).doThrow(new IOException("boom again")).doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); - ILoadBalancer lb = mock(ILoadBalancer.class); - MyBackOffPolicyFactory myBackOffPolicyFactory = new MyBackOffPolicyFactory(); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, - serviceName, host, port, delegate, lb, "", myBackOffPolicyFactory, false); - RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); - doReturn(method).when(request).getMethod(); - doReturn(uri).when(request).getURI(); - doReturn(request).when(request).withNewUri(any(URI.class)); - HttpUriRequest uriRequest = mock(HttpUriRequest.class); - doReturn(uriRequest).when(request).toRequest(any(RequestConfig.class)); - RibbonApacheHttpResponse returnedResponse = client.execute(request, null); - verify(response, times(0)).close(); - verify(delegate, times(3)).execute(any(HttpUriRequest.class)); - verify(lb, times(1)).chooseServer(eq(serviceName)); - assertEquals(2, myBackOffPolicyFactory.getCount()); - } - - @Configuration - protected static class UseDefaults { - - } - - @Configuration - protected static class FollowRedirects { - @Bean - public IClientConfig clientConfig() { - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.set(CommonClientConfigKey.FollowRedirects, true); - return config; - } - } - - @Configuration - protected static class DoNotFollowRedirects { - @Bean - public IClientConfig clientConfig() { - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.set(CommonClientConfigKey.FollowRedirects, false); - return config; - } - } - - @Configuration - protected static class Timeouts { - @Bean - public IClientConfig clientConfig() { - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.set(CommonClientConfigKey.ConnectTimeout, 60000); - config.set(CommonClientConfigKey.ReadTimeout, 50000); - return config; - } - } - - - @Configuration - protected static class Connections { - @Bean - public IClientConfig clientConfig() { - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.set(CommonClientConfigKey.MaxTotalConnections, 101); - config.set(CommonClientConfigKey.MaxConnectionsPerHost, 201); - return config; - } - } - - private RequestConfig getBuiltRequestConfig(Class defaultConfigurationClass, - IClientConfig configOverride) throws Exception { - return getBuiltRequestConfig(defaultConfigurationClass, configOverride, new SpringClientFactory()); - } - - private RequestConfig getBuiltRequestConfig(Class defaultConfigurationClass, - IClientConfig configOverride, SpringClientFactory factory) - throws Exception { - - factory.setApplicationContext(new AnnotationConfigApplicationContext(HttpClientConfiguration.class, - RibbonAutoConfiguration.class, defaultConfigurationClass)); - String serviceName = "foo"; - String host = serviceName; - int port = 80; - URI uri = new URI("http://" + host + ":" + port); - CloseableHttpClient delegate = mock(CloseableHttpClient.class); - RibbonLoadBalancingHttpClient client = factory.getClient("service", - RibbonLoadBalancingHttpClient.class); - - ReflectionTestUtils.setField(client, "delegate", delegate); - ReflectionTestUtils.setField(client, "lb", loadBalancer); - CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); - doReturn(200).when(statusLine).getStatusCode(); - doReturn(statusLine).when(httpResponse).getStatusLine(); - given(delegate.execute(any(HttpUriRequest.class))).willReturn( - httpResponse); - RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); - doReturn(uri).when(request).getURI(); - doReturn(request).when(request).withNewUri(any(URI.class)); - given(request.toRequest(any(RequestConfig.class))).willReturn( - mock(HttpUriRequest.class)); - - client.execute(request, configOverride); - - ArgumentCaptor requestConfigCaptor = ArgumentCaptor - .forClass(RequestConfig.class); - verify(request, times(1)).toRequest(requestConfigCaptor.capture()); - return requestConfigCaptor.getValue(); - } - - class MyBackOffPolicyFactory implements LoadBalancedBackOffPolicyFactory, BackOffPolicy { - - private int count = 0; - - @Override - public BackOffContext start(RetryContext retryContext) { - return null; - } - - @Override - public void backOff(BackOffContext backOffContext) throws BackOffInterruptedException { - count++; - } - - public int getCount() { - return count; - } - - @Override - public BackOffPolicy createBackOffPolicy(String service) { - return this; - } - } - - class MyRetryListeners implements LoadBalancedRetryListenerFactory { - - private int onError = 0; - - @Override - public RetryListener[] createRetryListeners(String service) { - return new RetryListener[] {new RetryListener() { - @Override - public boolean open(RetryContext context, RetryCallback callback) { - return true; - } - - @Override - public void close(RetryContext context, RetryCallback callback, Throwable throwable) { - - } - - @Override - public void onError(RetryContext context, RetryCallback callback, Throwable throwable) { - onError++; - } - }}; - } - - public int getOnError() { - return onError; - } - } - - class MyRetryListenersNotRetry implements LoadBalancedRetryListenerFactory { - - @Override - public RetryListener[] createRetryListeners(String service) { - return new RetryListener[] {new RetryListener() { - @Override - public boolean open(RetryContext context, RetryCallback callback) { - return false; - } - - @Override - public void close(RetryContext context, RetryCallback callback, Throwable throwable) { - - } - - @Override - public void onError(RetryContext context, RetryCallback callback, Throwable throwable) { - - } - }}; - } - } - -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClientTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClientTests.java deleted file mode 100644 index 755e997b..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClientTests.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.okhttp; - -import okhttp3.OkHttpClient; - -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector; -import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -/** - * @author Spencer Gibb - */ -public class OkHttpLoadBalancingClientTests { - - @Test - public void testOkHttpClientUseDefaultsNoOverride() throws Exception { - OkHttpClient result = getHttpClient(UseDefaults.class, null); - - assertThat(result.followRedirects(), is(false)); - } - - @Test - public void testOkHttpClientDoNotFollowRedirectsNoOverride() throws Exception { - OkHttpClient result = getHttpClient(DoNotFollowRedirects.class, null); - - assertThat(result.followRedirects(), is(false)); - } - - @Test - public void testOkHttpClientFollowRedirectsNoOverride() throws Exception { - OkHttpClient result = getHttpClient(FollowRedirects.class, null); - - assertThat(result.followRedirects(), is(true)); - } - - @Test - public void testOkHttpClientDoNotFollowRedirectsOverrideWithFollowRedirects() - throws Exception { - - DefaultClientConfigImpl override = new DefaultClientConfigImpl(); - override.set(CommonClientConfigKey.FollowRedirects, true); - override.set(CommonClientConfigKey.IsSecure, false); - - OkHttpClient result = getHttpClient(DoNotFollowRedirects.class, override); - - assertThat(result.followRedirects(), is(true)); - } - - @Test - public void testOkHttpClientFollowRedirectsOverrideWithDoNotFollowRedirects() - throws Exception { - - DefaultClientConfigImpl override = new DefaultClientConfigImpl(); - override.set(CommonClientConfigKey.FollowRedirects, false); - override.set(CommonClientConfigKey.IsSecure, false); - - OkHttpClient result = getHttpClient(FollowRedirects.class, override); - - assertThat(result.followRedirects(), is(false)); - } - - @Test - public void testTimeouts() throws Exception { - OkHttpClient result = getHttpClient(Timeouts.class, null); - assertThat(result.readTimeoutMillis(), is(50000)); - assertThat(result.connectTimeoutMillis(), is(60000)); - } - - @Test - public void testDefaultTimeouts() throws Exception { - OkHttpClient result = getHttpClient(UseDefaults.class, null); - assertThat(result.readTimeoutMillis(), is(1000)); - assertThat(result.connectTimeoutMillis(), is(1000)); - } - - @Test - public void testTimeoutsOverride() throws Exception { - DefaultClientConfigImpl override = new DefaultClientConfigImpl(); - override.set(CommonClientConfigKey.ConnectTimeout, 60); - override.set(CommonClientConfigKey.ReadTimeout, 50); - OkHttpClient result = getHttpClient(Timeouts.class, override); - assertThat(result.readTimeoutMillis(), is(50)); - assertThat(result.connectTimeoutMillis(), is(60)); - } - - @Test - public void testUpdatedTimeouts() throws Exception { - SpringClientFactory factory = new SpringClientFactory(); - OkHttpClient result = getHttpClient(Timeouts.class, null, factory); - assertThat(result.readTimeoutMillis(), is(50000)); - assertThat(result.connectTimeoutMillis(), is(60000)); - IClientConfig config = factory.getClientConfig("service"); - config.set(CommonClientConfigKey.ConnectTimeout, 60); - config.set(CommonClientConfigKey.ReadTimeout, 50); - result = getHttpClient(Timeouts.class, null, factory); - assertThat(result.readTimeoutMillis(), is(50)); - assertThat(result.connectTimeoutMillis(), is(60)); - } - - private OkHttpClient getHttpClient(Class defaultConfigurationClass, - IClientConfig configOverride) throws Exception { - return getHttpClient(defaultConfigurationClass, configOverride, new SpringClientFactory()); - } - - private OkHttpClient getHttpClient(Class defaultConfigurationClass, - IClientConfig configOverride, - SpringClientFactory factory) throws Exception { - factory.setApplicationContext(new AnnotationConfigApplicationContext( - RibbonAutoConfiguration.class, OkHttpClientConfiguration.class, defaultConfigurationClass)); - - OkHttpLoadBalancingClient client = factory.getClient("service", - OkHttpLoadBalancingClient.class); - - return client.getOkHttpClient(configOverride, false); - } - - @Configuration - protected static class OkHttpClientConfiguration { - @Autowired(required = false) - IClientConfig clientConfig; - @Bean - public OkHttpLoadBalancingClient okHttpLoadBalancingClient() { - if(clientConfig == null) { - clientConfig = new DefaultClientConfigImpl(); - } - return new OkHttpLoadBalancingClient(new OkHttpClient(), clientConfig, new DefaultServerIntrospector()); - } - } - - @Configuration - protected static class UseDefaults { - - } - - @Configuration - protected static class FollowRedirects { - @Bean - public IClientConfig clientConfig() { - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.set(CommonClientConfigKey.FollowRedirects, true); - return config; - } - } - - @Configuration - protected static class DoNotFollowRedirects { - @Bean - public IClientConfig clientConfig() { - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.set(CommonClientConfigKey.FollowRedirects, false); - return config; - } - } - - @Configuration - protected static class Timeouts { - @Bean - public IClientConfig clientConfig() { - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.set(CommonClientConfigKey.ConnectTimeout, 60000); - config.set(CommonClientConfigKey.ReadTimeout, 50000); - return config; - } - } - -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequestTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequestTests.java deleted file mode 100644 index 09a48c62..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequestTests.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon.okhttp; - -import okhttp3.Request; -import okhttp3.RequestBody; -import okio.Buffer; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import org.junit.Test; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer; -import org.springframework.util.LinkedMultiValueMap; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; - -/** - * @author Spencer Gibb - */ -public class OkHttpRibbonRequestTests { - - @Test - public void testNullEntity() throws Exception { - String uri = "http://example.com"; - LinkedMultiValueMap headers = new LinkedMultiValueMap<>(); - headers.add("my-header", "my-value"); - // headers.add(HttpEncoding.CONTENT_LENGTH, "5192"); - LinkedMultiValueMap params = new LinkedMultiValueMap<>(); - params.add("myparam", "myparamval"); - RibbonCommandContext context = new RibbonCommandContext("example", "GET", uri, - false, headers, params, null, new ArrayList()); - OkHttpRibbonRequest httpRequest = new OkHttpRibbonRequest(context); - - Request request = httpRequest.toRequest(); - - assertThat("body is not null", request.body(), is(nullValue())); - assertThat("uri is wrong", request.url().toString(), startsWith(uri)); - assertThat("my-header is wrong", request.header("my-header"), - is(equalTo("my-value"))); - assertThat("myparam is missing", request.url().queryParameter("myparam"), - is(equalTo("myparamval"))); - } - - @Test - // this situation happens, see - // https://github.com/spring-cloud/spring-cloud-netflix/issues/1042#issuecomment-227723877 - public void testEmptyEntityGet() throws Exception { - String entityValue = ""; - testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), false, - "GET"); - } - - @Test - public void testNonEmptyEntityPost() throws Exception { - String entityValue = "abcd"; - testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), true, - "POST"); - } - - void testEntity(String entityValue, ByteArrayInputStream requestEntity, - boolean addContentLengthHeader, String method) throws IOException { - String lengthString = String.valueOf(entityValue.length()); - Long length = null; - String uri = "http://example.com"; - LinkedMultiValueMap headers = new LinkedMultiValueMap<>(); - if (addContentLengthHeader) { - headers.add("Content-Length", lengthString); - length = (long) entityValue.length(); - } - - RibbonRequestCustomizer requestCustomizer = new RibbonRequestCustomizer() { - @Override - public boolean accepts(Class builderClass) { - return builderClass == Request.Builder.class; - } - - @Override - public void customize(Request.Builder builder) { - builder.addHeader("from-customizer", "foo"); - } - }; - RibbonCommandContext context = new RibbonCommandContext("example", method, uri, - false, headers, new LinkedMultiValueMap(), requestEntity, - Collections.singletonList(requestCustomizer)); - context.setContentLength(length); - OkHttpRibbonRequest httpRequest = new OkHttpRibbonRequest(context); - - Request request = httpRequest.toRequest(); - - assertThat("uri is wrong", request.url().toString(), startsWith(uri)); - if (addContentLengthHeader) { - assertThat("Content-Length is wrong", request.header("Content-Length"), - is(equalTo(lengthString))); - } - assertThat("from-customizer is wrong", request.header("from-customizer"), - is(equalTo("foo"))); - - if (!method.equalsIgnoreCase("get")) { - assertThat("body is null", request.body(), is(notNullValue())); - RequestBody body = request.body(); - assertThat("contentLength is wrong", body.contentLength(), - is(equalTo((long) entityValue.length()))); - Buffer content = new Buffer(); - body.writeTo(content); - String string = content.readByteString().utf8(); - assertThat("content is wrong", string, is(equalTo(entityValue))); - } - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponseTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponseTests.java deleted file mode 100644 index 8a65c9fa..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponseTests.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.okhttp; - -import okhttp3.HttpUrl; -import okhttp3.MediaType; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; - -import java.net.URI; -import org.junit.Test; -import org.springframework.http.HttpStatus; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; - -/** - * @author Spencer Gibb - */ -public class OkHttpRibbonResponseTests { - - @Test - public void testNullEntity() throws Exception { - URI uri = URI.create("http://example.com"); - Response response = response(uri).build(); - - OkHttpRibbonResponse httpResponse = new OkHttpRibbonResponse(response, uri); - - assertThat(httpResponse.isSuccess(), is(true)); - assertThat(httpResponse.hasPayload(), is(false)); - assertThat(httpResponse.getPayload(), is(nullValue())); - assertThat(httpResponse.getInputStream(), is(nullValue())); - } - - @Test - public void testNotNullEntity() throws Exception { - URI uri = URI.create("http://example.com"); - Response response = response(uri) - .body(ResponseBody.create(MediaType.parse("text/plain"), "abcd")) - .build(); - - OkHttpRibbonResponse httpResponse = new OkHttpRibbonResponse(response, uri); - - assertThat(httpResponse.isSuccess(), is(true)); - assertThat(httpResponse.hasPayload(), is(true)); - assertThat(httpResponse.getPayload(), is(notNullValue())); - assertThat(httpResponse.getInputStream(), is(notNullValue())); - } - - Response.Builder response(URI uri) { - return new Response.Builder() - .request(new Request.Builder().url(HttpUrl.get(uri)).build()) - .protocol(Protocol.HTTP_1_1) - .code(HttpStatus.OK.value()) - .message(HttpStatus.OK.getReasonPhrase()); - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/SpringRetryDisableOkHttpClientTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/SpringRetryDisableOkHttpClientTests.java deleted file mode 100644 index c78e740a..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/SpringRetryDisableOkHttpClientTests.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.springframework.cloud.netflix.ribbon.okhttp; - -import java.util.Map; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicyFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration; -import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; -import org.springframework.cloud.test.ClassPathExclusions; -import org.springframework.cloud.test.ModifiedClassPathRunner; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.instanceOf; - -/** - * @author Ryan Baxter - * @author Biju Kunjummen - */ -@RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions({"spring-retry-*.jar", "spring-boot-starter-aop-*.jar"}) -public class SpringRetryDisableOkHttpClientTests { - - @Test - public void testLoadBalancedRetryFactoryBean() { - new ApplicationContextRunner() - .withPropertyValues("ribbon.okhttp.enabled=true") - .withConfiguration(AutoConfigurations.of(RibbonAutoConfiguration.class, - LoadBalancerAutoConfiguration.class, - HttpClientConfiguration.class, RibbonClientConfiguration.class)) - .withUserConfiguration( - OkHttpLoadBalancingClientTests.OkHttpClientConfiguration.class) - .run(context -> { - Map factories = context.getBeansOfType(LoadBalancedRetryPolicyFactory.class); - assertThat(factories.values(), hasSize(1)); - assertThat(factories.values().toArray()[0], instanceOf(LoadBalancedRetryPolicyFactory.NeverRetryFactory.class)); - Map clients = context.getBeansOfType(OkHttpLoadBalancingClient.class); - assertThat(clients.values(), hasSize(1)); - assertThat(clients.values().toArray()[0], instanceOf(OkHttpLoadBalancingClient.class)); - }); - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/SpringRetryEnabledOkHttpClientTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/SpringRetryEnabledOkHttpClientTests.java deleted file mode 100644 index 2cf328d3..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/SpringRetryEnabledOkHttpClientTests.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.cloud.netflix.ribbon.okhttp; - -import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.BeansException; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicyFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration; -import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancedRetryPolicyFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.instanceOf; - -/** - * @author Ryan Baxter - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(value = { "ribbon.okhttp.enabled: true", "ribbon.httpclient.enabled: false" }) -@ContextConfiguration(classes = { RibbonAutoConfiguration.class, - HttpClientConfiguration.class, RibbonClientConfiguration.class, - LoadBalancerAutoConfiguration.class }) -public class SpringRetryEnabledOkHttpClientTests implements ApplicationContextAware { - - private ApplicationContext context; - - @Test - public void testLoadBalancedRetryFactoryBean() throws Exception { - Map factories = context - .getBeansOfType(LoadBalancedRetryPolicyFactory.class); - assertThat(factories.values(), hasSize(1)); - assertThat(factories.values().toArray()[0], - instanceOf(RibbonLoadBalancedRetryPolicyFactory.class)); - Map clients = context - .getBeansOfType(OkHttpLoadBalancingClient.class); - assertThat(clients.values(), hasSize(1)); - assertThat(clients.values().toArray()[0], - instanceOf(RetryableOkHttpLoadBalancingClient.class)); - } - - @Override - public void setApplicationContext(ApplicationContext context) throws BeansException { - this.context = context; - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/support/ContextAwareRequestTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/support/ContextAwareRequestTests.java deleted file mode 100644 index b8abf629..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/support/ContextAwareRequestTests.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon.support; - - -import java.net.URI; -import java.util.Arrays; -import java.util.Collections; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -/** - * @author Ryan Baxter - */ -public class ContextAwareRequestTests { - - private RibbonCommandContext context; - private ContextAwareRequest request; - - @Before - public void setUp() throws Exception { - context = mock(RibbonCommandContext.class); - doReturn("GET").when(context).getMethod(); - MultiValueMap headers = new LinkedMultiValueMap<>(); - headers.put("header1", Collections.emptyList()); - headers.put("header2", Arrays.asList("value1", "value2")); - headers.put("header3", Arrays.asList("value1")); - doReturn(headers).when(context).getHeaders(); - doReturn(new URI("http://foo")).when(context).uri(); - doReturn("foo").when(context).getServiceId(); - doReturn(new LinkedMultiValueMap<>()).when(context).getParams(); - doReturn("testLoadBalancerKey").when(context).getLoadBalancerKey(); - request = new TestContextAwareRequest(context); - } - - @After - public void tearDown() throws Exception { - context = null; - request = null; - } - - @Test - public void getContext() throws Exception { - assertEquals(context, request.getContext()); - } - - @Test - public void getMethod() throws Exception { - assertEquals(HttpMethod.GET, request.getMethod()); - } - - @Test - public void getURI() throws Exception { - assertEquals(new URI("http://foo"), request.getURI()); - - RibbonCommandContext badUriContext = mock(RibbonCommandContext.class); - doReturn(new LinkedMultiValueMap()).when(badUriContext).getHeaders(); - doReturn("foobar").when(badUriContext).getUri(); - ContextAwareRequest badUriRequest = new TestContextAwareRequest(badUriContext); - - assertNull(badUriRequest.getURI()); - - } - - @Test - public void getHeaders() throws Exception { - HttpHeaders headers = new HttpHeaders(); - headers.put("header1", Collections.emptyList()); - headers.put("header2", Arrays.asList("value1", "value2")); - headers.put("header3", Arrays.asList("value1")); - assertEquals(headers, request.getHeaders()); - } - - @Test - public void getLoadBalancerKey() throws Exception { - assertEquals("testLoadBalancerKey", request.getLoadBalancerKey()); - - RibbonCommandContext defaultContext = mock(RibbonCommandContext.class); - doReturn(new LinkedMultiValueMap()).when(defaultContext).getHeaders(); - doReturn(null).when(defaultContext).getLoadBalancerKey(); - ContextAwareRequest defaultRequest = new TestContextAwareRequest(defaultContext); - - assertNull(defaultRequest.getLoadBalancerKey()); - } - - static class TestContextAwareRequest extends ContextAwareRequest { - - public TestContextAwareRequest(RibbonCommandContext context) { - super(context); - } - } - -} \ No newline at end of file diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContextTest.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContextTest.java deleted file mode 100644 index 5e21c41d..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContextTest.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.support; - -import okhttp3.Request; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collections; -import org.junit.Test; -import org.springframework.http.HttpMethod; -import org.springframework.util.LinkedMultiValueMap; -import com.google.common.collect.Lists; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - - -/** - * @author Andre Dörnbrack - */ -public class RibbonCommandContextTest { - - private static final byte[] TEST_CONTENT = { 42, 42, 42, 42, 42 }; - - private RibbonCommandContext ribbonCommandContext; - - @Test - public void testMultipleReadsOnRequestEntity() throws Exception { - givenRibbonCommandContextIsSetup(); - - InputStream requestEntity = ribbonCommandContext.getRequestEntity(); - assertTrue(requestEntity instanceof ResettableServletInputStreamWrapper); - - whenInputStreamIsConsumed(requestEntity); - assertEquals(-1, requestEntity.read()); - - requestEntity.reset(); - assertNotEquals(-1, requestEntity.read()); - - whenInputStreamIsConsumed(requestEntity); - assertEquals(-1, requestEntity.read()); - - requestEntity.reset(); - assertNotEquals(-1, requestEntity.read()); - - whenInputStreamIsConsumed(requestEntity); - assertEquals(-1, requestEntity.read()); - } - - private void whenInputStreamIsConsumed(InputStream requestEntity) throws IOException { - while (requestEntity.read() != -1) { - requestEntity.read(); - } - } - - private void givenRibbonCommandContextIsSetup() { - LinkedMultiValueMap headers = new LinkedMultiValueMap(); - LinkedMultiValueMap params = new LinkedMultiValueMap(); - - RibbonRequestCustomizer requestCustomizer = new RibbonRequestCustomizer() { - @Override - public boolean accepts(Class builderClass) { - return builderClass == Request.Builder.class; - } - - @Override - public void customize(Request.Builder builder) { - builder.addHeader("from-customizer", "foo"); - } - }; - - ribbonCommandContext = new RibbonCommandContext("serviceId", - HttpMethod.POST.toString(), "/my/route", true, headers, params, - new ByteArrayInputStream(TEST_CONTENT), - Lists.newArrayList(requestCustomizer)); - } - - @Test - public void testNullSafetyWithNullableParameters() throws Exception { - LinkedMultiValueMap headers = new LinkedMultiValueMap(); - LinkedMultiValueMap params = new LinkedMultiValueMap(); - - RibbonCommandContext testContext = new RibbonCommandContext("serviceId", - HttpMethod.POST.toString(), "/my/route", true, headers, params, - new ByteArrayInputStream(TEST_CONTENT), Collections.emptyList(), - null, null); - - assertNotEquals(0, testContext.hashCode()); - assertNotNull(testContext.toString()); - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/RibbonClientDefaultConfigurationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/RibbonClientDefaultConfigurationTests.java deleted file mode 100644 index 8037ffed..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/RibbonClientDefaultConfigurationTests.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.test; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.ribbon.test.RibbonClientDefaultConfigurationTestsConfig.BazServiceList; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.loadbalancer.BestAvailableRule; -import com.netflix.loadbalancer.PingUrl; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerListSubsetFilter; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; - -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -/** - * @author Dave Syer - * @author Spencer Gibb - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = RibbonClientDefaultConfigurationTestsConfig.class, value = "ribbon.eureka.enabled=true") -@DirtiesContext -public class RibbonClientDefaultConfigurationTests { - - @Autowired - private SpringClientFactory factory; - - @Test - public void ruleOverridesDefault() throws Exception { - assertThat("wrong rule type", getLoadBalancer("baz").getRule(), - is(instanceOf(BestAvailableRule.class))); - } - - @Test - public void pingOverridesDefault() throws Exception { - assertThat("wrong ping type", getLoadBalancer("baz").getPing(), - is(instanceOf(PingUrl.class))); - } - - @Test - public void serverListOverridesDefault() throws Exception { - assertThat("wrong server list type", getLoadBalancer("baz").getServerListImpl(), - is(instanceOf(BazServiceList.class))); - } - - @SuppressWarnings("unchecked") - private ZoneAwareLoadBalancer getLoadBalancer(String name) { - return (ZoneAwareLoadBalancer) this.factory.getLoadBalancer(name); - } - - @Test - public void serverListFilterOverride() throws Exception { - assertThat("wrong filter type", getLoadBalancer("baz").getFilter(), - is(instanceOf(ServerListSubsetFilter.class))); - } - -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/RibbonClientDefaultConfigurationTestsConfig.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/RibbonClientDefaultConfigurationTestsConfig.java deleted file mode 100644 index fb1346ff..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/RibbonClientDefaultConfigurationTestsConfig.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.ribbon.test; - -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; -import org.springframework.cloud.commons.util.UtilAutoConfiguration; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.BestAvailableRule; -import com.netflix.loadbalancer.ConfigurationBasedServerList; -import com.netflix.loadbalancer.IPing; -import com.netflix.loadbalancer.IRule; -import com.netflix.loadbalancer.PingUrl; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.loadbalancer.ServerListSubsetFilter; - -/** - * @author Spencer Gibb - */ -@Configuration -@Import({ PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class, - UtilAutoConfiguration.class, RibbonAutoConfiguration.class, HttpClientConfiguration.class }) -// tag::sample_default_ribbon_config[] -@RibbonClients(defaultConfiguration = DefaultRibbonConfig.class) -public class RibbonClientDefaultConfigurationTestsConfig { - - public static class BazServiceList extends ConfigurationBasedServerList { - public BazServiceList(IClientConfig config) { - super.initWithNiwsConfig(config); - } - } -} - -@Configuration -class DefaultRibbonConfig { - - @Bean - public IRule ribbonRule() { - return new BestAvailableRule(); - } - - @Bean - public IPing ribbonPing() { - return new PingUrl(); - } - - @Bean - public ServerList ribbonServerList(IClientConfig config) { - return new RibbonClientDefaultConfigurationTestsConfig.BazServiceList(config); - } - - @Bean - public ServerListSubsetFilter serverListFilter() { - ServerListSubsetFilter filter = new ServerListSubsetFilter(); - return filter; - } - -} -// end::sample_default_ribbon_config[] \ No newline at end of file diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestAutoConfiguration.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestAutoConfiguration.java deleted file mode 100644 index add2f2d9..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestAutoConfiguration.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.test; - -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -import org.springframework.cloud.client.discovery.noop.NoopDiscoveryClientAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.core.Ordered; -import org.springframework.core.annotation.Order; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.provisioning.InMemoryUserDetailsManager; - -/** - * @author Spencer Gibb - */ -@Configuration -@Import({NoopDiscoveryClientAutoConfiguration.class}) -@AutoConfigureBefore(SecurityAutoConfiguration.class) -public class TestAutoConfiguration { - - public static final String USER = "user"; - public static final String PASSWORD = "{noop}password"; - - @Configuration - @Order(Ordered.HIGHEST_PRECEDENCE) - protected static class TestSecurityConfiguration extends WebSecurityConfigurerAdapter { - - - TestSecurityConfiguration() { - super(true); - } - - @Bean - public UserDetailsService userDetailsService() { - InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); - manager.createUser(User.withUsername(USER).password(PASSWORD).roles("USER").build()); - return manager; - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - // super.configure(http); - http.antMatcher("/proxy-username") - .httpBasic() - .and() - .authorizeRequests().antMatchers("/**").permitAll(); - } - - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestLoadBalancer.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestLoadBalancer.java deleted file mode 100644 index 0de2ce21..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestLoadBalancer.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.test; - -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; - -/** - * @author Spencer Gibb - */ -public class TestLoadBalancer extends ZoneAwareLoadBalancer { -} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestServerList.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestServerList.java deleted file mode 100644 index 70335a18..00000000 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestServerList.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.ribbon.test; - -import java.util.ArrayList; -import java.util.List; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; - -/** - * @author Spencer Gibb - */ -public class TestServerList implements ServerList { - - private final List servers; - - public TestServerList() { - this.servers = new ArrayList<>(); - } - - public void add(T server) { - this.servers.add(server); - } - - @Override - public List getInitialListOfServers() { - return servers; - } - - @Override - public List getUpdatedListOfServers() { - return servers; - } -} diff --git a/spring-cloud-netflix-ribbon/src/test/resources/META-INF/spring.factories b/spring-cloud-netflix-ribbon/src/test/resources/META-INF/spring.factories deleted file mode 100644 index 8e405ed6..00000000 --- a/spring-cloud-netflix-ribbon/src/test/resources/META-INF/spring.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -org.springframework.cloud.netflix.ribbon.test.TestAutoConfiguration diff --git a/spring-cloud-netflix-ribbon/src/test/resources/application.yml b/spring-cloud-netflix-ribbon/src/test/resources/application.yml deleted file mode 100644 index 30a3f68a..00000000 --- a/spring-cloud-netflix-ribbon/src/test/resources/application.yml +++ /dev/null @@ -1,8 +0,0 @@ -# for RibbonClientPreprocessorPropertiesOverridesIntegrationTests -foo2: - ribbon: - NFLoadBalancerPingClassName: com.netflix.loadbalancer.NoOpPing - NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule - NIWSServerListClassName: org.springframework.cloud.netflix.ribbon.test.TestServerList - NIWSServerListFilterClassName: com.netflix.loadbalancer.ServerListSubsetFilter - NFLoadBalancerClassName: org.springframework.cloud.netflix.ribbon.test.TestLoadBalancer diff --git a/spring-cloud-netflix-sidecar/pom.xml b/spring-cloud-netflix-sidecar/pom.xml deleted file mode 100644 index be80b9f1..00000000 --- a/spring-cloud-netflix-sidecar/pom.xml +++ /dev/null @@ -1,107 +0,0 @@ - - - 4.0.0 - - org.springframework.cloud - spring-cloud-netflix - 2.0.0.BUILD-SNAPSHOT - .. - - spring-cloud-netflix-sidecar - jar - Spring Cloud Netflix Sidecar - https://projects.spring.io/spring-cloud/ - - ${basedir}/.. - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework.cloud - spring-cloud-commons - - - org.springframework.cloud - spring-cloud-context - - - org.springframework.cloud - spring-cloud-netflix-zuul - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework - spring-web - - - org.springframework.cloud - spring-cloud-netflix-core - - - org.springframework.cloud - spring-cloud-netflix-eureka-client - - - com.netflix.eureka - eureka-client - - - com.netflix.hystrix - hystrix-core - - - com.netflix.hystrix - hystrix-metrics-event-stream - - - com.netflix.hystrix - hystrix-javanica - - - com.netflix.ribbon - ribbon - - - com.netflix.ribbon - ribbon-core - - - com.netflix.ribbon - ribbon-eureka - - - com.netflix.ribbon - ribbon-httpclient - - - com.netflix.zuul - zuul-core - - - org.apache.tomcat.embed - tomcat-embed-el - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.cloud - spring-cloud-config-client - test - - - diff --git a/spring-cloud-netflix-sidecar/run-server.sh b/spring-cloud-netflix-sidecar/run-server.sh deleted file mode 100755 index 8bacc042..00000000 --- a/spring-cloud-netflix-sidecar/run-server.sh +++ /dev/null @@ -1 +0,0 @@ -python -m SimpleHTTPServer diff --git a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/EnableSidecar.java b/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/EnableSidecar.java deleted file mode 100644 index b55b131a..00000000 --- a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/EnableSidecar.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.sidecar; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.context.annotation.Import; - -/** - * @author Spencer Gibb - */ -@EnableCircuitBreaker -@EnableZuulProxy -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Import(SidecarConfiguration.class) -public @interface EnableSidecar { - -} diff --git a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthCheckHandler.java b/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthCheckHandler.java deleted file mode 100644 index d6b53c2e..00000000 --- a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthCheckHandler.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.sidecar; - -import static com.netflix.appinfo.InstanceInfo.InstanceStatus.DOWN; -import static com.netflix.appinfo.InstanceInfo.InstanceStatus.OUT_OF_SERVICE; -import static com.netflix.appinfo.InstanceInfo.InstanceStatus.UNKNOWN; -import static com.netflix.appinfo.InstanceInfo.InstanceStatus.UP; - -import com.netflix.appinfo.HealthCheckHandler; -import com.netflix.appinfo.InstanceInfo.InstanceStatus; -import org.springframework.boot.actuate.health.HealthIndicator; -import org.springframework.boot.actuate.health.Status; - -/** - * Eureka HealthCheckHandler that translates boot health status to - * InstanceStatus so the proper status of the non-JVM app is sent to Eureka. -* @author Spencer Gibb -*/ -class LocalApplicationHealthCheckHandler implements HealthCheckHandler { - - private final HealthIndicator healthIndicator; - - public LocalApplicationHealthCheckHandler(HealthIndicator healthIndicator) { - this.healthIndicator = healthIndicator; - } - - @Override - public InstanceStatus getStatus(InstanceStatus currentStatus) { - Status status = healthIndicator.health().getStatus(); - if (status.equals(Status.UP)) { - return UP; - } else if (status.equals(Status.OUT_OF_SERVICE)) { - return OUT_OF_SERVICE; - } else if (status.equals(Status.DOWN)) { - return DOWN; - } - return UNKNOWN; - } -} diff --git a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthIndicator.java b/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthIndicator.java deleted file mode 100644 index 19e1d1f1..00000000 --- a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthIndicator.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.sidecar; - -import java.net.URI; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.health.AbstractHealthIndicator; -import org.springframework.boot.actuate.health.Health; -import org.springframework.web.client.RestTemplate; - -/** - * @author Spencer Gibb - */ -public class LocalApplicationHealthIndicator extends AbstractHealthIndicator { - - @Autowired - private SidecarProperties properties; - - @SuppressWarnings("unchecked") - @Override - protected void doHealthCheck(Health.Builder builder) throws Exception { - URI uri = this.properties.getHealthUri(); - if (uri == null) { - builder.up(); - return; - } - Map map = new RestTemplate().getForObject(uri, Map.class); - Object status = map.get("status"); - if (status != null && status instanceof String) { - builder.status(status.toString()); - } - else if (status != null && status instanceof Map) { - Map statusMap = (Map) status; - Object code = statusMap.get("code"); - if (code != null) { - builder.status(code.toString()); - } - else { - getWarning(builder); - } - } - else { - getWarning(builder); - } - } - - private Health.Builder getWarning(Health.Builder builder) { - return builder.unknown().withDetail("warning", "no status field in response"); - } - -} diff --git a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarConfiguration.java b/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarConfiguration.java deleted file mode 100644 index 4efd3b4a..00000000 --- a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarConfiguration.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.sidecar; - -import static org.springframework.cloud.commons.util.IdUtils.getDefaultInstanceId; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.client.actuator.HasFeatures; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.util.StringUtils; - -import com.netflix.appinfo.HealthCheckHandler; -import com.netflix.discovery.EurekaClientConfig; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -/** - * Sidecar Configuration that setting up {@link com.netflix.appinfo.EurekaInstanceConfig}. - *

- * Depends on {@link SidecarProperties} and {@code eureka.instance.hostname} property. Since there is two way to - * configure hostname: - *

    - *
  1. {@code eureka.instance.hostname} property
  2. - *
  3. {@link SidecarProperties#hostname}
  4. - *
- * {@code eureka.instance.hostname} will always win against {@link SidecarProperties#hostname} due to - * {@code @ConfigurationProperties("eureka.instance")} on {@link EurekaInstanceConfigBeanConfiguration}. - * - * @author Spencer Gibb - * @author Ryan Baxter - * - * @see EurekaInstanceConfigBeanConfiguration - */ -@Configuration -@EnableConfigurationProperties -@ConditionalOnProperty(value = "spring.cloud.netflix.sidecar.enabled", matchIfMissing = true) -public class SidecarConfiguration { - - @Bean - public HasFeatures Feature() { - return HasFeatures.namedFeature("Netflix Sidecar", SidecarConfiguration.class); - } - - @Bean - public SidecarProperties sidecarProperties() { - return new SidecarProperties(); - } - - @Configuration - @ConditionalOnClass(EurekaClientConfig.class) - protected static class EurekaInstanceConfigBeanConfiguration { - @Autowired - private SidecarProperties sidecarProperties; - - @Autowired - private InetUtils inetUtils; - - @Value("${management.port:${MANAGEMENT_PORT:${server.port:${SERVER_PORT:${PORT:8080}}}}}") - private int managementPort = 8080; - - @Value("${eureka.instance.hostname:${EUREKA_INSTANCE_HOSTNAME:}}") - private String hostname; - - @Autowired - private ConfigurableEnvironment env; - - @Bean - public EurekaInstanceConfigBean eurekaInstanceConfigBean() { - EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(inetUtils); - String springAppName = this.env.getProperty("spring.application.name", ""); - int port = this.sidecarProperties.getPort(); - config.setNonSecurePort(port); - config.setInstanceId(getDefaultInstanceId(this.env)); - if (StringUtils.hasText(springAppName)) { - config.setAppname(springAppName); - config.setVirtualHostName(springAppName); - config.setSecureVirtualHostName(springAppName); - } - String hostname = this.sidecarProperties.getHostname(); - String ipAddress = this.sidecarProperties.getIpAddress(); - if (!StringUtils.hasText(hostname) && StringUtils.hasText(this.hostname)) { - hostname = this.hostname; - } - if (StringUtils.hasText(hostname)) { - config.setHostname(hostname); - } - if (StringUtils.hasText(ipAddress)) { - config.setIpAddress(ipAddress); - } - String scheme = config.getSecurePortEnabled() ? "https" : "http"; - config.setStatusPageUrl(scheme + "://" + config.getHostname() + ":" - + this.managementPort + config.getStatusPageUrlPath()); - config.setHealthCheckUrl(scheme + "://" + config.getHostname() + ":" - + this.managementPort + config.getHealthCheckUrlPath()); - config.setHomePageUrl(scheme + "://" + config.getHostname() + ":" + port - + config.getHomePageUrlPath()); - return config; - } - - @Bean - public HealthCheckHandler healthCheckHandler( - final LocalApplicationHealthIndicator healthIndicator) { - return new LocalApplicationHealthCheckHandler(healthIndicator); - } - - } - - @Bean - public LocalApplicationHealthIndicator localApplicationHealthIndicator() { - return new LocalApplicationHealthIndicator(); - } - - @Bean - public SidecarController sidecarController() { - return new SidecarController(); - } - -} diff --git a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarController.java b/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarController.java deleted file mode 100644 index b526d039..00000000 --- a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarController.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.sidecar; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -/** - * @author Spencer Gibb - */ -@RestController -public class SidecarController { - - @Autowired - private DiscoveryClient discovery; - - @Value("${spring.application.name}") - private String appName; - - @RequestMapping("/ping") - public String ping() { - return "OK"; - } - - @RequestMapping("/hosts/{appName}") - public List hosts(@PathVariable("appName") String appName) { - return hosts2(appName); - } - - @RequestMapping("/hosts") - public List hosts2(@RequestParam("appName") String appName) { - List instances = this.discovery.getInstances(appName); - return instances; - } - - @RequestMapping(value = "/", produces = "text/html") - public String home() { - return "Sidecar\n" - + "ping
\n" - + "health
\n" + "hosts/" + this.appName + "
\n" + ""; - } - -} diff --git a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarProperties.java b/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarProperties.java deleted file mode 100644 index 4f8aa8e5..00000000 --- a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarProperties.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.sidecar; - -import java.net.URI; -import java.util.Objects; - -import javax.validation.constraints.Max; -import javax.validation.constraints.Min; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * @author Spencer Gibb - * @author Gregor Zurowski - */ -@ConfigurationProperties("sidecar") -public class SidecarProperties { - - private URI healthUri; - - private URI homePageUri; - - @Max(65535) - @Min(1) - private int port; - - private String hostname; - - private String ipAddress; - - public URI getHealthUri() { - return healthUri; - } - - public void setHealthUri(URI healthUri) { - this.healthUri = healthUri; - } - - public URI getHomePageUri() { - return homePageUri; - } - - public void setHomePageUri(URI homePageUri) { - this.homePageUri = homePageUri; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getHostname() { - return hostname; - } - - public void setHostname(String hostname) { - this.hostname = hostname; - } - - public String getIpAddress() { - return ipAddress; - } - - public void setIpAddress(String ipAddress) { - this.ipAddress = ipAddress; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - SidecarProperties that = (SidecarProperties) o; - return Objects.equals(healthUri, that.healthUri) && - Objects.equals(homePageUri, that.homePageUri) && - port == that.port && - Objects.equals(hostname, that.hostname) && - Objects.equals(ipAddress, that.ipAddress); - } - - @Override - public int hashCode() { - return Objects.hash(healthUri, homePageUri, port, hostname, ipAddress); - } - - @Override - public String toString() { - return new StringBuilder("SidecarProperties{") - .append("healthUri=").append(healthUri).append(", ") - .append("homePageUri=").append(homePageUri).append(", ") - .append("port=").append(port).append(", ") - .append("hostname='").append(hostname).append("', ") - .append("ipAddress='").append(ipAddress).append("'}") - .toString(); - } - -} diff --git a/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthCheckHandlerTests.java b/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthCheckHandlerTests.java deleted file mode 100644 index caf4b376..00000000 --- a/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthCheckHandlerTests.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.sidecar; - -import static org.junit.Assert.assertEquals; -import static org.mockito.MockitoAnnotations.initMocks; -import static org.mockito.BDDMockito.*; - -import com.netflix.appinfo.InstanceInfo.InstanceStatus; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.springframework.boot.actuate.health.Health; -import org.springframework.boot.actuate.health.HealthIndicator; - -/** - * @author Spencer Gibb - */ -public class LocalApplicationHealthCheckHandlerTests { - - @Mock - private HealthIndicator healthIndicator; - - @Before - public void setup() { - initMocks(this); - } - - @Test - public void upMappingWorks() { - assertStatus(InstanceStatus.UP, Health.up()); - } - - @Test - public void downMappingWorks() { - assertStatus(InstanceStatus.DOWN, Health.down()); - } - - @Test - public void outOfServiceMappingWorks() { - assertStatus(InstanceStatus.OUT_OF_SERVICE, Health.outOfService()); - } - - @Test - public void unknownMappingWorks() { - assertStatus(InstanceStatus.UNKNOWN, Health.unknown()); - } - - private void assertStatus(InstanceStatus expected, Health.Builder builder) { - given(healthIndicator.health()).willReturn(builder.build()); - - LocalApplicationHealthCheckHandler handler = new LocalApplicationHealthCheckHandler(healthIndicator); - InstanceStatus status = handler.getStatus(InstanceStatus.UP); - assertEquals(expected, status); - } -} diff --git a/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/SidecarApplication.java b/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/SidecarApplication.java deleted file mode 100644 index 63fe5129..00000000 --- a/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/SidecarApplication.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.sidecar; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.web.bind.annotation.RestController; - -@SpringBootApplication -@EnableSidecar -@RestController -public class SidecarApplication { - - public static void main(String[] args) { - SpringApplication.run(SidecarApplication.class, args); - } - -} diff --git a/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/SidecarApplicationTests.java b/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/SidecarApplicationTests.java deleted file mode 100644 index 6e24dbb6..00000000 --- a/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/SidecarApplicationTests.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.sidecar; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -public class SidecarApplicationTests { - - @RunWith(SpringRunner.class) - @SpringBootTest(classes = SidecarApplication.class, webEnvironment = RANDOM_PORT, properties = { - "spring.application.name=mytest", "spring.cloud.client.hostname=mhhost", "spring.application.instance_id=1", - "eureka.instance.hostname=mhhost", "sidecar.port=7000", "sidecar.ip-address=127.0.0.1" }) - public static class EurekaTestConfigBeanTest { - @Autowired - EurekaInstanceConfigBean config; - - @Test - public void testEurekaConfigBean() { - assertThat(this.config.getAppname(), equalTo("mytest")); - assertThat(this.config.getHostname(), equalTo("mhhost")); - assertThat(this.config.getInstanceId(), equalTo("mhhost:mytest:1")); - assertThat(this.config.getNonSecurePort(), equalTo(7000)); - } - } - - @RunWith(SpringRunner.class) - @SpringBootTest(classes = SidecarApplication.class, webEnvironment = RANDOM_PORT, properties = { - "spring.application.name=mytest", "spring.cloud.client.hostname=mhhost", "spring.application.instance_id=1", - "sidecar.hostname=mhhost", "sidecar.port=7000", "sidecar.ip-address=127.0.0.1" }) - public static class NewPropertyEurekaTestConfigBeanTest { - @Autowired - EurekaInstanceConfigBean config; - - @Test - public void testEurekaConfigBean() { - assertThat(this.config.getAppname(), equalTo("mytest")); - assertThat(this.config.getHostname(), equalTo("mhhost")); - assertThat(this.config.getInstanceId(), equalTo("mhhost:mytest:1")); - assertThat(this.config.getNonSecurePort(), equalTo(7000)); - } - } - - @RunWith(SpringRunner.class) - @SpringBootTest(classes = SidecarApplication.class, webEnvironment = RANDOM_PORT, properties = { - "spring.application.name=mytest", "spring.cloud.client.hostname=mhhost", "spring.application.instance_id=1", - "eureka.instance.hostname=mhhost1", "sidecar.hostname=mhhost2", "sidecar.port=7000", "sidecar.ip-address=127.0.0.1" }) - public static class BothPropertiesEurekaTestConfigBeanTest { - @Autowired - EurekaInstanceConfigBean config; - - @Test - public void testEurekaConfigBeanEurekaInstanceHostnamePropertyShouldBeUsed() { - assertThat(this.config.getAppname(), equalTo("mytest")); - assertThat(this.config.getHostname(), equalTo("mhhost1")); - assertThat(this.config.getInstanceId(), equalTo("mhhost:mytest:1")); - assertThat(this.config.getNonSecurePort(), equalTo(7000)); - } - } - -} diff --git a/spring-cloud-netflix-sidecar/src/test/resources/application.yml b/spring-cloud-netflix-sidecar/src/test/resources/application.yml deleted file mode 100644 index d6dac53b..00000000 --- a/spring-cloud-netflix-sidecar/src/test/resources/application.yml +++ /dev/null @@ -1,29 +0,0 @@ -server: - port: 5678 -spring: - application: - name: sidecarTest - -sidecar: - port: 8000 - health-uri: http://localhost:8000/src/test/resources/health.json - -eureka: - instance: - app-group-name: mysidecargroup - client: - serviceUrl: - defaultZone: http://user:password@localhost:8761/eureka/ - -ribbon: - ServerListRefreshInterval: 5000 - ReadTimeout: 7777 - -endpoints: - refresh: - enabled: true - shutdown: - enabled: true - health: - sensitive: false - diff --git a/spring-cloud-netflix-sidecar/src/test/resources/bootstrap.yml b/spring-cloud-netflix-sidecar/src/test/resources/bootstrap.yml deleted file mode 100644 index bbd58928..00000000 --- a/spring-cloud-netflix-sidecar/src/test/resources/bootstrap.yml +++ /dev/null @@ -1,7 +0,0 @@ -spring: - #application: - # name: sideCarTest - cloud: - config: - username: user - password: password diff --git a/spring-cloud-netflix-sidecar/src/test/resources/health.json b/spring-cloud-netflix-sidecar/src/test/resources/health.json deleted file mode 100644 index 41f3615e..00000000 --- a/spring-cloud-netflix-sidecar/src/test/resources/health.json +++ /dev/null @@ -1 +0,0 @@ -{"status":"UP"} \ No newline at end of file diff --git a/spring-cloud-netflix-turbine-stream/pom.xml b/spring-cloud-netflix-turbine-stream/pom.xml deleted file mode 100644 index 7e16d172..00000000 --- a/spring-cloud-netflix-turbine-stream/pom.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - 4.0.0 - - org.springframework.cloud - spring-cloud-netflix - 2.0.0.BUILD-SNAPSHOT - .. - - spring-cloud-netflix-turbine-stream - jar - Spring Cloud Netflix Turbine Stream - Spring Cloud Netflix Turbine Stream - - ${basedir}/.. - 2.0.0-DP.2 - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.20 - - - ${project.version} - - - - - - - - - com.netflix.turbine - turbine-core - ${turbine.version} - - - com.netflix.rxjava - rxjava-core - - - org.slf4j - slf4j-simple - - - - - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework.cloud - spring-cloud-commons - true - - - org.springframework.integration - spring-integration-core - - - org.springframework.cloud - spring-cloud-netflix-core - - - org.springframework.cloud - spring-cloud-stream - - - com.netflix.turbine - turbine-core - - - io.reactivex - rxjava - - - org.springframework.boot - spring-boot-starter-web - true - - - org.springframework.cloud - spring-cloud-stream-binder-rabbit - true - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.cloud - spring-cloud-starter-contract-stub-runner - test - - - org.springframework.cloud - spring-cloud-netflix-hystrix-contract - test - - - diff --git a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/EnableTurbineStream.java b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/EnableTurbineStream.java deleted file mode 100644 index b4d3de82..00000000 --- a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/EnableTurbineStream.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine.stream; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.springframework.context.annotation.Import; - -/** - * Run the RxNetty based Spring Cloud Turbine Stream server. - * Based on Netflix Turbine 2 and Spring Cloud Stream - * - * @author Spencer Gibb - */ -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Import(TurbineStreamConfiguration.class) -public @interface EnableTurbineStream { - -} diff --git a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/HystrixStreamAggregator.java b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/HystrixStreamAggregator.java deleted file mode 100644 index cac18e40..00000000 --- a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/HystrixStreamAggregator.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine.stream; - -import java.io.IOException; -import java.util.List; -import java.util.Map; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.integration.annotation.ServiceActivator; -import org.springframework.messaging.handler.annotation.Payload; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; - -import rx.subjects.PublishSubject; - -/** - * @author Spencer Gibb - */ -@Component // needed for ServiceActivator to be picked up -public class HystrixStreamAggregator { - - private static final Log log = LogFactory.getLog(HystrixStreamAggregator.class); - - private ObjectMapper objectMapper; - - private PublishSubject> subject; - - @Autowired - public HystrixStreamAggregator(ObjectMapper objectMapper, - PublishSubject> subject) { - this.objectMapper = objectMapper; - this.subject = subject; - } - - @ServiceActivator(inputChannel = TurbineStreamClient.INPUT) - public void sendToSubject(@Payload String payload) { - if (payload.startsWith("\"")) { - // Legacy payload from an Angel client - payload = payload.substring(1, payload.length() - 1); - payload = payload.replace("\\\"", "\""); - } - try { - if (payload.startsWith("[")) { - @SuppressWarnings("unchecked") - List> list = this.objectMapper.readValue(payload, - List.class); - for (Map map : list) { - sendMap(map); - } - } - else { - @SuppressWarnings("unchecked") - Map map = this.objectMapper.readValue(payload, Map.class); - sendMap(map); - } - } - catch (IOException ex) { - log.error("Error receiving hystrix stream payload: " + payload, ex); - } - } - - private void sendMap(Map map) { - Map data = getPayloadData(map); - if (log.isDebugEnabled()) { - log.debug("Received hystrix stream payload: " + data); - } - this.subject.onNext(data); - } - - public static Map getPayloadData(Map jsonMap) { - @SuppressWarnings("unchecked") - Map origin = (Map) jsonMap.get("origin"); - String instanceId = null; - if (origin.containsKey("id")) { - instanceId = origin.get("id").toString(); - } - if (!StringUtils.hasText(instanceId)) { - // TODO: instanceid template - instanceId = origin.get("serviceId") + ":" + origin.get("host") + ":" - + origin.get("port"); - } - @SuppressWarnings("unchecked") - Map data = (Map) jsonMap.get("data"); - data.put("instanceId", instanceId); - return data; - } - -} diff --git a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineApplication.java b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineApplication.java deleted file mode 100644 index 2fa39702..00000000 --- a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineApplication.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.springframework.cloud.netflix.turbine.stream; - -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableAutoConfiguration -@EnableTurbineStream -public class TurbineApplication { - - public static void main(String[] args) { - new SpringApplicationBuilder(TurbineApplication.class).properties( - "spring.config.name=turbine").run(args); - } - -} diff --git a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbinePortApplicationListener.java b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbinePortApplicationListener.java deleted file mode 100644 index 83a89023..00000000 --- a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbinePortApplicationListener.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.springframework.cloud.netflix.turbine.stream; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; -import org.springframework.context.ApplicationListener; -import org.springframework.core.env.MapPropertySource; - -public class TurbinePortApplicationListener implements - ApplicationListener { - - @Override - public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { - Integer serverPort = event.getEnvironment().getProperty("server.port", - Integer.class); - Integer managementPort = event.getEnvironment().getProperty("management.port", - Integer.class); - Integer turbinePort = event.getEnvironment().getProperty("turbine.stream.port", - Integer.class); - if (serverPort == null && managementPort == null) { - return; - } - if (serverPort != Integer.valueOf(-1)) { - Map ports = new HashMap<>(); - if (turbinePort == null) { - // The actual server.port used by the application forced to be -1 (no user - // endpoints) because no value was provided for turbine - ports.put("server.port", -1); - if (serverPort != null) { - // Turbine port defaults to server port value supplied by user - ports.put("turbine.stream.port", serverPort); - } - } - else if (managementPort != null && managementPort != -1 && serverPort == null) { - // User wants 2 ports, but hasn't specified server.port explicitly - ports.put("server.port", managementPort); - } - event.getEnvironment().getPropertySources() - .addFirst(new MapPropertySource("ports", ports)); - } - } - -} diff --git a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamAutoConfiguration.java b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamAutoConfiguration.java deleted file mode 100644 index ecdb026c..00000000 --- a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamAutoConfiguration.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine.stream; - -import java.util.Map; - -import javax.annotation.PostConstruct; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.stream.annotation.EnableBinding; -import org.springframework.cloud.stream.config.BindingProperties; -import org.springframework.cloud.stream.config.BindingServiceProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import rx.subjects.PublishSubject; - -/** - * Autoconfiguration for a Spring Cloud Turbine using Spring Cloud Stream. Enabled by - * default if spring-cloud-stream is on the classpath, and can be switched off with - * turbine.stream.enabled. - * - * @author Spencer Gibb - * @author Dave Syer - */ -@Configuration -@ConditionalOnClass(EnableBinding.class) -@ConditionalOnProperty(value = "turbine.stream.enabled", matchIfMissing = true) -@EnableBinding(TurbineStreamClient.class) -public class TurbineStreamAutoConfiguration { - - @Autowired - private BindingServiceProperties bindings; - - @Autowired - private TurbineStreamProperties properties; - - @PostConstruct - public void init() { - BindingProperties inputBinding = this.bindings.getBindings() - .get(TurbineStreamClient.INPUT); - if (inputBinding == null) { - this.bindings.getBindings().put(TurbineStreamClient.INPUT, - new BindingProperties()); - } - BindingProperties input = this.bindings.getBindings() - .get(TurbineStreamClient.INPUT); - if (input.getDestination() == null) { - input.setDestination(this.properties.getDestination()); - } - if (input.getContentType() == null) { - input.setContentType(this.properties.getContentType()); - } - } - - @Bean - public HystrixStreamAggregator hystrixStreamAggregator(ObjectMapper mapper, - PublishSubject> publisher) { - return new HystrixStreamAggregator(mapper, publisher); - } - -} diff --git a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamClient.java b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamClient.java deleted file mode 100644 index 1e727b73..00000000 --- a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamClient.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine.stream; - -import org.springframework.cloud.stream.annotation.Input; -import org.springframework.messaging.SubscribableChannel; - -/** - * @author Dave Syer - * - */ -public interface TurbineStreamClient { - - String INPUT = "turbineStreamInput"; - - @Input(INPUT) - SubscribableChannel turbineStreamInput(); -} diff --git a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamConfiguration.java b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamConfiguration.java deleted file mode 100644 index 517daf1d..00000000 --- a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamConfiguration.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine.stream; - -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import io.reactivex.netty.RxNetty; -import io.reactivex.netty.protocol.http.server.HttpServer; -import io.reactivex.netty.protocol.http.sse.ServerSentEvent; - -import com.netflix.turbine.aggregator.InstanceKey; -import com.netflix.turbine.aggregator.StreamAggregator; -import com.netflix.turbine.internal.JsonUtility; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.client.actuator.HasFeatures; -import org.springframework.context.SmartLifecycle; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.SocketUtils; - -import static io.reactivex.netty.pipeline.PipelineConfigurators.serveSseConfigurator; - -import rx.Observable; -import rx.subjects.PublishSubject; - -/** - * @author Spencer Gibb - * @author Daniel Lavoie - */ -@Configuration -@EnableConfigurationProperties(TurbineStreamProperties.class) -public class TurbineStreamConfiguration implements SmartLifecycle { - - private static final Log log = LogFactory.getLog(TurbineStreamConfiguration.class); - - private AtomicBoolean running = new AtomicBoolean(false); - - @Autowired - private TurbineStreamProperties properties; - - private int turbinePort; - - @Bean - public HasFeatures Feature() { - return HasFeatures.namedFeature("Turbine (Stream)", - TurbineStreamProperties.class); - } - - @Bean - public PublishSubject> hystrixSubject() { - return PublishSubject.create(); - } - - @Bean - @SuppressWarnings("deprecation") - public HttpServer aggregatorServer() { - // multicast so multiple concurrent subscribers get the same stream - Observable> publishedStreams = StreamAggregator - .aggregateGroupedStreams(hystrixSubject().groupBy( - data -> InstanceKey.create((String) data.get("instanceId")))) - .doOnUnsubscribe(() -> log.info("Unsubscribing aggregation.")) - .doOnSubscribe(() -> log.info("Starting aggregation")).flatMap(o -> o) - .publish().refCount(); - Observable> ping = Observable.timer(1, 10, TimeUnit.SECONDS) - .map(count -> Collections.singletonMap("type", (Object) "Ping")).publish() - .refCount(); - Observable> output = Observable.merge(publishedStreams, ping); - - this.turbinePort = this.properties.getPort(); - - if (this.turbinePort <= 0) { - this.turbinePort = SocketUtils.findAvailableTcpPort(40000); - } - - HttpServer httpServer = RxNetty - .createHttpServer(this.turbinePort, (request, response) -> { - log.info("SSE Request Received"); - response.getHeaders().setHeader("Content-Type", "text/event-stream"); - return output.doOnUnsubscribe( - () -> log.info("Unsubscribing RxNetty server connection")) - .flatMap(data -> response.writeAndFlush(new ServerSentEvent( - null, - Unpooled.copiedBuffer("message", - StandardCharsets.UTF_8), - Unpooled.copiedBuffer(JsonUtility.mapToJson(data), - StandardCharsets.UTF_8)))); - }, serveSseConfigurator()); - return httpServer; - } - - @Override - public boolean isAutoStartup() { - return true; - } - - @Override - public void stop(Runnable callback) { - stop(); - callback.run(); - } - - @Override - public void start() { - if (this.running.compareAndSet(false, true)) { - aggregatorServer().start(); - } - } - - @Override - public void stop() { - if (this.running.compareAndSet(true, false)) { - try { - aggregatorServer().shutdown(); - } - catch (InterruptedException ex) { - log.error("Error shutting down", ex); - } - } - } - - @Override - public boolean isRunning() { - return this.running.get(); - } - - @Override - public int getPhase() { - return 0; - } - - public int getTurbinePort() { - return this.turbinePort; - } - -} diff --git a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamProperties.java b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamProperties.java deleted file mode 100644 index 8c50ecee..00000000 --- a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamProperties.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine.stream; - -import java.util.Objects; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.cloud.netflix.hystrix.HystrixConstants; -import org.springframework.http.MediaType; - -/** - * @author Dave Syer - * @author Gregor Zurowski - */ -@ConfigurationProperties("turbine.stream") -public class TurbineStreamProperties { - - @Value("${server.port:8989}") - private int port = 8989; - - private String destination = HystrixConstants.HYSTRIX_STREAM_DESTINATION; - - private String contentType = MediaType.APPLICATION_JSON_VALUE; - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getDestination() { - return destination; - } - - public void setDestination(String destination) { - this.destination = destination; - } - - public String getContentType() { - return contentType; - } - - public void setContentType(String contentType) { - this.contentType = contentType; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - TurbineStreamProperties that = (TurbineStreamProperties) o; - return port == that.port && Objects.equals(destination, that.destination) - && Objects.equals(contentType, that.contentType); - } - - @Override - public int hashCode() { - return Objects.hash(port, destination, contentType); - } - - @Override - public String toString() { - return new StringBuilder("TurbineStreamProperties{").append("port=").append(port) - .append(", ").append("destination='").append(destination).append("', ") - .append("contentType='").append(contentType).append("'}").toString(); - } - -} diff --git a/spring-cloud-netflix-turbine-stream/src/main/resources/META-INF/spring.factories b/spring-cloud-netflix-turbine-stream/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 1235e5f9..00000000 --- a/spring-cloud-netflix-turbine-stream/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,5 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -org.springframework.cloud.netflix.turbine.stream.TurbineStreamAutoConfiguration - -org.springframework.context.ApplicationListener=\ -org.springframework.cloud.netflix.turbine.stream.TurbinePortApplicationListener \ No newline at end of file diff --git a/spring-cloud-netflix-turbine-stream/src/main/resources/turbine.yml b/spring-cloud-netflix-turbine-stream/src/main/resources/turbine.yml deleted file mode 100644 index 20b58315..00000000 --- a/spring-cloud-netflix-turbine-stream/src/main/resources/turbine.yml +++ /dev/null @@ -1,13 +0,0 @@ -info: - component: Turbine Stream -spring: - application: - name: turbine - jmx: - default_domain: cloud.turbine.stream - -server: - port: 8990 -turbine: - stream: - port: 8989 diff --git a/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/HystrixStreamAggregatorTests.java b/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/HystrixStreamAggregatorTests.java deleted file mode 100644 index 5d9352c3..00000000 --- a/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/HystrixStreamAggregatorTests.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine.stream; - -import java.util.Map; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.junit.Rule; -import org.junit.Test; - -import org.springframework.boot.test.rule.OutputCapture; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.not; -import static org.junit.Assert.assertThat; - -import rx.subjects.PublishSubject; - -public class HystrixStreamAggregatorTests { - - private ObjectMapper mapper = new ObjectMapper(); - - private PublishSubject> publisher = PublishSubject.create(); - - private HystrixStreamAggregator aggregator = new HystrixStreamAggregator(this.mapper, - this.publisher); - - @Rule - public OutputCapture output = new OutputCapture(); - - @Test - public void messageDecoded() throws Exception { - this.publisher.subscribe(map -> { - assertThat(map.get("type"), equalTo("HystrixCommand")); - }); - this.aggregator.sendToSubject(PAYLOAD); - this.output.expect(not(containsString("ERROR"))); - } - - @Test - public void messageWrappedInArray() throws Exception { - this.publisher.subscribe(map -> { - assertThat(map.get("type"), equalTo("HystrixCommand")); - }); - this.aggregator.sendToSubject("[" + PAYLOAD + "]"); - this.output.expect(not(containsString("ERROR"))); - } - - @Test - public void doubleEncodedMessage() throws Exception { - this.publisher.subscribe(map -> { - assertThat(map.get("type"), equalTo("HystrixCommand")); - }); - // If The JSON is embedded in a JSON String this is what it looks like - String payload = "\"" + PAYLOAD.replace("\"", "\\\"") + "\""; - this.aggregator.sendToSubject(payload); - this.output.expect(not(containsString("ERROR"))); - } - - private static String PAYLOAD = "{\"origin\":{\"host\":\"dsyer\",\"port\":-1,\"serviceId\":\"application\",\"id\":\"application\"},\"data\":{\"type\":\"HystrixCommand\",\"name\":\"application.ok\",\"group\":\"MyService\",\"currentTime\":1457089387160,\"isCircuitBreakerOpen\":false,\"errorPercentage\":0,\"errorCount\":0,\"requestCount\":0,\"rollingCountCollapsedRequests\":0,\"rollingCountExceptionsThrown\":0,\"rollingCountFailure\":0,\"rollingCountFallbackFailure\":0,\"rollingCountFallbackRejection\":0,\"rollingCountFallbackSuccess\":0,\"rollingCountResponsesFromCache\":0,\"rollingCountSemaphoreRejected\":0,\"rollingCountShortCircuited\":0,\"rollingCountSuccess\":1,\"rollingCountThreadPoolRejected\":0,\"rollingCountTimeout\":0,\"currentConcurrentExecutionCount\":0,\"latencyExecute_mean\":0,\"latencyExecute\":{\"0\":0,\"25\":0,\"50\":0,\"75\":0,\"90\":0,\"95\":0,\"99\":0,\"99.5\":0,\"100\":0},\"latencyTotal_mean\":0,\"latencyTotal\":{\"0\":0,\"25\":0,\"50\":0,\"75\":0,\"90\":0,\"95\":0,\"99\":0,\"99.5\":0,\"100\":0},\"propertyValue_circuitBreakerRequestVolumeThreshold\":20,\"propertyValue_circuitBreakerSleepWindowInMilliseconds\":5000,\"propertyValue_circuitBreakerErrorThresholdPercentage\":50,\"propertyValue_circuitBreakerForceOpen\":false,\"propertyValue_circuitBreakerForceClosed\":false,\"propertyValue_circuitBreakerEnabled\":true,\"propertyValue_executionIsolationStrategy\":\"THREAD\",\"propertyValue_executionIsolationThreadTimeoutInMilliseconds\":1000,\"propertyValue_executionIsolationThreadInterruptOnTimeout\":true,\"propertyValue_executionIsolationThreadPoolKeyOverride\":null,\"propertyValue_executionIsolationSemaphoreMaxConcurrentRequests\":10,\"propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests\":10,\"propertyValue_metricsRollingStatisticalWindowInMilliseconds\":10000,\"propertyValue_requestCacheEnabled\":true,\"propertyValue_requestLogEnabled\":true,\"reportingHosts\":1}}"; -} diff --git a/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/TurbinePortApplicationListenerTests.java b/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/TurbinePortApplicationListenerTests.java deleted file mode 100644 index 887cfce8..00000000 --- a/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/TurbinePortApplicationListenerTests.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.springframework.cloud.netflix.turbine.stream; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; -import org.springframework.boot.test.util.EnvironmentTestUtils; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.StandardEnvironment; - -public class TurbinePortApplicationListenerTests { - - private TurbinePortApplicationListener listener = new TurbinePortApplicationListener(); - - private ConfigurableEnvironment environment = new StandardEnvironment(); - - private ApplicationEnvironmentPreparedEvent event = new ApplicationEnvironmentPreparedEvent(new SpringApplication(), null, environment); - - @Test - public void noop() { - listener.onApplicationEvent(event); - } - - @Test - public void serverPortOnly() { - EnvironmentTestUtils.addEnvironment(environment, "server.port=9999"); - listener.onApplicationEvent(event); - assertEquals("-1", environment.resolvePlaceholders("${server.port}")); - assertEquals("9999", environment.resolvePlaceholders("${turbine.stream.port}")); - } - - @Test - public void turbinePortOnly() { - EnvironmentTestUtils.addEnvironment(environment, "turbine.stream.port=9999"); - listener.onApplicationEvent(event); - assertEquals("9999", environment.resolvePlaceholders("${turbine.stream.port}")); - assertEquals("0", environment.resolvePlaceholders("${server.port:0}")); - } - - @Test - public void turbineAndManagementPorts() { - EnvironmentTestUtils.addEnvironment(environment, "turbine.stream.port=9999", "management.port=9000"); - listener.onApplicationEvent(event); - assertEquals("9999", environment.resolvePlaceholders("${turbine.stream.port}")); - assertEquals("9000", environment.resolvePlaceholders("${server.port:0}")); - assertEquals("9000", environment.resolvePlaceholders("${management.port:0}")); - } - - @Test - public void turbineAndServerPorts() { - EnvironmentTestUtils.addEnvironment(environment, "turbine.stream.port=9999", "server.port=9000"); - listener.onApplicationEvent(event); - assertEquals("9999", environment.resolvePlaceholders("${turbine.stream.port}")); - assertEquals("9000", environment.resolvePlaceholders("${server.port:0}")); - assertEquals("0", environment.resolvePlaceholders("${management.port:0}")); - } - -} diff --git a/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamTests.java b/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamTests.java deleted file mode 100644 index 1a4466b8..00000000 --- a/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamTests.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine.stream; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URI; -import java.util.Map; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.contract.stubrunner.StubTrigger; -import org.springframework.cloud.contract.stubrunner.spring.AutoConfigureStubRunner; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpRequest; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.http.client.ClientHttpRequestExecution; -import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.integration.support.management.MessageChannelMetrics; -import org.springframework.messaging.SubscribableChannel; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.client.RestTemplate; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Spencer Gibb - * @author Daniel Lavoie - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = TurbineStreamTests.Application.class, webEnvironment = WebEnvironment.NONE, value = { - "turbine.stream.port=0", "spring.jmx.enabled=true", - "spring.main.web-application-type=servlet", - // TODO: we don't need this if we harmonize the turbine and hystrix destinations - // https://github.com/spring-cloud/spring-cloud-netflix/issues/1948 - "spring.cloud.stream.bindings.turbineStreamInput.destination=hystrixStreamOutput", - "spring.jmx.enabled=true", "stubrunner.workOffline=true", - "stubrunner.ids=org.springframework.cloud:spring-cloud-netflix-hystrix-stream:${projectVersion:2.0.0.BUILD-SNAPSHOT}:stubs" }) -@AutoConfigureStubRunner -public class TurbineStreamTests { - @Autowired - StubTrigger stubTrigger; - - @Autowired - ObjectMapper mapper; - - @Autowired - @Qualifier(TurbineStreamClient.INPUT) - SubscribableChannel input; - - RestTemplate rest = new RestTemplate(); - - @Autowired - TurbineStreamConfiguration turbine; - - @EnableAutoConfiguration - @EnableTurbineStream - public static class Application { - } - - @Test - @Ignore // FIXME 2.0.0 Elmurst stream missing class @Controller? - public void contextLoads() throws Exception { - rest.getInterceptors().add(new NonClosingInterceptor()); - int count = ((MessageChannelMetrics) input).getSendCount(); - ResponseEntity response = rest.execute( - new URI("http://localhost:" + turbine.getTurbinePort() + "/"), - HttpMethod.GET, null, this::extract); - assertThat(response.getHeaders().getContentType()) - .isEqualTo(MediaType.TEXT_EVENT_STREAM); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - Map metrics = extractMetrics(response.getBody()); - assertThat(metrics).containsEntry("type", "HystrixCommand"); - assertThat(((MessageChannelMetrics) input).getSendCount()).isEqualTo(count + 1); - } - - private boolean containsMetrics(String line) { - return line.startsWith("data:") && !line.contains("Ping"); - } - - @SuppressWarnings("unchecked") - private Map extractMetrics(String body) throws Exception { - for (String value : body.split("\n")) { - if (containsMetrics(value)) { - return mapper.readValue(value.split("data:")[1], Map.class); - } - } - return null; - } - - private ResponseEntity extract(ClientHttpResponse response) - throws IOException { - // The message has to be sent after the endpoint is activated, so this is a - // convenient place to put it - stubTrigger.trigger("metrics"); - - String responseBody = ""; - boolean metricFound = false; - try (BufferedReader buffer = new BufferedReader( - new InputStreamReader(response.getBody()))) { - do { - String line = buffer.readLine(); - responseBody += line + "\n"; - if (containsMetrics(line)) { - metricFound = true; - } - } - while (!metricFound); - } - - return ResponseEntity.status(response.getStatusCode()) - .headers(response.getHeaders()).body(responseBody); - } - - /** - * Special interceptor that prevents the response from being closed and allows us to - * assert on the contents of an event stream. - */ - private class NonClosingInterceptor implements ClientHttpRequestInterceptor { - - private class NonClosingResponse implements ClientHttpResponse { - - private ClientHttpResponse delegate; - - public NonClosingResponse(ClientHttpResponse delegate) { - this.delegate = delegate; - } - - @Override - public InputStream getBody() throws IOException { - return delegate.getBody(); - } - - @Override - public HttpHeaders getHeaders() { - return delegate.getHeaders(); - } - - @Override - public HttpStatus getStatusCode() throws IOException { - return delegate.getStatusCode(); - } - - @Override - public int getRawStatusCode() throws IOException { - return delegate.getRawStatusCode(); - } - - @Override - public String getStatusText() throws IOException { - return delegate.getStatusText(); - } - - @Override - public void close() { - } - - } - - @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, - ClientHttpRequestExecution execution) throws IOException { - return new NonClosingResponse(execution.execute(request, body)); - } - - } -} diff --git a/spring-cloud-netflix-turbine/pom.xml b/spring-cloud-netflix-turbine/pom.xml deleted file mode 100644 index 1185b7a5..00000000 --- a/spring-cloud-netflix-turbine/pom.xml +++ /dev/null @@ -1,98 +0,0 @@ - - - 4.0.0 - - org.springframework.cloud - spring-cloud-netflix - 2.0.0.BUILD-SNAPSHOT - .. - - spring-cloud-netflix-turbine - jar - Spring Cloud Netflix Turbine - https://projects.spring.io/spring-cloud/ - - ${basedir}/.. - 1.0.0 - - - - - com.netflix.turbine - turbine-core - ${turbine.version} - - - javax.servlet - servlet-api - - - log4j - log4j - - - com.netflix.rxjava - rxjava-core - - - org.slf4j - slf4j-simple - - - org.mockito - mockito-all - - - - - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.cloud - spring-cloud-commons - - - org.springframework.cloud - spring-cloud-context - true - - - org.springframework.cloud - spring-cloud-netflix-core - true - - - org.springframework.cloud - spring-cloud-netflix-eureka-client - true - - - com.netflix.eureka - eureka-client - true - - - org.apache.httpcomponents - httpclient - - - com.netflix.turbine - turbine-core - - - org.springframework.boot - spring-boot-starter-test - test - - - diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/CommonsInstanceDiscovery.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/CommonsInstanceDiscovery.java deleted file mode 100644 index 333d6ac6..00000000 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/CommonsInstanceDiscovery.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.expression.Expression; -import org.springframework.expression.spel.standard.SpelExpressionParser; -import org.springframework.expression.spel.support.StandardEvaluationContext; - -import com.netflix.turbine.discovery.Instance; -import com.netflix.turbine.discovery.InstanceDiscovery; - -/** - * Class that encapsulates an {@link InstanceDiscovery} - * implementation that uses Spring Cloud Commons (see https://github.com/spring-cloud/spring-cloud-commons) - * The plugin requires a list of applications configured. It then queries the set of - * instances for * each application. Instance information retrieved from the {@link DiscoveryClient} - * must be translated to * something that Turbine can understand i.e the - * {@link Instance} class. - *

- * All the logic to perform this translation can be overriden here, so that you can - * provide your own implementation if needed. - * - * @author Spencer Gibb - */ -public class CommonsInstanceDiscovery implements InstanceDiscovery { - - private static final Log log = LogFactory.getLog(CommonsInstanceDiscovery.class); - - private static final String DEFAULT_CLUSTER_NAME_EXPRESSION = "serviceId"; - protected static final String PORT_KEY = "port"; - protected static final String SECURE_PORT_KEY = "securePort"; - protected static final String FUSED_HOST_PORT_KEY = "fusedHostPort"; - - private final Expression clusterNameExpression; - private DiscoveryClient discoveryClient; - private TurbineProperties turbineProperties; - private final boolean combineHostPort; - - public CommonsInstanceDiscovery(TurbineProperties turbineProperties, DiscoveryClient discoveryClient) { - this(turbineProperties, DEFAULT_CLUSTER_NAME_EXPRESSION); - this.discoveryClient = discoveryClient; - } - - protected CommonsInstanceDiscovery(TurbineProperties turbineProperties, String defaultExpression) { - this.turbineProperties = turbineProperties; - SpelExpressionParser parser = new SpelExpressionParser(); - String clusterNameExpression = turbineProperties - .getClusterNameExpression(); - if (clusterNameExpression == null) { - clusterNameExpression = defaultExpression; - } - this.clusterNameExpression = parser.parseExpression(clusterNameExpression); - this.combineHostPort = turbineProperties.isCombineHostPort(); - } - - protected Expression getClusterNameExpression() { - return clusterNameExpression; - } - - public TurbineProperties getTurbineProperties() { - return turbineProperties; - } - - protected boolean isCombineHostPort() { - return combineHostPort; - } - - /** - * Method that queries DiscoveryClient for a list of configured application names - * @return Collection - */ - @Override - public Collection getInstanceList() throws Exception { - List instances = new ArrayList<>(); - List appNames = getApplications(); - if (appNames == null || appNames.size() == 0) { - log.info("No apps configured, returning an empty instance list"); - return instances; - } - log.info("Fetching instance list for apps: " + appNames); - for (String appName : appNames) { - try { - instances.addAll(getInstancesForApp(appName)); - } - catch (Exception ex) { - log.error("Failed to fetch instances for app: " + appName - + ", retrying once more", ex); - try { - instances.addAll(getInstancesForApp(appName)); - } - catch (Exception retryException) { - log.error("Failed again to fetch instances for app: " + appName - + ", giving up", ex); - } - } - } - return instances; - } - - protected List getApplications() { - return turbineProperties.getAppConfigList(); - } - - /** - * helper that fetches the Instances for each application from DiscoveryClient. - * @param serviceId - * @return List - * @throws Exception - */ - protected List getInstancesForApp(String serviceId) throws Exception { - List instances = new ArrayList<>(); - log.info("Fetching instances for app: " + serviceId); - List serviceInstances = discoveryClient.getInstances(serviceId); - if (serviceInstances == null || serviceInstances.isEmpty()) { - log.warn("DiscoveryClient returned null or empty for service: " + serviceId); - return instances; - } - try { - log.info("Received instance list for service: " + serviceId + ", size=" - + serviceInstances.size()); - for (ServiceInstance serviceInstance : serviceInstances) { - Instance instance = marshall(serviceInstance); - if (instance != null) { - instances.add(instance); - } - } - } - catch (Exception e) { - log.warn("Failed to retrieve instances from DiscoveryClient", e); - } - return instances; - } - - /** - * Private helper that marshals the information from each instance into something that - * Turbine can understand. Override this method for your own implementation. - * @param serviceInstance - * @return Instance - */ - Instance marshall(ServiceInstance serviceInstance) { - String hostname = serviceInstance.getHost(); - String managementPort = serviceInstance.getMetadata().get("management.port"); - String port = managementPort == null ? String.valueOf(serviceInstance.getPort()) : managementPort; - String cluster = getClusterName(serviceInstance); - Boolean status = Boolean.TRUE; //TODO: where to get? - if (hostname != null && cluster != null && status != null) { - Instance instance = getInstance(hostname, port, cluster, status); - - Map metadata = serviceInstance.getMetadata(); - boolean securePortEnabled = serviceInstance.isSecure(); - - addMetadata(instance, hostname, port, securePortEnabled, port, metadata); - - return instance; - } - else { - return null; - } - } - - protected void addMetadata(Instance instance, String hostname, String port, boolean securePortEnabled, String securePort, Map metadata) { - // add metadata - if (metadata != null) { - instance.getAttributes().putAll(metadata); - } - - // add ports - instance.getAttributes().put(PORT_KEY, port); - if (securePortEnabled) { - instance.getAttributes().put(SECURE_PORT_KEY, securePort); - } - if (this.isCombineHostPort()) { - String fusedHostPort = securePortEnabled ? hostname+":"+securePort : instance.getHostname() ; - instance.getAttributes().put(FUSED_HOST_PORT_KEY, fusedHostPort); - } - } - - protected Instance getInstance(String hostname, String port, String cluster, Boolean status) { - String hostPart = this.isCombineHostPort() ? hostname+":"+port : hostname; - return new Instance(hostPart, cluster, status); - } - - /** - * Helper that fetches the cluster name. Cluster is a Turbine concept and not a commons - * concept. By default we choose the amazon serviceId as the cluster. A custom - * implementation can be plugged in by overriding this method. - */ - protected String getClusterName(Object object) { - StandardEvaluationContext context = new StandardEvaluationContext(object); - Object value = this.clusterNameExpression.getValue(context); - if (value != null) { - return value.toString(); - } - return null; - } - -} diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/ConfigurationBasedTurbineClustersProvider.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/ConfigurationBasedTurbineClustersProvider.java deleted file mode 100644 index 74c5baf6..00000000 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/ConfigurationBasedTurbineClustersProvider.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.List; - -/** - * Provides clusters names for Turbine based on configuration value. - * - * @author Anastasiia Smirnova - */ -public class ConfigurationBasedTurbineClustersProvider implements TurbineClustersProvider { - - private static final Log log = LogFactory.getLog(ConfigurationBasedTurbineClustersProvider.class); - private final TurbineAggregatorProperties properties; - - public ConfigurationBasedTurbineClustersProvider(TurbineAggregatorProperties turbineAggregatorProperties) { - this.properties = turbineAggregatorProperties; - } - - @Override - public List getClusterNames() { - List clusterNames = properties.getClusterConfig(); - log.trace("Using clusters names: " + clusterNames); - return clusterNames; - } -} diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EnableTurbine.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EnableTurbine.java deleted file mode 100644 index 9dab18ed..00000000 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EnableTurbine.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.springframework.context.annotation.Import; - -/** - * @author Spencer Gibb - */ -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Import(TurbineHttpConfiguration.class) -public @interface EnableTurbine { - -} diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EurekaBasedTurbineClustersProvider.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EurekaBasedTurbineClustersProvider.java deleted file mode 100644 index 87927510..00000000 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EurekaBasedTurbineClustersProvider.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine; - -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.shared.Application; -import com.netflix.discovery.shared.Applications; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.List; - -/** - * Provides clusters names for Turbine based on applications names registered in Eureka. - * - * @author Anastasiia Smirnova - */ -public class EurekaBasedTurbineClustersProvider implements TurbineClustersProvider { - - private static final Log log = LogFactory.getLog(EurekaBasedTurbineClustersProvider.class); - private final EurekaClient eurekaClient; - - public EurekaBasedTurbineClustersProvider(EurekaClient eurekaClient) { - this.eurekaClient = eurekaClient; - } - - @Override - public List getClusterNames() { - Applications applications = eurekaClient.getApplications(); - List registeredApplications = applications.getRegisteredApplications(); - List appNames = new ArrayList<>(registeredApplications.size()); - for (Application application : registeredApplications) { - appNames.add(application.getName()); - } - log.trace("Using clusters names: " + appNames); - return appNames; - } -} diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EurekaInstanceDiscovery.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EurekaInstanceDiscovery.java deleted file mode 100644 index 426ce991..00000000 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EurekaInstanceDiscovery.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import com.netflix.appinfo.AmazonInfo; -import com.netflix.appinfo.DataCenterInfo; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.appinfo.InstanceInfo.InstanceStatus; -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.shared.Application; -import com.netflix.turbine.discovery.Instance; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Class that encapsulates an {@link com.netflix.turbine.discovery.InstanceDiscovery} - * implementation that uses Eureka (see https://github.com/Netflix/eureka) The plugin - * requires a list of applications configured. It then queries the set of instances for - * each application. Instance information retrieved from Eureka must be translated to - * something that Turbine can understand i.e the - * {@link com.netflix.turbine.discovery.Instance} class. - *

- * All the logic to perform this translation can be overriden here, so that you can - * provide your own implementation if needed. - * - * @author Spencer Gibb - */ -public class EurekaInstanceDiscovery extends CommonsInstanceDiscovery { - - private static final Log log = LogFactory.getLog(EurekaInstanceDiscovery.class); - - private static final String EUREKA_DEFAULT_CLUSTER_NAME_EXPRESSION = "appName"; - private static final String ASG_KEY = "asg"; - - private final EurekaClient eurekaClient; - - - public EurekaInstanceDiscovery(TurbineProperties turbineProperties, EurekaClient eurekaClient) { - super(turbineProperties, EUREKA_DEFAULT_CLUSTER_NAME_EXPRESSION); - this.eurekaClient = eurekaClient; - } - - /** - * Private helper that fetches the Instances for each application. - * @param serviceId - * @return List - * @throws Exception - */ - @Override - protected List getInstancesForApp(String serviceId) throws Exception { - List instances = new ArrayList<>(); - log.info("Fetching instances for app: " + serviceId); - Application app = eurekaClient.getApplication(serviceId); - if (app == null) { - log.warn("Eureka returned null for app: " + serviceId); - return instances; - } - try { - List instancesForApp = app.getInstances(); - if (instancesForApp != null) { - log.info("Received instance list for app: " + serviceId + ", size=" - + instancesForApp.size()); - for (InstanceInfo iInfo : instancesForApp) { - Instance instance = marshall(iInfo); - if (instance != null) { - instances.add(instance); - } - } - } - } - catch (Exception e) { - log.warn("Failed to retrieve instances from Eureka", e); - } - return instances; - } - - /** - * Private helper that marshals the information from each instance into something that - * Turbine can understand. Override this method for your own implementation for - * parsing Eureka info. - * @param instanceInfo - * @return Instance - */ - Instance marshall(InstanceInfo instanceInfo) { - String hostname = instanceInfo.getHostName(); - final String managementPort = instanceInfo.getMetadata().get("management.port"); - String port = managementPort == null ? String.valueOf(instanceInfo.getPort()) : managementPort; - String cluster = getClusterName(instanceInfo); - Boolean status = parseInstanceStatus(instanceInfo.getStatus()); - if (hostname != null && cluster != null && status != null) { - Instance instance = getInstance(hostname, port, cluster, status); - - Map metadata = instanceInfo.getMetadata(); - boolean securePortEnabled = instanceInfo.isPortEnabled(InstanceInfo.PortType.SECURE); - String securePort = String.valueOf(instanceInfo.getSecurePort()); - - addMetadata(instance, hostname, port, securePortEnabled, securePort, metadata); - - // add amazon metadata - String asgName = instanceInfo.getASGName(); - if (asgName != null) { - instance.getAttributes().put(ASG_KEY, asgName); - } - - DataCenterInfo dcInfo = instanceInfo.getDataCenterInfo(); - if (dcInfo != null && dcInfo.getName().equals(DataCenterInfo.Name.Amazon)) { - AmazonInfo amznInfo = (AmazonInfo) dcInfo; - instance.getAttributes().putAll(amznInfo.getMetadata()); - } - - return instance; - } - else { - return null; - } - } - - /** - * Helper that returns whether the instance is Up of Down - */ - protected Boolean parseInstanceStatus(InstanceStatus status) { - if (status == null) { - return null; - } - return status == InstanceStatus.UP; - } - - -} diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/SpringAggregatorFactory.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/SpringAggregatorFactory.java deleted file mode 100644 index efc53e52..00000000 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/SpringAggregatorFactory.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine; - -import java.util.Collection; - -import com.netflix.turbine.data.AggDataFromCluster; -import com.netflix.turbine.discovery.Instance; -import com.netflix.turbine.handler.PerformanceCriteria; -import com.netflix.turbine.handler.TurbineDataHandler; -import com.netflix.turbine.monitor.TurbineDataMonitor; -import com.netflix.turbine.monitor.cluster.AggregateClusterMonitor; -import com.netflix.turbine.monitor.cluster.ClusterMonitor; -import com.netflix.turbine.monitor.cluster.ClusterMonitorFactory; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import static com.netflix.turbine.monitor.cluster.AggregateClusterMonitor.AggregatorClusterMonitorConsole; - -/** - * @author Spencer Gibb - */ -public class SpringAggregatorFactory implements ClusterMonitorFactory { - - private static final Log log = LogFactory.getLog(SpringAggregatorFactory.class); - - private final TurbineClustersProvider clustersProvider; - - public SpringAggregatorFactory(TurbineClustersProvider clustersProvider) { - this.clustersProvider = clustersProvider; - } - - /** - * @return {@link com.netflix.turbine.monitor.cluster.ClusterMonitor}< - * {@link com.netflix.turbine.data.AggDataFromCluster}> - */ - @Override - public ClusterMonitor getClusterMonitor(String name) { - TurbineDataMonitor clusterMonitor = AggregateClusterMonitor.AggregatorClusterMonitorConsole - .findMonitor(name + "_agg"); - return (ClusterMonitor) clusterMonitor; - } - - public static TurbineDataMonitor findOrRegisterAggregateMonitor( - String clusterName) { - TurbineDataMonitor clusterMonitor = AggregatorClusterMonitorConsole - .findMonitor(clusterName + "_agg"); - if (clusterMonitor == null) { - log.info("Could not find monitors: " - + AggregatorClusterMonitorConsole.toString()); - clusterMonitor = new SpringClusterMonitor(clusterName + "_agg", clusterName); - clusterMonitor = AggregatorClusterMonitorConsole - .findOrRegisterMonitor(clusterMonitor); - } - return clusterMonitor; - } - - @Override - public void initClusterMonitors() { - for (String clusterName : clustersProvider.getClusterNames()) { - ClusterMonitor clusterMonitor = (ClusterMonitor) findOrRegisterAggregateMonitor(clusterName); - clusterMonitor.registerListenertoClusterMonitor(this.StaticListener); - try { - clusterMonitor.startMonitor(); - } - catch (Exception ex) { - log.warn("Could not init cluster monitor for: " + clusterName); - clusterMonitor.stopMonitor(); - clusterMonitor.getDispatcher().stopDispatcher(); - } - } - } - - /** - * shutdown all configured cluster monitors - */ - @Override - public void shutdownClusterMonitors() { - for (String clusterName : clustersProvider.getClusterNames()) { - ClusterMonitor clusterMonitor = (ClusterMonitor) AggregateClusterMonitor - .findOrRegisterAggregateMonitor(clusterName); - clusterMonitor.stopMonitor(); - clusterMonitor.getDispatcher().stopDispatcher(); - } - } - - private TurbineDataHandler StaticListener = new TurbineDataHandler() { - - @Override - public String getName() { - return "StaticListener_For_Aggregator"; - } - - @Override - public void handleData(Collection stats) { - } - - @Override - public void handleHostLost(Instance host) { - } - - @Override - public PerformanceCriteria getCriteria() { - return SpringAggregatorFactory.this.NonCriticalCriteria; - } - - }; - - private PerformanceCriteria NonCriticalCriteria = new PerformanceCriteria() { - - @Override - public boolean isCritical() { - return false; - } - - @Override - public int getMaxQueueSize() { - return 0; - } - - @Override - public int numThreads() { - return 0; - } - - }; -} diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/SpringClusterMonitor.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/SpringClusterMonitor.java deleted file mode 100644 index 0b680900..00000000 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/SpringClusterMonitor.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine; - -import com.netflix.config.DynamicBooleanProperty; -import com.netflix.config.DynamicPropertyFactory; -import com.netflix.config.DynamicStringProperty; -import com.netflix.turbine.data.DataFromSingleInstance; -import com.netflix.turbine.discovery.Instance; -import com.netflix.turbine.handler.PerformanceCriteria; -import com.netflix.turbine.monitor.MonitorConsole; -import com.netflix.turbine.monitor.cluster.AggregateClusterMonitor; -import com.netflix.turbine.monitor.cluster.ObservationCriteria; -import com.netflix.turbine.monitor.instance.InstanceUrlClosure; - -/** - * @author Spencer Gibb - */ -public class SpringClusterMonitor extends AggregateClusterMonitor { - - // TODO: convert to ConfigurationProperties (how to do per-cluster configuration? - - public SpringClusterMonitor(String name, String clusterName) { - super(name, new ObservationCriteria.ClusterBasedObservationCriteria(clusterName), - new PerformanceCriteria.AggClusterPerformanceCriteria(clusterName), - new MonitorConsole(), InstanceMonitorDispatcher, - SpringClusterMonitor.ClusterConfigBasedUrlClosure); - } - - /** - * TODO: make this a template of some kind (secure, management port, etc...) Helper - * class that decides how to connect to a server based on injected config. Note that - * the cluster name must be provided here since one can have different configs for - * different clusters - */ - public static InstanceUrlClosure ClusterConfigBasedUrlClosure = new InstanceUrlClosure() { - - private final DynamicStringProperty defaultUrlClosureConfig = DynamicPropertyFactory - .getInstance().getStringProperty("turbine.instanceUrlSuffix", - "hystrix.stream"); - private final DynamicBooleanProperty instanceInsertPort = DynamicPropertyFactory - .getInstance().getBooleanProperty("turbine.instanceInsertPort", true); - - @Override - public String getUrlPath(Instance host) { - if (host.getCluster() == null) { - throw new RuntimeException( - "Host must have cluster name in order to use ClusterConfigBasedUrlClosure"); - } - - // find url - String key = "turbine.instanceUrlSuffix." + host.getCluster(); - DynamicStringProperty urlClosureConfig = DynamicPropertyFactory.getInstance() - .getStringProperty(key, null); - String url = urlClosureConfig.get(); - if (url == null) { - url = this.defaultUrlClosureConfig.get(); - } - if (url == null) { - throw new RuntimeException("Config property: " - + urlClosureConfig.getName() + " or " - + this.defaultUrlClosureConfig.getName() + " must be set"); - } - - // find port and scheme - String port; - String scheme; - if (host.getAttributes().containsKey("securePort")) { - port = host.getAttributes().get("securePort"); - scheme = "https"; - } else { - port = host.getAttributes().get("port"); - scheme = "http"; - } - - if (host.getAttributes().containsKey("fusedHostPort")) { - return String.format("%s://%s/%s", scheme, host.getAttributes().get("fusedHostPort"), url); - } - - // determine if to insert port - String insertPortKey = "turbine.instanceInsertPort." + host.getCluster(); - DynamicStringProperty insertPortProp = DynamicPropertyFactory.getInstance() - .getStringProperty(insertPortKey, null); - boolean insertPort; - if (insertPortProp.get() == null) { - insertPort = this.instanceInsertPort.get(); - } - else { - insertPort = Boolean.parseBoolean(insertPortProp.get()); - } - - // format url with port - if (insertPort) { - if (url.startsWith("/")) { - url = url.substring(1); - } - if (port == null) { - throw new RuntimeException( - "Configured to use port, but port or securePort is not in host attributes"); - } - - return String.format("%s://%s:%s/%s", scheme, host.getHostname(), port, url); - } - - //format url without port - return scheme + "://" + host.getHostname() + url; - } - }; - -} diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineAggregatorProperties.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineAggregatorProperties.java deleted file mode 100644 index e7f7e9d2..00000000 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineAggregatorProperties.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -/** - * @author Anastasiia Smirnova - */ -@ConfigurationProperties("turbine.aggregator") -public class TurbineAggregatorProperties { - - private static final String DEFAULT = "default"; - /** - * The list of cluster names. - */ - private List clusterConfig = Collections.singletonList(DEFAULT); - - public List getClusterConfig() { - return clusterConfig; - } - - public void setClusterConfig(List clusterConfig) { - this.clusterConfig = clusterConfig; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - TurbineAggregatorProperties that = (TurbineAggregatorProperties) o; - return Objects.equals(clusterConfig, that.clusterConfig); - } - - @Override - public int hashCode() { - return Objects.hash(clusterConfig); - } - - @Override - public String toString() { - return "TurbineAggregatorProperties{" + "clusterConfig='" + clusterConfig + '\'' - + '}'; - } -} diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineClustersProvider.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineClustersProvider.java deleted file mode 100644 index 1e17cccc..00000000 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineClustersProvider.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine; - -import java.util.List; - -/** - * Interface that gives possibility to customize which clusters names Turbine will use. - * - * @author Anastasiia Smirnova - */ -public interface TurbineClustersProvider { - - List getClusterNames(); -} diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineHttpConfiguration.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineHttpConfiguration.java deleted file mode 100644 index 23ca5969..00000000 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineHttpConfiguration.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine; - -import com.netflix.turbine.monitor.cluster.ClusterMonitorFactory; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.web.servlet.ServletRegistrationBean; -import org.springframework.cloud.client.actuator.HasFeatures; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.netflix.discovery.EurekaClient; -import com.netflix.turbine.discovery.InstanceDiscovery; -import com.netflix.turbine.streaming.servlet.TurbineStreamServlet; - -/** - * @author Spencer Gibb - */ -@Configuration -@EnableConfigurationProperties -public class TurbineHttpConfiguration { - - @Bean - public HasFeatures Feature() { - return HasFeatures.namedFeature("Turbine (HTTP)", TurbineHttpConfiguration.class); - } - - @Bean - @ConditionalOnMissingBean(name = "turbineStreamServlet") - public ServletRegistrationBean turbineStreamServlet() { - return new ServletRegistrationBean(new TurbineStreamServlet(), "/turbine.stream"); - } - - @Bean - @ConditionalOnMissingBean - public TurbineProperties turbineProperties() { - return new TurbineProperties(); - } - - @Bean - @ConditionalOnMissingBean - public TurbineAggregatorProperties turbineAggregatorProperties() { - return new TurbineAggregatorProperties(); - } - - @Bean - @ConditionalOnMissingBean - public TurbineLifecycle turbineLifecycle(InstanceDiscovery instanceDiscovery, - ClusterMonitorFactory factory) { - return new TurbineLifecycle(instanceDiscovery, factory); - } - - @Bean - @ConditionalOnMissingBean - public ClusterMonitorFactory clusterMonitorFactory(TurbineClustersProvider clustersProvider) { - return new SpringAggregatorFactory(clustersProvider); - } - - @Bean - @ConditionalOnMissingBean - public TurbineClustersProvider clustersProvider(TurbineAggregatorProperties turbineAggregatorProperties) { - return new ConfigurationBasedTurbineClustersProvider(turbineAggregatorProperties); - } - - @Configuration - @ConditionalOnClass(EurekaClient.class) - protected static class EurekaTurbineConfiguration { - - @Bean - @ConditionalOnMissingBean - public InstanceDiscovery instanceDiscovery(TurbineProperties turbineProperties, EurekaClient eurekaClient) { - return new EurekaInstanceDiscovery(turbineProperties, eurekaClient); - } - - } - - @Configuration - @ConditionalOnMissingClass("com.netflix.discovery.EurekaClient") - protected static class DiscoveryClientTurbineConfiguration { - - @Bean - @ConditionalOnMissingBean - public InstanceDiscovery instanceDiscovery(TurbineProperties turbineProperties, DiscoveryClient discoveryClient) { - return new CommonsInstanceDiscovery(turbineProperties, discoveryClient); - } - } -} diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineLifecycle.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineLifecycle.java deleted file mode 100644 index 019a8ce7..00000000 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineLifecycle.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine; - -import com.netflix.turbine.monitor.cluster.ClusterMonitorFactory; -import org.springframework.context.SmartLifecycle; -import org.springframework.core.Ordered; - -import com.netflix.turbine.discovery.InstanceDiscovery; -import com.netflix.turbine.init.TurbineInit; -import com.netflix.turbine.plugins.PluginsFactory; - -/** - * @author Spencer Gibb - */ -public class TurbineLifecycle implements SmartLifecycle, Ordered { - - private final InstanceDiscovery instanceDiscovery; - private final ClusterMonitorFactory factory; - - private volatile boolean running; - - public TurbineLifecycle(InstanceDiscovery instanceDiscovery, ClusterMonitorFactory factory) { - this.instanceDiscovery = instanceDiscovery; - this.factory = factory; - } - - @Override - public boolean isAutoStartup() { - return true; - } - - @Override - public void stop(Runnable callback) { - callback.run(); - } - - @Override - public void start() { - PluginsFactory.setClusterMonitorFactory(factory); - PluginsFactory.setInstanceDiscovery(instanceDiscovery); - TurbineInit.init(); - } - - @Override - public void stop() { - this.running = false; - } - - @Override - public boolean isRunning() { - return this.running; - } - - @Override - public int getPhase() { - return 0; - } - - @Override - public int getOrder() { - return -1; - } - -} diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineProperties.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineProperties.java deleted file mode 100644 index 4dfd0f14..00000000 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineProperties.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine; - -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.util.StringUtils; - -/** - * @author Spencer Gibb - * @author Gregor Zurowski - */ -@ConfigurationProperties("turbine") -public class TurbineProperties { - - private String clusterNameExpression; - - private String appConfig; - - private boolean combineHostPort = true; - - public List getAppConfigList() { - if (!StringUtils.hasText(this.appConfig)) { - return null; - } - String[] parts = StringUtils.commaDelimitedListToStringArray(this.appConfig); - if (parts != null && parts.length > 0) { - parts = StringUtils.trimArrayElements(parts); - return Arrays.asList(parts); - } - return null; - } - - public String getClusterNameExpression() { - return clusterNameExpression; - } - - public void setClusterNameExpression(String clusterNameExpression) { - this.clusterNameExpression = clusterNameExpression; - } - - public String getAppConfig() { - return appConfig; - } - - public void setAppConfig(String appConfig) { - this.appConfig = appConfig; - } - - public boolean isCombineHostPort() { - return combineHostPort; - } - - public void setCombineHostPort(boolean combineHostPort) { - this.combineHostPort = combineHostPort; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - TurbineProperties that = (TurbineProperties) o; - return Objects.equals(clusterNameExpression, that.clusterNameExpression) && - Objects.equals(appConfig, that.appConfig) && - Objects.equals(combineHostPort, that.combineHostPort); - } - - @Override - public int hashCode() { - return Objects.hash(clusterNameExpression, appConfig, combineHostPort); - } - - @Override - public String toString() { - return new StringBuilder("TurbineProperties{") - .append("clusterNameExpression='").append(clusterNameExpression).append("', ") - .append("appConfig='").append(appConfig).append("', ") - .append("combineHostPort=").append(combineHostPort).append("}") - .toString(); - } - -} diff --git a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/CommonsInstanceDiscoveryTests.java b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/CommonsInstanceDiscoveryTests.java deleted file mode 100644 index 0d227514..00000000 --- a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/CommonsInstanceDiscoveryTests.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine; - -import java.util.Collections; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.cloud.client.DefaultServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; - -import com.netflix.turbine.discovery.Instance; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; - -/** - * @author Spencer Gibb - */ -public class CommonsInstanceDiscoveryTests { - - private DiscoveryClient discoveryClient; - private TurbineProperties turbineProperties; - - @Before - public void setUp() throws Exception { - this.discoveryClient = mock(DiscoveryClient.class); - this.turbineProperties = new TurbineProperties(); - } - - @Test - public void testSecureCombineHostPort() { - turbineProperties.setCombineHostPort(true); - CommonsInstanceDiscovery discovery = createDiscovery(); - String appName = "testAppName"; - int port = 8443; - String hostName = "myhost"; - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, hostName, port, true); - Instance instance = discovery.marshall(serviceInstance); - assertEquals("port is wrong", String.valueOf(port), instance.getAttributes().get("port")); - assertEquals("securePort is wrong", String.valueOf(port), instance.getAttributes().get("securePort")); - - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "https://"+hostName+":"+port+"/hystrix.stream", urlPath); - } - - @Test - public void testCombineHostPort() { - turbineProperties.setCombineHostPort(true); - CommonsInstanceDiscovery discovery = createDiscovery(); - String appName = "testAppName"; - int port = 8080; - String hostName = "myhost"; - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, hostName, port, false); - Instance instance = discovery.marshall(serviceInstance); - assertEquals("hostname is wrong", hostName+":"+port, instance.getHostname()); - assertEquals("port is wrong", String.valueOf(port), instance.getAttributes().get("port")); - - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "http://"+hostName+":"+port+"/hystrix.stream", urlPath); - - String clusterName = discovery.getClusterName(serviceInstance); - assertEquals("clusterName is wrong", appName, clusterName); - } - - @Test - public void testGetClusterName() { - CommonsInstanceDiscovery discovery = createDiscovery(); - String appName = "testAppName"; - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, "myhost", 8080, false); - String clusterName = discovery.getClusterName(serviceInstance); - assertEquals("clusterName is wrong", appName, clusterName); - } - - @Test - public void testGetPort() { - CommonsInstanceDiscovery discovery = createDiscovery(); - String appName = "testAppName"; - int port = 8080; - String hostName = "myhost"; - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, hostName, port, false); - Instance instance = discovery.marshall(serviceInstance); - assertEquals("port is wrong", String.valueOf(port), instance.getAttributes().get("port")); - - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "http://"+hostName+":"+port+"/hystrix.stream", urlPath); - } - - @Test - public void testUseManagementPortFromMetadata() { - CommonsInstanceDiscovery discovery = createDiscovery(); - String appName = "testAppName"; - int port = 8080; - int managementPort = 8081; - String hostName = "myhost"; - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, hostName, port, false); - serviceInstance.getMetadata().put("management.port", String.valueOf(managementPort)); - Instance instance = discovery.marshall(serviceInstance); - assertEquals("port is wrong", String.valueOf(managementPort), instance.getAttributes().get("port")); - - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "http://"+hostName+":"+managementPort+"/hystrix.stream", urlPath); - } - - @Test - public void testGetSecurePort() { - CommonsInstanceDiscovery discovery = createDiscovery(); - String appName = "testAppName"; - //int port = 8080; - int port = 8443; - String hostName = "myhost"; - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, hostName, port, true); - Instance instance = discovery.marshall(serviceInstance); - assertEquals("port is wrong", String.valueOf(port), instance.getAttributes().get("port")); - assertEquals("securePort is wrong", String.valueOf(port), instance.getAttributes().get("securePort")); - - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "https://"+hostName+":"+port+"/hystrix.stream", urlPath); - } - - @Test - public void testGetClusterNameCustomExpression() { - turbineProperties.setClusterNameExpression("host"); - CommonsInstanceDiscovery discovery = createDiscovery(); - String appName = "testAppName"; - String hostName = "myhost"; - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, hostName, 8080, true); - String clusterName = discovery.getClusterName(serviceInstance); - assertEquals("clusterName is wrong", hostName, clusterName); - } - - @Test - public void testGetClusterNameInstanceMetadataMapExpression() { - turbineProperties.setClusterNameExpression("metadata['cluster']"); - CommonsInstanceDiscovery discovery = createDiscovery(); - String metadataProperty = "myCluster"; - String appName = "testAppName"; - String hostName = "myhost"; - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, hostName, 8080, true, Collections.singletonMap("cluster", metadataProperty)); - String clusterName = discovery.getClusterName(serviceInstance); - assertEquals("clusterName is wrong", metadataProperty, clusterName); - } - - private CommonsInstanceDiscovery createDiscovery() { - return new CommonsInstanceDiscovery(turbineProperties, discoveryClient); - } - -} diff --git a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/ConfigurationBasedTurbineClustersProviderTest.java b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/ConfigurationBasedTurbineClustersProviderTest.java deleted file mode 100644 index 5115f342..00000000 --- a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/ConfigurationBasedTurbineClustersProviderTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.springframework.cloud.netflix.turbine; - -import org.junit.Test; - -import java.util.Arrays; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ConfigurationBasedTurbineClustersProviderTest { - - @Test - public void shouldReturnDefaultClusterIfConfigurationIsEmpty() throws Exception { - TurbineAggregatorProperties properties = new TurbineAggregatorProperties(); - TurbineClustersProvider provider = new ConfigurationBasedTurbineClustersProvider( - properties); - List clusterNames = provider.getClusterNames(); - - assertThat(clusterNames).containsOnly("default"); - } - - @Test - public void shouldReturnConfiguredClusters() throws Exception { - TurbineAggregatorProperties properties = new TurbineAggregatorProperties(); - properties.setClusterConfig(Arrays.asList("cluster1", "cluster2", "cluster3")); - TurbineClustersProvider provider = new ConfigurationBasedTurbineClustersProvider( - properties); - List clusterNames = provider.getClusterNames(); - - assertThat(clusterNames).containsOnly("cluster1", "cluster2", "cluster3"); - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/EurekaBasedTurbineClustersProviderTest.java b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/EurekaBasedTurbineClustersProviderTest.java deleted file mode 100644 index 1b7ebcf7..00000000 --- a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/EurekaBasedTurbineClustersProviderTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.springframework.cloud.netflix.turbine; - -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.shared.Application; -import com.netflix.discovery.shared.Applications; -import org.junit.Test; - -import java.util.List; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class EurekaBasedTurbineClustersProviderTest { - - EurekaClient eurekaClient = mock(EurekaClient.class); - TurbineClustersProvider provider = new EurekaBasedTurbineClustersProvider(eurekaClient); - - @Test - public void shouldProvideAllClustersNames() throws Exception { - Applications applications = registeredApplications(asList(application("service1"), - application("service2"), application("service3"))); - when(eurekaClient.getApplications()).thenReturn(applications); - - List clusterNames = provider.getClusterNames(); - - assertThat(clusterNames).containsOnly("service1", "service2", "service3"); - } - - private Applications registeredApplications(List registered) { - Applications applications = mock(Applications.class); - when(applications.getRegisteredApplications()).thenReturn(registered); - return applications; - } - - private Application application(String name) { - Application application = mock(Application.class); - when(application.getName()).thenReturn(name); - return application; - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/EurekaInstanceDiscoveryTests.java b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/EurekaInstanceDiscoveryTests.java deleted file mode 100644 index f04d4c68..00000000 --- a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/EurekaInstanceDiscoveryTests.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine; - -import org.junit.Before; -import org.junit.Test; - -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.EurekaClient; -import com.netflix.turbine.discovery.Instance; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; - -/** - * @author Spencer Gibb - */ -public class EurekaInstanceDiscoveryTests { - - private EurekaClient eurekaClient; - private TurbineProperties turbineProperties; - private InstanceInfo.Builder builder; - - @Before - public void setUp() throws Exception { - eurekaClient = mock(EurekaClient.class); - turbineProperties = new TurbineProperties(); - builder = InstanceInfo.Builder.newBuilder(); - } - - @Test - public void testSecureCombineHostPort() { - turbineProperties.setCombineHostPort(true); - EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery( - turbineProperties, eurekaClient); - String appName = "testAppName"; - int port = 8080; - int securePort = 8443; - String hostName = "myhost"; - InstanceInfo instanceInfo = builder.setAppName(appName) - .setHostName(hostName) - .setPort(port) - .setSecurePort(securePort) - .enablePort(InstanceInfo.PortType.SECURE, true) - .build(); - Instance instance = discovery.marshall(instanceInfo); - assertEquals("port is wrong", String.valueOf(port), instance.getAttributes().get("port")); - assertEquals("securePort is wrong", String.valueOf(securePort), instance.getAttributes().get("securePort")); - - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "https://"+hostName+":"+securePort+"/hystrix.stream", urlPath); - } - - @Test - public void testCombineHostPort() { - turbineProperties.setCombineHostPort(true); - EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery( - turbineProperties, eurekaClient); - String appName = "testAppName"; - int port = 8080; - String hostName = "myhost"; - InstanceInfo instanceInfo = builder.setAppName(appName) - .setHostName(hostName) - .setPort(port) - .build(); - Instance instance = discovery.marshall(instanceInfo); - assertEquals("hostname is wrong", hostName+":"+port, instance.getHostname()); - assertEquals("port is wrong", String.valueOf(port), instance.getAttributes().get("port")); - - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "http://"+hostName+":"+port+"/hystrix.stream", urlPath); - - String clusterName = discovery.getClusterName(instanceInfo); - assertEquals("clusterName is wrong", appName.toUpperCase(), clusterName); - } - - @Test - public void testUseManagementPortFromMetadata() { - EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery(turbineProperties, - eurekaClient); - String appName = "testAppName"; - int port = 8080; - int managementPort = 8081; - String hostName = "myhost"; - InstanceInfo instanceInfo = builder.setAppName(appName).setHostName(hostName).setPort(port) - .build(); - instanceInfo.getMetadata().put("management.port", "8081"); - Instance instance = discovery.marshall(instanceInfo); - assertEquals("hostname is wrong", hostName + ":" + managementPort, instance.getHostname()); - assertEquals("port is wrong", String.valueOf(managementPort), - instance.getAttributes().get("port")); - - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", - "http://" + hostName + ":" + managementPort + "/hystrix.stream", urlPath); - - String clusterName = discovery.getClusterName(instanceInfo); - assertEquals("clusterName is wrong", appName.toUpperCase(), clusterName); - } - - @Test - public void testGetClusterName() { - EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery(turbineProperties, - eurekaClient); - String appName = "testAppName"; - InstanceInfo instanceInfo = builder.setAppName(appName).build(); - String clusterName = discovery.getClusterName(instanceInfo); - assertEquals("clusterName is wrong", appName.toUpperCase(), clusterName); - } - - @Test - public void testGetPort() { - EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery( - turbineProperties, eurekaClient); - String appName = "testAppName"; - int port = 8080; - String hostName = "myhost"; - InstanceInfo instanceInfo = builder.setAppName(appName) - .setHostName(hostName) - .setPort(port) - .build(); - Instance instance = discovery.marshall(instanceInfo); - assertEquals("port is wrong", String.valueOf(port), instance.getAttributes().get("port")); - - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "http://"+hostName+":"+port+"/hystrix.stream", urlPath); - } - - @Test - public void testGetSecurePort() { - EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery( - turbineProperties, eurekaClient); - String appName = "testAppName"; - int port = 8080; - int securePort = 8443; - String hostName = "myhost"; - InstanceInfo instanceInfo = builder.setAppName(appName) - .setHostName(hostName) - .setPort(port) - .setSecurePort(securePort) - .enablePort(InstanceInfo.PortType.SECURE, true) - .build(); - Instance instance = discovery.marshall(instanceInfo); - assertEquals("port is wrong", String.valueOf(port), instance.getAttributes().get("port")); - assertEquals("securePort is wrong", String.valueOf(securePort), instance.getAttributes().get("securePort")); - - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "https://"+hostName+":"+securePort+"/hystrix.stream", urlPath); - } - - @Test - public void testGetClusterNameCustomExpression() { - turbineProperties.setClusterNameExpression("aSGName"); - EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery(turbineProperties, eurekaClient); - String asgName = "myAsgName"; - InstanceInfo instanceInfo = builder - .setAppName("testApp").setASGName(asgName).build(); - String clusterName = discovery.getClusterName(instanceInfo); - assertEquals("clusterName is wrong", asgName, clusterName); - } - - @Test - public void testGetClusterNameInstanceMetadataMapExpression() { - turbineProperties.setClusterNameExpression("metadata['cluster']"); - EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery(turbineProperties, eurekaClient); - String metadataProperty = "myCluster"; - InstanceInfo instanceInfo = builder - .setAppName("testApp").add("cluster", metadataProperty).build(); - String clusterName = discovery.getClusterName(instanceInfo); - assertEquals("clusterName is wrong", metadataProperty, clusterName); - } - -} diff --git a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/TurbineAggregatorPropertiesTest.java b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/TurbineAggregatorPropertiesTest.java deleted file mode 100644 index 80ceb1b2..00000000 --- a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/TurbineAggregatorPropertiesTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.springframework.cloud.netflix.turbine; - -import org.junit.After; -import org.junit.Test; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Configuration; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.boot.test.util.EnvironmentTestUtils.addEnvironment; - -public class TurbineAggregatorPropertiesTest { - - private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - - @After - public void clear() { - if (this.context != null) { - this.context.close(); - } - } - - @Test - public void shouldHaveDefaultConfiguration() throws Exception { - setupContext(); - - TurbineAggregatorProperties actual = getProperties(); - assertThat(actual.getClusterConfig()).containsOnly("default"); - } - - @Test - public void shouldLoadCustomProperties() { - addEnvironment(this.context, - "turbine.aggregator.clusterConfig=cluster1, cluster2, cluster3"); - setupContext(); - - TurbineAggregatorProperties actual = getProperties(); - assertThat(actual.getClusterConfig()).containsOnly("cluster1", "cluster2", - "cluster3"); - } - - private void setupContext() { - this.context.register(TestConfiguration.class); - this.context.refresh(); - } - - private TurbineAggregatorProperties getProperties() { - return this.context.getBean(TurbineAggregatorProperties.class); - } - - @Configuration - @EnableConfigurationProperties(TurbineAggregatorProperties.class) - static class TestConfiguration { - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/TurbineHttpTests.java b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/TurbineHttpTests.java deleted file mode 100644 index 77ea0e6e..00000000 --- a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/TurbineHttpTests.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.turbine; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * @author Spencer Gibb - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = TurbineHttpTests.TurbineHttpSampleApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class TurbineHttpTests { - - @EnableAutoConfiguration - @EnableTurbine - public static class TurbineHttpSampleApplication { - } - - @Test - public void contextLoads() { - } -} diff --git a/spring-cloud-netflix-zuul/pom.xml b/spring-cloud-netflix-zuul/pom.xml deleted file mode 100644 index fe81dbcc..00000000 --- a/spring-cloud-netflix-zuul/pom.xml +++ /dev/null @@ -1,127 +0,0 @@ - - - 4.0.0 - - spring-cloud-netflix - org.springframework.cloud - 2.0.0.BUILD-SNAPSHOT - .. - - - - spring-cloud-netflix-zuul - jar - Spring Cloud Netflix Zuul - Spring Cloud Netflix Zuul - - ${basedir}/.. - - - - - org.springframework.cloud - spring-cloud-netflix-core - - - com.netflix.hystrix - hystrix-core - true - - - com.netflix.ribbon - ribbon-loadbalancer - true - - - com.netflix.ribbon - ribbon-core - true - - - com.netflix.ribbon - ribbon-httpclient - true - - - org.springframework.boot - spring-boot-starter-actuator - true - - - org.springframework.boot - spring-boot-starter-web - true - - - org.springframework.boot - spring-boot-starter-security - true - - - org.springframework.cloud - spring-cloud-commons - true - - - org.springframework.cloud - spring-cloud-context - true - - - com.netflix.zuul - zuul-core - true - - - groovy-all - org.codehaus.groovy - - - mockito-all - org.mockito - - - - - org.springframework.cloud - spring-cloud-starter-netflix-ribbon - true - - - com.netflix.netflix-commons - netflix-commons-util - - - org.springframework.cloud - spring-cloud-starter-netflix-hystrix - - - org.springframework.retry - spring-retry - true - - - commons-configuration - commons-configuration - true - - - org.springframework.cloud - spring-cloud-test-support - test - - - org.springframework.boot - spring-boot-starter-test - test - - - com.squareup.okhttp3 - okhttp - test - - - - diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/EnableZuulProxy.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/EnableZuulProxy.java deleted file mode 100644 index 41327b2b..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/EnableZuulProxy.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; -import org.springframework.context.annotation.Import; - -/** - * Sets up a Zuul server endpoint and installs some reverse proxy filters in it, so it can - * forward requests to backend servers. The backends can be registered manually through - * configuration or via DiscoveryClient. - * - * @see EnableZuulServer for how to get a Zuul server without any proxying - * - * @author Spencer Gibb - * @author Dave Syer - * @author Biju Kunjummen - */ -@EnableCircuitBreaker -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Import(ZuulProxyMarkerConfiguration.class) -public @interface EnableZuulProxy { -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/EnableZuulServer.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/EnableZuulServer.java deleted file mode 100644 index 6491e2bc..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/EnableZuulServer.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.context.annotation.Import; - -/** - * Set up the application to act as a generic Zuul server without any built-in reverse - * proxy features. The routes into the Zuul server can be configured through - * {@link ZuulProperties} (by default there are none). - * - * @see EnableZuulProxy to see how to get reverse proxy out of the box - * - * @author Spencer Gibb - * @author Biju Kunjummen - */ -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Import(ZuulServerMarkerConfiguration.class) -public @interface EnableZuulServer { - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/FiltersEndpoint.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/FiltersEndpoint.java deleted file mode 100644 index 3cf22ffa..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/FiltersEndpoint.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.springframework.cloud.netflix.zuul; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; - -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.filters.FilterRegistry; - -/** - * Endpoint for listing Zuul filters. - * - * @author Daryl Robbins - * @author Gregor Zurowski - */ -@Endpoint(id = "filters") -public class FiltersEndpoint { - - private final FilterRegistry filterRegistry; - - public FiltersEndpoint(FilterRegistry filterRegistry) { - this.filterRegistry = filterRegistry; - } - - @ReadOperation - public Map>> invoke() { - // Map of filters by type - final Map>> filterMap = new TreeMap<>(); - - for (ZuulFilter filter : this.filterRegistry.getAllFilters()) { - // Ensure that we have a list to store filters of each type - if (!filterMap.containsKey(filter.filterType())) { - filterMap.put(filter.filterType(), new ArrayList<>()); - } - - final Map filterInfo = new LinkedHashMap<>(); - filterInfo.put("class", filter.getClass().getName()); - filterInfo.put("order", filter.filterOrder()); - filterInfo.put("disabled", filter.isFilterDisabled()); - filterInfo.put("static", filter.isStaticFilter()); - - filterMap.get(filter.filterType()).add(filterInfo); - } - - return filterMap; - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RibbonCommandFactoryConfiguration.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RibbonCommandFactoryConfiguration.java deleted file mode 100644 index b44f6f81..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RibbonCommandFactoryConfiguration.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2015-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.util.Collections; -import java.util.Set; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.AnyNestedCondition; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; -import org.springframework.cloud.netflix.zuul.filters.route.RestClientRibbonCommandFactory; -import org.springframework.cloud.netflix.zuul.filters.route.RibbonCommandFactory; -import org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFactory; -import org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommandFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Conditional; -import org.springframework.context.annotation.Configuration; - -/** - * @author Dave Syer - * - */ -public class RibbonCommandFactoryConfiguration { - - @Configuration - @ConditionalOnRibbonRestClient - protected static class RestClientRibbonConfiguration { - - @Autowired(required = false) - private Set zuulFallbackProviders = Collections.emptySet(); - - @Bean - @ConditionalOnMissingBean - public RibbonCommandFactory ribbonCommandFactory( - SpringClientFactory clientFactory, ZuulProperties zuulProperties) { - return new RestClientRibbonCommandFactory(clientFactory, zuulProperties, - zuulFallbackProviders); - } - } - - @Configuration - @ConditionalOnRibbonOkHttpClient - @ConditionalOnClass(name = "okhttp3.OkHttpClient") - protected static class OkHttpRibbonConfiguration { - - @Autowired(required = false) - private Set zuulFallbackProviders = Collections.emptySet(); - - @Bean - @ConditionalOnMissingBean - public RibbonCommandFactory ribbonCommandFactory( - SpringClientFactory clientFactory, ZuulProperties zuulProperties) { - return new OkHttpRibbonCommandFactory(clientFactory, zuulProperties, - zuulFallbackProviders); - } - } - - @Configuration - @ConditionalOnRibbonHttpClient - protected static class HttpClientRibbonConfiguration { - - @Autowired(required = false) - private Set zuulFallbackProviders = Collections.emptySet(); - - @Bean - @ConditionalOnMissingBean - public RibbonCommandFactory ribbonCommandFactory( - SpringClientFactory clientFactory, ZuulProperties zuulProperties) { - return new HttpClientRibbonCommandFactory(clientFactory, zuulProperties, zuulFallbackProviders); - } - } - - @Target({ ElementType.TYPE, ElementType.METHOD }) - @Retention(RetentionPolicy.RUNTIME) - @Documented - @Conditional(OnRibbonHttpClientCondition.class) - @interface ConditionalOnRibbonHttpClient { } - - private static class OnRibbonHttpClientCondition extends AnyNestedCondition { - public OnRibbonHttpClientCondition() { - super(ConfigurationPhase.PARSE_CONFIGURATION); - } - - @ConditionalOnProperty(name = "ribbon.httpclient.enabled", matchIfMissing = true) - static class RibbonProperty {} - } - - @Target({ ElementType.TYPE, ElementType.METHOD }) - @Retention(RetentionPolicy.RUNTIME) - @Documented - @Conditional(OnRibbonOkHttpClientCondition.class) - @interface ConditionalOnRibbonOkHttpClient { } - - private static class OnRibbonOkHttpClientCondition extends AnyNestedCondition { - public OnRibbonOkHttpClientCondition() { - super(ConfigurationPhase.PARSE_CONFIGURATION); - } - - @ConditionalOnProperty("ribbon.okhttp.enabled") - static class RibbonProperty {} - } - - @Target({ ElementType.TYPE, ElementType.METHOD }) - @Retention(RetentionPolicy.RUNTIME) - @Documented - @Conditional(OnRibbonRestClientCondition.class) - @interface ConditionalOnRibbonRestClient { } - - private static class OnRibbonRestClientCondition extends AnyNestedCondition { - public OnRibbonRestClientCondition() { - super(ConfigurationPhase.PARSE_CONFIGURATION); - } - - @ConditionalOnProperty("ribbon.restclient.enabled") - static class RibbonProperty {} - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RoutesEndpoint.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RoutesEndpoint.java deleted file mode 100644 index 70c70e9e..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RoutesEndpoint.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; -import org.springframework.boot.actuate.endpoint.annotation.Selector; -import org.springframework.boot.actuate.endpoint.annotation.WriteOperation; -import org.springframework.cloud.netflix.zuul.filters.Route; -import org.springframework.cloud.netflix.zuul.filters.RouteLocator; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.context.ApplicationEventPublisherAware; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -/** - * Endpoint to display the zuul proxy routes - * - * @author Spencer Gibb - * @author Dave Syer - * @author Ryan Baxter - * @author Gregor Zurowski - */ -@Endpoint(id = RoutesEndpoint.ID) -public class RoutesEndpoint implements ApplicationEventPublisherAware { - - static final String ID = "routes"; - static final String FORMAT_DETAILS = "details"; - - private RouteLocator routes; - - private ApplicationEventPublisher publisher; - - public RoutesEndpoint(RouteLocator routes) { - this.routes = routes; - } - - @Override - public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { - this.publisher = publisher; - } - - @ReadOperation - public Map invoke() { - Map map = new LinkedHashMap<>(); - for (Route route : this.routes.getRoutes()) { - map.put(route.getFullPath(), route.getLocation()); - } - return map; - } - - Map invokeRouteDetails() { - Map map = new LinkedHashMap<>(); - for (Route route : this.routes.getRoutes()) { - map.put(route.getFullPath(), new RouteDetails(route)); - } - return map; - } - - @WriteOperation - public Object reset() { - this.publisher.publishEvent(new RoutesRefreshedEvent(this.routes)); - return invoke(); - } - - /** - * Expose Zuul {@link Route} information with details. - */ - @ReadOperation - public Object invokeRouteDetails(@Selector String format) { - if (FORMAT_DETAILS.equalsIgnoreCase(format)) { - return invokeRouteDetails(); - } else { - return invoke(); - } - } - - /** - * Container for exposing Zuul {@link Route} details as JSON. - */ - @JsonPropertyOrder({ "id", "fullPath", "location" }) - @JsonInclude(JsonInclude.Include.NON_EMPTY) - public static class RouteDetails { - - private String id; - - private String fullPath; - - private String path; - - private String location; - - private String prefix; - - private Boolean retryable; - - private Set sensitiveHeaders; - - private boolean customSensitiveHeaders; - - private boolean prefixStripped; - - public RouteDetails() { - } - - RouteDetails(final Route route) { - this.id = route.getId(); - this.fullPath = route.getFullPath(); - this.path = route.getPath(); - this.location = route.getLocation(); - this.prefix = route.getPrefix(); - this.retryable = route.getRetryable(); - this.sensitiveHeaders = route.getSensitiveHeaders(); - this.customSensitiveHeaders = route.isCustomSensitiveHeaders(); - this.prefixStripped = route.isPrefixStripped(); - } - - public String getId() { - return id; - } - - public String getFullPath() { - return fullPath; - } - - public String getPath() { - return path; - } - - public String getLocation() { - return location; - } - - public String getPrefix() { - return prefix; - } - - public Boolean getRetryable() { - return retryable; - } - - public Set getSensitiveHeaders() { - return sensitiveHeaders; - } - - public boolean isCustomSensitiveHeaders() { - return customSensitiveHeaders; - } - - public boolean isPrefixStripped() { - return prefixStripped; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - RouteDetails that = (RouteDetails) o; - return Objects.equals(id, that.id) && - Objects.equals(fullPath, that.fullPath) && - Objects.equals(path, that.path) && - Objects.equals(location, that.location) && - Objects.equals(prefix, that.prefix) && - Objects.equals(retryable, that.retryable) && - Objects.equals(sensitiveHeaders, that.sensitiveHeaders) && - customSensitiveHeaders == that.customSensitiveHeaders && - prefixStripped == that.prefixStripped; - } - - @Override - public int hashCode() { - return Objects.hash(id, fullPath, path, location, prefix, retryable, - sensitiveHeaders, customSensitiveHeaders, prefixStripped); - } - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RoutesRefreshedEvent.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RoutesRefreshedEvent.java deleted file mode 100644 index adac90e6..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RoutesRefreshedEvent.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul; - -import org.springframework.cloud.netflix.zuul.filters.RouteLocator; -import org.springframework.context.ApplicationEvent; - -/** - * @author Dave Syer - */ -@SuppressWarnings("serial") -public class RoutesRefreshedEvent extends ApplicationEvent { - - private RouteLocator locator; - - public RoutesRefreshedEvent(RouteLocator locator) { - super(locator); - this.locator = locator; - } - - public RouteLocator getLocator() { - return this.locator; - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulFilterInitializer.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulFilterInitializer.java deleted file mode 100644 index 166eecc7..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulFilterInitializer.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul; - -import java.lang.reflect.Field; -import java.util.Map; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.util.ReflectionUtils; - -import com.netflix.zuul.FilterLoader; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.filters.FilterRegistry; -import com.netflix.zuul.monitoring.CounterFactory; -import com.netflix.zuul.monitoring.TracerFactory; - -/** - * Initializes various Zuul components including {@link ZuulFilter}. - * - * @author Spencer Gibb - * - */ -public class ZuulFilterInitializer { - - private static final Log log = LogFactory.getLog(ZuulFilterInitializer.class); - - private final Map filters; - private final CounterFactory counterFactory; - private final TracerFactory tracerFactory; - private final FilterLoader filterLoader; - private final FilterRegistry filterRegistry; - - public ZuulFilterInitializer(Map filters, - CounterFactory counterFactory, - TracerFactory tracerFactory, - FilterLoader filterLoader, - FilterRegistry filterRegistry) { - this.filters = filters; - this.counterFactory = counterFactory; - this.tracerFactory = tracerFactory; - this.filterLoader = filterLoader; - this.filterRegistry = filterRegistry; - } - - @PostConstruct - public void contextInitialized() { - log.info("Starting filter initializer"); - - TracerFactory.initialize(tracerFactory); - CounterFactory.initialize(counterFactory); - - for (Map.Entry entry : this.filters.entrySet()) { - filterRegistry.put(entry.getKey(), entry.getValue()); - } - } - - @PreDestroy - public void contextDestroyed() { - log.info("Stopping filter initializer"); - for (Map.Entry entry : this.filters.entrySet()) { - filterRegistry.remove(entry.getKey()); - } - clearLoaderCache(); - - TracerFactory.initialize(null); - CounterFactory.initialize(null); - } - - private void clearLoaderCache() { - Field field = ReflectionUtils.findField(FilterLoader.class, "hashFiltersByType"); - ReflectionUtils.makeAccessible(field); - @SuppressWarnings("rawtypes") - Map cache = (Map) ReflectionUtils.getField(field, filterLoader); - cache.clear(); - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulProxyAutoConfiguration.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulProxyAutoConfiguration.java deleted file mode 100644 index 042e2755..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulProxyAutoConfiguration.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul; - -import java.util.Collections; -import java.util.List; - -import org.apache.http.impl.client.CloseableHttpClient; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; -import org.springframework.boot.actuate.health.Health; -import org.springframework.boot.actuate.web.trace.HttpTraceRepository; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; -import org.springframework.cloud.client.actuator.HasFeatures; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.client.discovery.event.HeartbeatEvent; -import org.springframework.cloud.client.discovery.event.HeartbeatMonitor; -import org.springframework.cloud.client.discovery.event.InstanceRegisteredEvent; -import org.springframework.cloud.client.discovery.event.ParentHeartbeatEvent; -import org.springframework.cloud.client.serviceregistry.Registration; -import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory; -import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory; -import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; -import org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer; -import org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelper; -import org.springframework.cloud.netflix.zuul.filters.RouteLocator; -import org.springframework.cloud.netflix.zuul.filters.TraceProxyRequestHelper; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; -import org.springframework.cloud.netflix.zuul.filters.discovery.ServiceRouteMapper; -import org.springframework.cloud.netflix.zuul.filters.discovery.SimpleServiceRouteMapper; -import org.springframework.cloud.netflix.zuul.filters.pre.PreDecorationFilter; -import org.springframework.cloud.netflix.zuul.filters.route.RibbonCommandFactory; -import org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter; -import org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter; -import org.springframework.cloud.netflix.zuul.web.ZuulHandlerMapping; -import org.springframework.context.ApplicationEvent; -import org.springframework.context.ApplicationListener; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -import com.netflix.zuul.filters.FilterRegistry; - -/** - * @author Spencer Gibb - * @author Dave Syer - * @author Biju Kunjummen - */ -@Configuration -@Import({ RibbonCommandFactoryConfiguration.RestClientRibbonConfiguration.class, - RibbonCommandFactoryConfiguration.OkHttpRibbonConfiguration.class, - RibbonCommandFactoryConfiguration.HttpClientRibbonConfiguration.class, - HttpClientConfiguration.class }) -@ConditionalOnBean(ZuulProxyMarkerConfiguration.Marker.class) -public class ZuulProxyAutoConfiguration extends ZuulServerAutoConfiguration { - - @SuppressWarnings("rawtypes") - @Autowired(required = false) - private List requestCustomizers = Collections.emptyList(); - - @Autowired(required = false) - private Registration registration; - - @Autowired - private DiscoveryClient discovery; - - @Autowired - private ServiceRouteMapper serviceRouteMapper; - - @Override - public HasFeatures zuulFeature() { - return HasFeatures.namedFeature("Zuul (Discovery)", - ZuulProxyAutoConfiguration.class); - } - - @Bean - @ConditionalOnMissingBean(DiscoveryClientRouteLocator.class) - public DiscoveryClientRouteLocator discoveryRouteLocator() { - return new DiscoveryClientRouteLocator(this.server.getServlet().getServletPrefix(), this.discovery, this.zuulProperties, - this.serviceRouteMapper, this.registration); - } - - // pre filters - @Bean - public PreDecorationFilter preDecorationFilter(RouteLocator routeLocator, ProxyRequestHelper proxyRequestHelper) { - return new PreDecorationFilter(routeLocator, this.server.getServlet().getServletPrefix(), this.zuulProperties, - proxyRequestHelper); - } - - // route filters - @Bean - public RibbonRoutingFilter ribbonRoutingFilter(ProxyRequestHelper helper, - RibbonCommandFactory ribbonCommandFactory) { - RibbonRoutingFilter filter = new RibbonRoutingFilter(helper, ribbonCommandFactory, - this.requestCustomizers); - return filter; - } - - @Bean - @ConditionalOnMissingBean({SimpleHostRoutingFilter.class, CloseableHttpClient.class}) - public SimpleHostRoutingFilter simpleHostRoutingFilter(ProxyRequestHelper helper, - ZuulProperties zuulProperties, - ApacheHttpClientConnectionManagerFactory connectionManagerFactory, - ApacheHttpClientFactory httpClientFactory) { - return new SimpleHostRoutingFilter(helper, zuulProperties, - connectionManagerFactory, httpClientFactory); - } - - @Bean - @ConditionalOnMissingBean({SimpleHostRoutingFilter.class}) - public SimpleHostRoutingFilter simpleHostRoutingFilter2(ProxyRequestHelper helper, - ZuulProperties zuulProperties, - CloseableHttpClient httpClient) { - return new SimpleHostRoutingFilter(helper, zuulProperties, - httpClient); - } - - @Bean - public ApplicationListener zuulDiscoveryRefreshRoutesListener() { - return new ZuulDiscoveryRefreshListener(); - } - - @Bean - @ConditionalOnMissingBean(ServiceRouteMapper.class) - public ServiceRouteMapper serviceRouteMapper() { - return new SimpleServiceRouteMapper(); - } - - @Configuration - @ConditionalOnMissingClass("org.springframework.boot.actuate.endpoint.Endpoint") - protected static class NoActuatorConfiguration { - - @Bean - public ProxyRequestHelper proxyRequestHelper(ZuulProperties zuulProperties) { - ProxyRequestHelper helper = new ProxyRequestHelper(); - helper.setIgnoredHeaders(zuulProperties.getIgnoredHeaders()); - helper.setTraceRequestBody(zuulProperties.isTraceRequestBody()); - return helper; - } - - } - - @Configuration - @ConditionalOnClass(Health.class) - protected static class EndpointConfiguration { - - @Autowired(required = false) - private HttpTraceRepository traces; - - @Bean - @ConditionalOnEnabledEndpoint - public RoutesEndpoint routesEndpoint(RouteLocator routeLocator) { - return new RoutesEndpoint(routeLocator); - } - - @ConditionalOnEnabledEndpoint - @Bean - public FiltersEndpoint filtersEndpoint() { - FilterRegistry filterRegistry = FilterRegistry.instance(); - return new FiltersEndpoint(filterRegistry); - } - - @Bean - public ProxyRequestHelper proxyRequestHelper(ZuulProperties zuulProperties) { - TraceProxyRequestHelper helper = new TraceProxyRequestHelper(); - if (this.traces != null) { - helper.setTraces(this.traces); - } - helper.setIgnoredHeaders(zuulProperties.getIgnoredHeaders()); - helper.setTraceRequestBody(zuulProperties.isTraceRequestBody()); - return helper; - } - } - - private static class ZuulDiscoveryRefreshListener - implements ApplicationListener { - - private HeartbeatMonitor monitor = new HeartbeatMonitor(); - - @Autowired - private ZuulHandlerMapping zuulHandlerMapping; - - @Override - public void onApplicationEvent(ApplicationEvent event) { - if (event instanceof InstanceRegisteredEvent) { - reset(); - } - else if (event instanceof ParentHeartbeatEvent) { - ParentHeartbeatEvent e = (ParentHeartbeatEvent) event; - resetIfNeeded(e.getValue()); - } - else if (event instanceof HeartbeatEvent) { - HeartbeatEvent e = (HeartbeatEvent) event; - resetIfNeeded(e.getValue()); - } - - } - - private void resetIfNeeded(Object value) { - if (this.monitor.update(value)) { - reset(); - } - } - - private void reset() { - this.zuulHandlerMapping.setDirty(true); - } - - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulProxyMarkerConfiguration.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulProxyMarkerConfiguration.java deleted file mode 100644 index 451442bf..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulProxyMarkerConfiguration.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Responsible for adding in a marker bean to trigger activation of - * {@link ZuulProxyAutoConfiguration} - * - * @author Biju Kunjummen - */ - -@Configuration -public class ZuulProxyMarkerConfiguration { - @Bean - public Marker zuulProxyMarkerBean() { - return new Marker(); - } - - class Marker { - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulRouteApplicationContextInitializer.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulRouteApplicationContextInitializer.java deleted file mode 100644 index 5d11d449..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulRouteApplicationContextInitializer.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul; - -import org.springframework.cloud.netflix.ribbon.RibbonApplicationContextInitializer; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -/** - * Responsible for taking in the list of registered serviceid's (Ribbon client names) - * and creating the Spring {@link org.springframework.context.ApplicationContext} on - * start-up - * - * @author Biju Kunjummen - */ - -public class ZuulRouteApplicationContextInitializer extends - RibbonApplicationContextInitializer { - public ZuulRouteApplicationContextInitializer(SpringClientFactory springClientFactory, - ZuulProperties zuulProperties) { - super(springClientFactory, getServiceIdsFromZuulProps(zuulProperties)); - } - - private static List getServiceIdsFromZuulProps(ZuulProperties zuulProperties) { - Map zuulRoutes = zuulProperties.getRoutes(); - Collection registeredRoutes = zuulRoutes.values(); - List serviceIds = new ArrayList<>(); - if (registeredRoutes != null) { - for (ZuulProperties.ZuulRoute route: registeredRoutes) { - String serviceId = route.getServiceId(); - if (serviceId != null) { - serviceIds.add(serviceId); - } - } - } - return serviceIds; - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServerAutoConfiguration.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServerAutoConfiguration.java deleted file mode 100644 index 20939a07..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServerAutoConfiguration.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import java.util.Collection; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.web.ServerProperties; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.web.servlet.ServletRegistrationBean; -import org.springframework.boot.web.servlet.error.ErrorController; -import org.springframework.cloud.client.actuator.HasFeatures; -import org.springframework.cloud.client.discovery.event.HeartbeatEvent; -import org.springframework.cloud.client.discovery.event.HeartbeatMonitor; -import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.zuul.filters.CompositeRouteLocator; -import org.springframework.cloud.netflix.zuul.filters.RouteLocator; -import org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilter; -import org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter; -import org.springframework.cloud.netflix.zuul.filters.pre.DebugFilter; -import org.springframework.cloud.netflix.zuul.filters.pre.FormBodyWrapperFilter; -import org.springframework.cloud.netflix.zuul.filters.pre.Servlet30WrapperFilter; -import org.springframework.cloud.netflix.zuul.filters.pre.ServletDetectionFilter; -import org.springframework.cloud.netflix.zuul.filters.route.SendForwardFilter; -import org.springframework.cloud.netflix.zuul.metrics.DefaultCounterFactory; -import org.springframework.cloud.netflix.zuul.metrics.EmptyCounterFactory; -import org.springframework.cloud.netflix.zuul.metrics.EmptyTracerFactory; -import org.springframework.cloud.netflix.zuul.web.ZuulController; -import org.springframework.cloud.netflix.zuul.web.ZuulHandlerMapping; -import org.springframework.context.ApplicationEvent; -import org.springframework.context.ApplicationListener; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.context.event.ContextRefreshedEvent; - -import com.netflix.zuul.FilterLoader; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.filters.FilterRegistry; -import com.netflix.zuul.http.ZuulServlet; -import com.netflix.zuul.monitoring.CounterFactory; -import com.netflix.zuul.monitoring.TracerFactory; - -import io.micrometer.core.instrument.MeterRegistry; - -/** - * @author Spencer Gibb - * @author Dave Syer - * @author Biju Kunjummen - */ -@Configuration -@EnableConfigurationProperties({ ZuulProperties.class }) -@ConditionalOnClass(ZuulServlet.class) -@ConditionalOnBean(ZuulServerMarkerConfiguration.Marker.class) -// Make sure to get the ServerProperties from the same place as a normal web app would -// FIXME @Import(ServerPropertiesAutoConfiguration.class) -public class ZuulServerAutoConfiguration { - - @Autowired - protected ZuulProperties zuulProperties; - - @Autowired - protected ServerProperties server; - - @Autowired(required = false) - private ErrorController errorController; - - @Bean - public HasFeatures zuulFeature() { - return HasFeatures.namedFeature("Zuul (Simple)", ZuulServerAutoConfiguration.class); - } - - @Bean - @Primary - public CompositeRouteLocator primaryRouteLocator( - Collection routeLocators) { - return new CompositeRouteLocator(routeLocators); - } - - @Bean - @ConditionalOnMissingBean(SimpleRouteLocator.class) - public SimpleRouteLocator simpleRouteLocator() { - return new SimpleRouteLocator(this.server.getServlet().getServletPrefix(), - this.zuulProperties); - } - - @Bean - public ZuulController zuulController() { - return new ZuulController(); - } - - @Bean - public ZuulHandlerMapping zuulHandlerMapping(RouteLocator routes) { - ZuulHandlerMapping mapping = new ZuulHandlerMapping(routes, zuulController()); - mapping.setErrorController(this.errorController); - return mapping; - } - - @Bean - public ApplicationListener zuulRefreshRoutesListener() { - return new ZuulRefreshListener(); - } - - @Bean - @ConditionalOnMissingBean(name = "zuulServlet") - public ServletRegistrationBean zuulServlet() { - ServletRegistrationBean servlet = new ServletRegistrationBean<>(new ZuulServlet(), - this.zuulProperties.getServletPattern()); - // The whole point of exposing this servlet is to provide a route that doesn't - // buffer requests. - servlet.addInitParameter("buffer-requests", "false"); - return servlet; - } - - // pre filters - - @Bean - public ServletDetectionFilter servletDetectionFilter() { - return new ServletDetectionFilter(); - } - - @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(ZuulProperties properties) { - return new SendResponseFilter(zuulProperties); - } - - @Bean - public SendErrorFilter sendErrorFilter() { - return new SendErrorFilter(); - } - - @Bean - public SendForwardFilter sendForwardFilter() { - return new SendForwardFilter(); - } - - @Bean - @ConditionalOnProperty(value = "zuul.ribbon.eager-load.enabled") - public ZuulRouteApplicationContextInitializer zuulRoutesApplicationContextInitiazer( - SpringClientFactory springClientFactory) { - return new ZuulRouteApplicationContextInitializer(springClientFactory, - zuulProperties); - } - - @Configuration - protected static class ZuulFilterConfiguration { - - @Autowired - private Map filters; - - @Bean - public ZuulFilterInitializer zuulFilterInitializer( - CounterFactory counterFactory, TracerFactory tracerFactory) { - FilterLoader filterLoader = FilterLoader.getInstance(); - FilterRegistry filterRegistry = FilterRegistry.instance(); - return new ZuulFilterInitializer(this.filters, counterFactory, tracerFactory, filterLoader, filterRegistry); - } - - } - - @Configuration - @ConditionalOnClass(MeterRegistry.class) - protected static class ZuulCounterFactoryConfiguration { - - @Bean - @ConditionalOnBean(MeterRegistry.class) - public CounterFactory counterFactory(MeterRegistry meterRegistry) { - return new DefaultCounterFactory(meterRegistry); - } - } - - @Configuration - protected static class ZuulMetricsConfiguration { - - @Bean - @ConditionalOnMissingBean(CounterFactory.class) - public CounterFactory counterFactory() { - return new EmptyCounterFactory(); - } - - @ConditionalOnMissingBean(TracerFactory.class) - @Bean - public TracerFactory tracerFactory() { - return new EmptyTracerFactory(); - } - - } - - private static class ZuulRefreshListener - implements ApplicationListener { - - @Autowired - private ZuulHandlerMapping zuulHandlerMapping; - - private HeartbeatMonitor heartbeatMonitor = new HeartbeatMonitor(); - - @Override - public void onApplicationEvent(ApplicationEvent event) { - if (event instanceof ContextRefreshedEvent - || event instanceof RefreshScopeRefreshedEvent - || event instanceof RoutesRefreshedEvent) { - this.zuulHandlerMapping.setDirty(true); - } - else if (event instanceof HeartbeatEvent) { - if (this.heartbeatMonitor.update(((HeartbeatEvent) event).getValue())) { - this.zuulHandlerMapping.setDirty(true); - } - } - } - - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServerMarkerConfiguration.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServerMarkerConfiguration.java deleted file mode 100644 index 93947877..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServerMarkerConfiguration.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Responsible for adding in a marker bean to trigger activation of - * {@link ZuulServerAutoConfiguration} - * - * @author Biju Kunjummen - */ - -@Configuration -public class ZuulServerMarkerConfiguration { - @Bean - public Marker zuulServerMarkerBean() { - return new Marker(); - } - - class Marker { - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/CompositeRouteLocator.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/CompositeRouteLocator.java deleted file mode 100644 index a106d97a..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/CompositeRouteLocator.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.cloud.netflix.zuul.filters; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.springframework.core.annotation.AnnotationAwareOrderComparator; -import org.springframework.util.Assert; - -/** - * RouteLocator that composes multiple RouteLocators. - * - * @author Johannes Edmeier - * - */ -public class CompositeRouteLocator implements RefreshableRouteLocator { - private final Collection routeLocators; - private ArrayList rl; - - public CompositeRouteLocator(Collection routeLocators) { - Assert.notNull(routeLocators, "'routeLocators' must not be null"); - rl = new ArrayList<>(routeLocators); - AnnotationAwareOrderComparator.sort(rl); - this.routeLocators = rl; - } - - @Override - public Collection getIgnoredPaths() { - List ignoredPaths = new ArrayList<>(); - for (RouteLocator locator : routeLocators) { - ignoredPaths.addAll(locator.getIgnoredPaths()); - } - return ignoredPaths; - } - - @Override - public List getRoutes() { - List route = new ArrayList<>(); - for (RouteLocator locator : routeLocators) { - route.addAll(locator.getRoutes()); - } - return route; - } - - @Override - public Route getMatchingRoute(String path) { - for (RouteLocator locator : routeLocators) { - Route route = locator.getMatchingRoute(path); - if (route != null) { - return route; - } - } - return null; - } - - @Override - public void refresh() { - for (RouteLocator locator : routeLocators) { - if (locator instanceof RefreshableRouteLocator) { - ((RefreshableRouteLocator) locator).refresh(); - } - } - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/ProxyRequestHelper.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/ProxyRequestHelper.java deleted file mode 100644 index 3f53f437..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/ProxyRequestHelper.java +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Collection; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.netflix.zuul.util.RequestUtils; -import org.springframework.http.HttpHeaders; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.util.UriTemplate; -import org.springframework.web.util.UriUtils; -import org.springframework.web.util.WebUtils; - -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.util.HTTPRequestUtils; - -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.REQUEST_URI_KEY; -import static org.springframework.http.HttpHeaders.CONTENT_ENCODING; -import static org.springframework.http.HttpHeaders.CONTENT_LENGTH; - -/** - * @author Dave Syer - * @author Marcos Barbero - * @author Spencer Gibb - */ -public class ProxyRequestHelper { - - private static final Log log = LogFactory.getLog(ProxyRequestHelper.class); - - /** - * Zuul context key for a collection of ignored headers for the current request. - * Pre-filters can set this up as a set of lowercase strings. - */ - public static final String IGNORED_HEADERS = "ignoredHeaders"; - - private Set ignoredHeaders = new LinkedHashSet<>(); - - private Set sensitiveHeaders = new LinkedHashSet<>(); - - private Set whitelistHosts = new LinkedHashSet<>(); - - private boolean traceRequestBody = true; - - public void setWhitelistHosts(Set whitelistHosts) { - this.whitelistHosts.addAll(whitelistHosts); - } - - public void setSensitiveHeaders(Set sensitiveHeaders) { - this.sensitiveHeaders.addAll(sensitiveHeaders); - } - - public void setIgnoredHeaders(Set ignoredHeaders) { - this.ignoredHeaders.addAll(ignoredHeaders); - } - - public void setTraceRequestBody(boolean traceRequestBody) { - this.traceRequestBody = traceRequestBody; - } - - public String buildZuulRequestURI(HttpServletRequest request) { - RequestContext context = RequestContext.getCurrentContext(); - String uri = request.getRequestURI(); - String contextURI = (String) context.get(REQUEST_URI_KEY); - if (contextURI != null) { - try { - uri = UriUtils.encodePath(contextURI, characterEncoding(request)); - } - catch (Exception e) { - log.debug( - "unable to encode uri path from context, falling back to uri from request", - e); - } - } - return uri; - } - - private String characterEncoding(HttpServletRequest request) { - return request.getCharacterEncoding() != null ? request.getCharacterEncoding() - : WebUtils.DEFAULT_CHARACTER_ENCODING; - } - - public MultiValueMap buildZuulRequestQueryParams( - HttpServletRequest request) { - Map> map = HTTPRequestUtils.getInstance().getQueryParams(); - MultiValueMap params = new LinkedMultiValueMap<>(); - if (map == null) { - return params; - } - for (String key : map.keySet()) { - for (String value : map.get(key)) { - params.add(key, value); - } - } - return params; - } - - public MultiValueMap buildZuulRequestHeaders( - HttpServletRequest request) { - RequestContext context = RequestContext.getCurrentContext(); - MultiValueMap headers = new HttpHeaders(); - Enumeration headerNames = request.getHeaderNames(); - if (headerNames != null) { - while (headerNames.hasMoreElements()) { - String name = headerNames.nextElement(); - if (isIncludedHeader(name)) { - Enumeration values = request.getHeaders(name); - while (values.hasMoreElements()) { - String value = values.nextElement(); - headers.add(name, value); - } - } - } - } - Map zuulRequestHeaders = context.getZuulRequestHeaders(); - for (String header : zuulRequestHeaders.keySet()) { - headers.set(header, zuulRequestHeaders.get(header)); - } - headers.set(HttpHeaders.ACCEPT_ENCODING, "gzip"); - return headers; - } - - public void setResponse(int status, InputStream entity, - MultiValueMap headers) throws IOException { - RequestContext context = RequestContext.getCurrentContext(); - context.setResponseStatusCode(status); - if (entity != null) { - context.setResponseDataStream(entity); - } - - boolean isOriginResponseGzipped = false; - for (Entry> header : headers.entrySet()) { - String name = header.getKey(); - for (String value : header.getValue()) { - if (name.equalsIgnoreCase(HttpHeaders.CONTENT_ENCODING) - && HTTPRequestUtils.getInstance().isGzipped(value)) { - isOriginResponseGzipped = true; - } - if (name.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) { - context.setOriginContentLength(value); - } - if (isIncludedHeader(name)) { - context.addZuulResponseHeader(name, value); - } - } - } - context.setResponseGZipped(isOriginResponseGzipped); - } - - public void addIgnoredHeaders(String... names) { - RequestContext ctx = RequestContext.getCurrentContext(); - if (!ctx.containsKey(IGNORED_HEADERS)) { - ctx.set(IGNORED_HEADERS, new HashSet()); - } - @SuppressWarnings("unchecked") - Set set = (Set) ctx.get(IGNORED_HEADERS); - for (String name : this.ignoredHeaders) { - set.add(name.toLowerCase()); - } - for (String name : names) { - set.add(name.toLowerCase()); - } - } - - public boolean isIncludedHeader(String headerName) { - String name = headerName.toLowerCase(); - RequestContext ctx = RequestContext.getCurrentContext(); - if (ctx.containsKey(IGNORED_HEADERS)) { - Object object = ctx.get(IGNORED_HEADERS); - if (object instanceof Collection && ((Collection) object).contains(name)) { - return false; - } - } - switch (name) { - case "host": - case "connection": - case "content-length": - case "content-encoding": - case "server": - case "transfer-encoding": - case "x-application-context": - return false; - default: - return true; - } - } - - public Map debug(String verb, String uri, - MultiValueMap headers, MultiValueMap params, - InputStream requestEntity) throws IOException { - Map info = new LinkedHashMap<>(); - return info; - } - - protected boolean shouldDebugBody(RequestContext ctx) { - HttpServletRequest request = ctx.getRequest(); - if (!this.traceRequestBody || ctx.isChunkedRequestBody() - || RequestUtils.isZuulServletRequest()) { - return false; - } - if (request == null || request.getContentType() == null) { - return true; - } - return !request.getContentType().toLowerCase().contains("multipart"); - } - - public void appendDebug(Map info, int status, - MultiValueMap headers) { - } - - /** - * Get url encoded query string. Pay special attention to single parameters with no values - * and parameter names with colon (:) from use of UriTemplate. - * @param params Un-encoded request parameters - * @return - */ - public String getQueryString(MultiValueMap params) { - if (params.isEmpty()) { - return ""; - } - StringBuilder query = new StringBuilder(); - Map singles = new HashMap<>(); - for (String param : params.keySet()) { - int i = 0; - for (String value : params.get(param)) { - query.append("&"); - query.append(param); - if (!"".equals(value)) { // don't add =, if original is ?wsdl, output is not ?wsdl= - String key = param; - // if form feed is already part of param name double - // since form feed is used as the colon replacement below - if (key.contains("\f")) { - key = (key.replaceAll("\f", "\f\f")); - } - // colon is special to UriTemplate - if (key.contains(":")) { - key = key.replaceAll(":", "\f"); - } - key = key + i; - singles.put(key, value); - query.append("={"); - query.append(key); - query.append("}"); - } - i++; - } - } - - UriTemplate template = new UriTemplate("?" + query.toString().substring(1)); - return template.expand(singles).toString(); - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/RefreshableRouteLocator.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/RefreshableRouteLocator.java deleted file mode 100644 index 905c8489..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/RefreshableRouteLocator.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters; - -/** - * Interface for a route locator that can be refreshed if routes change. - * - * @author Dave Syer - */ -public interface RefreshableRouteLocator extends RouteLocator { - - void refresh(); - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/Route.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/Route.java deleted file mode 100644 index 2c327ef3..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/Route.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters; - -import java.util.LinkedHashSet; -import java.util.Objects; -import java.util.Set; - -import org.springframework.util.StringUtils; - -public class Route { - - public Route(String id, String path, String location, String prefix, - Boolean retryable, Set ignoredHeaders) { - this.id = id; - this.prefix = StringUtils.hasText(prefix) ? prefix : ""; - this.path = path; - this.fullPath = prefix + path; - this.location = location; - this.retryable = retryable; - this.sensitiveHeaders = new LinkedHashSet<>(); - if (ignoredHeaders != null) { - this.customSensitiveHeaders = true; - for (String header : ignoredHeaders) { - this.sensitiveHeaders.add(header.toLowerCase()); - } - } - } - - public Route(String id, String path, String location, String prefix, - Boolean retryable, Set ignoredHeaders, boolean prefixStripped) { - this(id, path, location, prefix, retryable, ignoredHeaders); - this.prefixStripped = prefixStripped; - } - - private String id; - - private String fullPath; - - private String path; - - private String location; - - private String prefix; - - private Boolean retryable; - - private Set sensitiveHeaders = new LinkedHashSet<>(); - - private boolean customSensitiveHeaders; - - private boolean prefixStripped = true; - - public boolean isCustomSensitiveHeaders() { - return this.customSensitiveHeaders; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getFullPath() { - return fullPath; - } - - public void setFullPath(String fullPath) { - this.fullPath = fullPath; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } - - public String getPrefix() { - return prefix; - } - - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - public Boolean getRetryable() { - return retryable; - } - - public void setRetryable(Boolean retryable) { - this.retryable = retryable; - } - - public Set getSensitiveHeaders() { - return sensitiveHeaders; - } - - public void setSensitiveHeaders(Set sensitiveHeaders) { - this.sensitiveHeaders = sensitiveHeaders; - } - - public void setCustomSensitiveHeaders(boolean customSensitiveHeaders) { - this.customSensitiveHeaders = customSensitiveHeaders; - } - - public boolean isPrefixStripped() { - return prefixStripped; - } - - public void setPrefixStripped(boolean prefixStripped) { - this.prefixStripped = prefixStripped; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Route that = (Route) o; - return customSensitiveHeaders == that.customSensitiveHeaders && - prefixStripped == that.prefixStripped && - Objects.equals(id, that.id) && - Objects.equals(fullPath, that.fullPath) && - Objects.equals(path, that.path) && - Objects.equals(location, that.location) && - Objects.equals(prefix, that.prefix) && - Objects.equals(retryable, that.retryable) && - Objects.equals(sensitiveHeaders, that.sensitiveHeaders); - } - - @Override - public int hashCode() { - return Objects.hash(id, fullPath, path, location, prefix, retryable, - sensitiveHeaders, customSensitiveHeaders, prefixStripped); - } - - @Override - public String toString() { - return new StringBuilder("Route{") - .append("id='").append(id).append("', ") - .append("fullPath='").append(fullPath).append("', ") - .append("path='").append(path).append("', ") - .append("location='").append(location).append("', ") - .append("prefix='").append(prefix).append("', ") - .append("retryable=").append(retryable).append(", ") - .append("sensitiveHeaders=").append(sensitiveHeaders).append(", ") - .append("customSensitiveHeaders=").append(customSensitiveHeaders).append(", ") - .append("prefixStripped=").append(prefixStripped) - .append("}").toString(); - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/RouteLocator.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/RouteLocator.java deleted file mode 100644 index 7c7e3857..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/RouteLocator.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters; - -import java.util.Collection; -import java.util.List; - -/** - * @author Dave Syer - */ -public interface RouteLocator { - - /** - * Ignored route paths (or patterns), if any. - */ - Collection getIgnoredPaths(); - - /** - * A map of route path (pattern) to location (e.g. service id or URL). - */ - List getRoutes(); - - /** - * Maps a path to an actual route with full metadata. - */ - Route getMatchingRoute(String path); - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/SimpleRouteLocator.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/SimpleRouteLocator.java deleted file mode 100644 index 35490ff8..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/SimpleRouteLocator.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.atomic.AtomicReference; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute; -import org.springframework.cloud.netflix.zuul.util.RequestUtils; -import org.springframework.core.Ordered; -import org.springframework.util.AntPathMatcher; -import org.springframework.util.PathMatcher; -import org.springframework.util.StringUtils; - -/** - * Simple {@link RouteLocator} based on configuration data held in {@link ZuulProperties}. - * - * @author Dave Syer - */ -public class SimpleRouteLocator implements RouteLocator, Ordered { - - private static final Log log = LogFactory.getLog(SimpleRouteLocator.class); - - private static final int DEFAULT_ORDER = 0; - - private ZuulProperties properties; - - private PathMatcher pathMatcher = new AntPathMatcher(); - - private String dispatcherServletPath = "/"; - private String zuulServletPath; - - private AtomicReference> routes = new AtomicReference<>(); - private int order = DEFAULT_ORDER; - - public SimpleRouteLocator(String servletPath, ZuulProperties properties) { - this.properties = properties; - if (StringUtils.hasText(servletPath)) { - this.dispatcherServletPath = servletPath; - } - - this.zuulServletPath = properties.getServletPath(); - } - - @Override - public List getRoutes() { - List values = new ArrayList<>(); - for (Entry entry : getRoutesMap().entrySet()) { - ZuulRoute route = entry.getValue(); - String path = route.getPath(); - values.add(getRoute(route, path)); - } - return values; - } - - @Override - public Collection getIgnoredPaths() { - return this.properties.getIgnoredPatterns(); - } - - @Override - public Route getMatchingRoute(final String path) { - - return getSimpleMatchingRoute(path); - - } - - protected Map getRoutesMap() { - if (this.routes.get() == null) { - this.routes.set(locateRoutes()); - } - return this.routes.get(); - } - - protected Route getSimpleMatchingRoute(final String path) { - if (log.isDebugEnabled()) { - log.debug("Finding route for path: " + path); - } - - // This is called for the initialization done in getRoutesMap() - getRoutesMap(); - - if (log.isDebugEnabled()) { - log.debug("servletPath=" + this.dispatcherServletPath); - log.debug("zuulServletPath=" + this.zuulServletPath); - log.debug("RequestUtils.isDispatcherServletRequest()=" - + RequestUtils.isDispatcherServletRequest()); - log.debug("RequestUtils.isZuulServletRequest()=" - + RequestUtils.isZuulServletRequest()); - } - - String adjustedPath = adjustPath(path); - - ZuulRoute route = getZuulRoute(adjustedPath); - - return getRoute(route, adjustedPath); - } - - protected ZuulRoute getZuulRoute(String adjustedPath) { - if (!matchesIgnoredPatterns(adjustedPath)) { - for (Entry entry : getRoutesMap().entrySet()) { - String pattern = entry.getKey(); - log.debug("Matching pattern:" + pattern); - if (this.pathMatcher.match(pattern, adjustedPath)) { - return entry.getValue(); - } - } - } - return null; - } - - protected Route getRoute(ZuulRoute route, String path) { - if (route == null) { - return null; - } - if (log.isDebugEnabled()) { - log.debug("route matched=" + route); - } - String targetPath = path; - String prefix = this.properties.getPrefix(); - if(prefix.endsWith("/")) { - prefix = prefix.substring(0, prefix.length() - 1); - } - if (path.startsWith(prefix + "/") && this.properties.isStripPrefix()) { - targetPath = path.substring(prefix.length()); - } - if (route.isStripPrefix()) { - int index = route.getPath().indexOf("*") - 1; - if (index > 0) { - String routePrefix = route.getPath().substring(0, index); - targetPath = targetPath.replaceFirst(routePrefix, ""); - prefix = prefix + routePrefix; - } - } - Boolean retryable = this.properties.getRetryable(); - if (route.getRetryable() != null) { - retryable = route.getRetryable(); - } - return new Route(route.getId(), targetPath, route.getLocation(), prefix, - retryable, - route.isCustomSensitiveHeaders() ? route.getSensitiveHeaders() : null, - route.isStripPrefix()); - } - - /** - * Calculate all the routes and set up a cache for the values. Subclasses can call - * this method if they need to implement {@link RefreshableRouteLocator}. - */ - protected void doRefresh() { - this.routes.set(locateRoutes()); - } - - /** - * Compute a map of path pattern to route. The default is just a static map from the - * {@link ZuulProperties}, but subclasses can add dynamic calculations. - */ - protected Map locateRoutes() { - LinkedHashMap routesMap = new LinkedHashMap<>(); - for (ZuulRoute route : this.properties.getRoutes().values()) { - routesMap.put(route.getPath(), route); - } - return routesMap; - } - - protected boolean matchesIgnoredPatterns(String path) { - for (String pattern : this.properties.getIgnoredPatterns()) { - log.debug("Matching ignored pattern:" + pattern); - if (this.pathMatcher.match(pattern, path)) { - log.debug("Path " + path + " matches ignored pattern " + pattern); - return true; - } - } - return false; - } - - private String adjustPath(final String path) { - String adjustedPath = path; - - if (RequestUtils.isDispatcherServletRequest() - && StringUtils.hasText(this.dispatcherServletPath)) { - if (!this.dispatcherServletPath.equals("/")) { - adjustedPath = path.substring(this.dispatcherServletPath.length()); - log.debug("Stripped dispatcherServletPath"); - } - } - else if (RequestUtils.isZuulServletRequest()) { - if (StringUtils.hasText(this.zuulServletPath) - && !this.zuulServletPath.equals("/")) { - adjustedPath = path.substring(this.zuulServletPath.length()); - log.debug("Stripped zuulServletPath"); - } - } - else { - // do nothing - } - - log.debug("adjustedPath=" + adjustedPath); - return adjustedPath; - } - - @Override - public int getOrder() { - return order; - } - - public void setOrder(int order) { - this.order = order; - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/TraceProxyRequestHelper.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/TraceProxyRequestHelper.java deleted file mode 100644 index edec513c..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/TraceProxyRequestHelper.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URI; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Enumeration; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.springframework.boot.actuate.web.trace.HttpExchangeTracer; -import org.springframework.boot.actuate.web.trace.HttpTrace; -import org.springframework.boot.actuate.web.trace.HttpTraceRepository; -import org.springframework.boot.actuate.web.trace.Include; -import org.springframework.boot.actuate.web.trace.TraceableRequest; -import org.springframework.util.MultiValueMap; - -import com.netflix.zuul.context.RequestContext; -import org.springframework.util.StringUtils; - -import javax.servlet.http.HttpServletRequest; - -/** - * @author Spencer Gibb - */ -public class TraceProxyRequestHelper extends ProxyRequestHelper { - - private HttpTraceRepository traces; - private final HttpExchangeTracer tracer = new HttpExchangeTracer( - Include.defaultIncludes()); - - public void setTraces(HttpTraceRepository traces) { - this.traces = traces; - } - - @Override - public Map debug(String verb, String uri, - MultiValueMap headers, MultiValueMap params, - InputStream requestEntity) throws IOException { - Map info = new LinkedHashMap<>(); - if (this.traces != null) { - RequestContext context = RequestContext.getCurrentContext(); - info.put("method", verb); - info.put("path", uri); - info.put("query", getQueryString(params)); - info.put("remote", true); - info.put("proxy", context.get("proxy")); - Map trace = new LinkedHashMap<>(); - Map input = new LinkedHashMap<>(); - trace.put("request", input); - info.put("headers", trace); - debugHeaders(headers, input); - HttpServletRequest request = context.getRequest(); - if (shouldDebugBody(context)) { - // Prevent input stream from being read if it needs to go downstream - if (requestEntity != null) { - debugRequestEntity(info, request.getInputStream()); - } - } - HttpTrace httpTrace = tracer - .receivedRequest(new ServletTraceableRequest(request)); - this.traces.add(httpTrace); - return info; - } - return info; - } - - private class ServletTraceableRequest implements TraceableRequest { - private HttpServletRequest request; - - public ServletTraceableRequest(HttpServletRequest request) { - - this.request = request; - } - - @Override - public String getMethod() { - return request.getMethod(); - } - - @Override - public URI getUri() { - StringBuffer urlBuffer = request.getRequestURL(); - if (StringUtils.hasText(request.getQueryString())) { - urlBuffer.append("?"); - urlBuffer.append(request.getQueryString()); - } - return URI.create(urlBuffer.toString()); - } - - @Override - public Map> getHeaders() { - return extractHeaders(); - } - - @Override - public String getRemoteAddress() { - return request.getRemoteAddr(); - } - - private Map> extractHeaders() { - Map> headers = new LinkedHashMap<>(); - Enumeration names = request.getHeaderNames(); - while (names.hasMoreElements()) { - String name = names.nextElement(); - headers.put(name, toList(request.getHeaders(name))); - } - return headers; - } - - private List toList(Enumeration enumeration) { - List list = new ArrayList<>(); - while (enumeration.hasMoreElements()) { - list.add(enumeration.nextElement()); - } - return list; - } - } - - void debugHeaders(MultiValueMap headers, Map map) { - for (Entry> entry : headers.entrySet()) { - Collection collection = entry.getValue(); - Object value = collection; - if (collection.size() < 2) { - value = collection.isEmpty() ? "" : collection.iterator().next(); - } - map.put(entry.getKey(), value); - } - } - - public void appendDebug(Map info, int status, - MultiValueMap headers) { - if (this.traces != null) { - @SuppressWarnings("unchecked") - Map trace = (Map) info.get("headers"); - Map output = new LinkedHashMap<>(); - trace.put("response", output); - debugHeaders(headers, output); - output.put("status", "" + status); - } - } - - private void debugRequestEntity(Map info, InputStream inputStream) - throws IOException { - if (RequestContext.getCurrentContext().isChunkedRequestBody()) { - info.put("body", ""); - return; - } - char[] buffer = new char[4096]; - int count = new InputStreamReader(inputStream, Charset.forName("UTF-8")) - .read(buffer, 0, buffer.length); - if (count > 0) { - String entity = new String(buffer).substring(0, count); - info.put("body", entity.length() < 4096 ? entity : entity + ""); - } - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/ZuulProperties.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/ZuulProperties.java deleted file mode 100644 index 46b6c9ab..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/ZuulProperties.java +++ /dev/null @@ -1,887 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters; - -import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.util.ClassUtils; -import org.springframework.util.StringUtils; - -import javax.annotation.PostConstruct; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import static com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE; - -/** - * @author Spencer Gibb - * @author Dave Syer - * @author Mathias Düsterhöft - * @author Bilal Alp - * @author Gregor Zurowski - */ -@ConfigurationProperties("zuul") -public class ZuulProperties { - - /** - * Headers that are generally expected to be added by Spring Security, and hence often - * duplicated if the proxy and the backend are secured with Spring. By default they - * are added to the ignored headers if Spring Security is present and ignoreSecurityHeaders = true. - */ - public static final List SECURITY_HEADERS = Arrays.asList("Pragma", - "Cache-Control", "X-Frame-Options", "X-Content-Type-Options", - "X-XSS-Protection", "Expires"); - - /** - * A common prefix for all routes. - */ - private String prefix = ""; - - /** - * Flag saying whether to strip the prefix from the path before forwarding. - */ - private boolean stripPrefix = true; - - /** - * Flag for whether retry is supported by default (assuming the routes themselves - * support it). - */ - private Boolean retryable = false; - - /** - * Map of route names to properties. - */ - private Map routes = new LinkedHashMap<>(); - - /** - * Flag to determine whether the proxy adds X-Forwarded-* headers. - */ - private boolean addProxyHeaders = true; - - /** - * Flag to determine whether the proxy forwards the Host header. - */ - private boolean addHostHeader = false; - - /** - * Set of service names not to consider for proxying automatically. By default all - * services in the discovery client will be proxied. - */ - private Set ignoredServices = new LinkedHashSet<>(); - - private Set ignoredPatterns = new LinkedHashSet<>(); - - /** - * Names of HTTP headers to ignore completely (i.e. leave them out of downstream - * requests and drop them from downstream responses). - */ - private Set ignoredHeaders = new LinkedHashSet<>(); - - /** - * Flag to say that SECURITY_HEADERS are added to ignored headers if spring security is on the classpath. - * By setting ignoreSecurityHeaders to false we can switch off this default behaviour. This should be used together with - * disabling the default spring security headers - * see https://docs.spring.io/spring-security/site/docs/current/reference/html/headers.html#default-security-headers - */ - private boolean ignoreSecurityHeaders = true; - - /** - * Flag to force the original query string encoding when building the backend URI in - * SimpleHostRoutingFilter. When activated, query string will be built using - * HttpServletRequest getQueryString() method instead of UriTemplate. Note that this - * flag is not used in RibbonRoutingFilter with services found via DiscoveryClient - * (like Eureka). - */ - private boolean forceOriginalQueryStringEncoding = false; - - /** - * Path to install Zuul as a servlet (not part of Spring MVC). The servlet is more - * memory efficient for requests with large bodies, e.g. file uploads. - */ - private String servletPath = "/zuul"; - - private boolean ignoreLocalService = true; - - /** - * Host properties controlling default connection pool properties. - */ - private Host host = new Host(); - - /** - * Flag to say that request bodies can be traced. - */ - private boolean traceRequestBody = true; - - /** - * Flag to say that path elements past the first semicolon can be dropped. - */ - private boolean removeSemicolonContent = true; - - /** - * List of sensitive headers that are not passed to downstream requests. Defaults to a - * "safe" set of headers that commonly contain user credentials. It's OK to remove - * those from the list if the downstream service is part of the same system as the - * proxy, so they are sharing authentication data. If using a physical URL outside - * your own domain, then generally it would be a bad idea to leak user credentials. - */ - private Set sensitiveHeaders = new LinkedHashSet<>( - Arrays.asList("Cookie", "Set-Cookie", "Authorization")); - - /** - * Flag to say whether the hostname for ssl connections should be verified or not. Default is true. - * This should only be used in test setups! - */ - private boolean sslHostnameValidationEnabled =true; - - private ExecutionIsolationStrategy ribbonIsolationStrategy = SEMAPHORE; - - private HystrixSemaphore semaphore = new HystrixSemaphore(); - - private HystrixThreadPool threadPool = new HystrixThreadPool(); - - /** - * Setting for SendResponseFilter to conditionally set Content-Length header. - */ - private boolean setContentLength = false; - - /** - * Setting for SendResponseFilter to conditionally include X-Zuul-Debug-Header header. - */ - private boolean includeDebugHeader = false; - - /** - * Setting for SendResponseFilter for the initial stream buffer size. - */ - private int initialStreamBufferSize = 8192; - - public Set getIgnoredHeaders() { - Set ignoredHeaders = new LinkedHashSet<>(this.ignoredHeaders); - if (ClassUtils.isPresent( - "org.springframework.security.config.annotation.web.WebSecurityConfigurer", - null) && Collections.disjoint(ignoredHeaders, SECURITY_HEADERS) && ignoreSecurityHeaders) { - // Allow Spring Security in the gateway to control these headers - ignoredHeaders.addAll(SECURITY_HEADERS); - } - return ignoredHeaders; - } - - public void setIgnoredHeaders(Set ignoredHeaders) { - this.ignoredHeaders.addAll(ignoredHeaders); - } - - @PostConstruct - public void init() { - for (Entry entry : this.routes.entrySet()) { - ZuulRoute value = entry.getValue(); - if (!StringUtils.hasText(value.getLocation())) { - value.serviceId = entry.getKey(); - } - if (!StringUtils.hasText(value.getId())) { - value.id = entry.getKey(); - } - if (!StringUtils.hasText(value.getPath())) { - value.path = "/" + entry.getKey() + "/**"; - } - } - } - - public static class ZuulRoute { - - /** - * The ID of the route (the same as its map key by default). - */ - private String id; - - /** - * The path (pattern) for the route, e.g. /foo/**. - */ - private String path; - - /** - * The service ID (if any) to map to this route. You can specify a physical URL or - * a service, but not both. - */ - private String serviceId; - - /** - * A full physical URL to map to the route. An alternative is to use a service ID - * and service discovery to find the physical address. - */ - private String url; - - /** - * Flag to determine whether the prefix for this route (the path, minus pattern - * patcher) should be stripped before forwarding. - */ - private boolean stripPrefix = true; - - /** - * Flag to indicate that this route should be retryable (if supported). Generally - * retry requires a service ID and ribbon. - */ - private Boolean retryable; - - /** - * List of sensitive headers that are not passed to downstream requests. Defaults - * to a "safe" set of headers that commonly contain user credentials. It's OK to - * remove those from the list if the downstream service is part of the same system - * as the proxy, so they are sharing authentication data. If using a physical URL - * outside your own domain, then generally it would be a bad idea to leak user - * credentials. - */ - private Set sensitiveHeaders = new LinkedHashSet<>(); - - private boolean customSensitiveHeaders = false; - - public ZuulRoute() {} - - public ZuulRoute(String id, String path, String serviceId, String url, - boolean stripPrefix, Boolean retryable, Set sensitiveHeaders) { - this.id = id; - this.path = path; - this.serviceId = serviceId; - this.url = url; - this.stripPrefix = stripPrefix; - this.retryable = retryable; - this.sensitiveHeaders = sensitiveHeaders; - this.customSensitiveHeaders = sensitiveHeaders != null; - } - - public ZuulRoute(String text) { - String location = null; - String path = text; - if (text.contains("=")) { - String[] values = StringUtils - .trimArrayElements(StringUtils.split(text, "=")); - location = values[1]; - path = values[0]; - } - this.id = extractId(path); - if (!path.startsWith("/")) { - path = "/" + path; - } - setLocation(location); - this.path = path; - } - - public ZuulRoute(String path, String location) { - this.id = extractId(path); - this.path = path; - setLocation(location); - } - - public String getLocation() { - if (StringUtils.hasText(this.url)) { - return this.url; - } - return this.serviceId; - } - - public void setLocation(String location) { - if (location != null - && (location.startsWith("http:") || location.startsWith("https:"))) { - this.url = location; - } - else { - this.serviceId = location; - } - } - - private String extractId(String path) { - path = path.startsWith("/") ? path.substring(1) : path; - path = path.replace("/*", "").replace("*", ""); - return path; - } - - public Route getRoute(String prefix) { - return new Route(this.id, this.path, getLocation(), prefix, this.retryable, - isCustomSensitiveHeaders() ? this.sensitiveHeaders : null, - this.stripPrefix); - } - - public void setSensitiveHeaders(Set headers) { - this.customSensitiveHeaders = true; - this.sensitiveHeaders = new LinkedHashSet<>(headers); - } - - public boolean isCustomSensitiveHeaders() { - return this.customSensitiveHeaders; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public String getServiceId() { - return serviceId; - } - - public void setServiceId(String serviceId) { - this.serviceId = serviceId; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public boolean isStripPrefix() { - return stripPrefix; - } - - public void setStripPrefix(boolean stripPrefix) { - this.stripPrefix = stripPrefix; - } - - public Boolean getRetryable() { - return retryable; - } - - public void setRetryable(Boolean retryable) { - this.retryable = retryable; - } - - public Set getSensitiveHeaders() { - return sensitiveHeaders; - } - - public void setCustomSensitiveHeaders(boolean customSensitiveHeaders) { - this.customSensitiveHeaders = customSensitiveHeaders; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ZuulRoute that = (ZuulRoute) o; - return customSensitiveHeaders == that.customSensitiveHeaders && - Objects.equals(id, that.id) && - Objects.equals(path, that.path) && - Objects.equals(retryable, that.retryable) && - Objects.equals(sensitiveHeaders, that.sensitiveHeaders) && - Objects.equals(serviceId, that.serviceId) && - stripPrefix == that.stripPrefix && - Objects.equals(url, that.url); - } - - @Override - public int hashCode() { - return Objects.hash(customSensitiveHeaders, id, path, retryable, - sensitiveHeaders, serviceId, stripPrefix, url); - } - - @Override public String toString() { - return new StringBuilder("ZuulRoute{").append("id='").append(id).append("', ") - .append("path='").append(path).append("', ") - .append("serviceId='").append(serviceId).append("', ") - .append("url='").append(url).append("', ") - .append("stripPrefix=").append(stripPrefix).append(", ") - .append("retryable=").append(retryable).append(", ") - .append("sensitiveHeaders=").append(sensitiveHeaders).append(", ") - .append("customSensitiveHeaders=").append(customSensitiveHeaders).append(", ") - .append("}").toString(); - } - - } - - public static class Host { - /** - * The maximum number of total connections the proxy can hold open to backends. - */ - private int maxTotalConnections = 200; - /** - * The maximum number of connections that can be used by a single route. - */ - private int maxPerRouteConnections = 20; - /** - * The socket timeout in millis. Defaults to 10000. - */ - private int socketTimeoutMillis = 10000; - /** - * The connection timeout in millis. Defaults to 2000. - */ - private int connectTimeoutMillis = 2000; - /** - * The lifetime for the connection pool. - */ - private long timeToLive = -1; - /** - * The time unit for timeToLive. - */ - private TimeUnit timeUnit = TimeUnit.MILLISECONDS; - - public Host() { - } - - public Host(int maxTotalConnections, int maxPerRouteConnections, - int socketTimeoutMillis, int connectTimeoutMillis, long timeToLive, - TimeUnit timeUnit) { - this.maxTotalConnections = maxTotalConnections; - this.maxPerRouteConnections = maxPerRouteConnections; - this.socketTimeoutMillis = socketTimeoutMillis; - this.connectTimeoutMillis = connectTimeoutMillis; - this.timeToLive = timeToLive; - this.timeUnit = timeUnit; - } - - public int getMaxTotalConnections() { - return maxTotalConnections; - } - - public void setMaxTotalConnections(int maxTotalConnections) { - this.maxTotalConnections = maxTotalConnections; - } - - public int getMaxPerRouteConnections() { - return maxPerRouteConnections; - } - - public void setMaxPerRouteConnections(int maxPerRouteConnections) { - this.maxPerRouteConnections = maxPerRouteConnections; - } - - public int getSocketTimeoutMillis() { - return socketTimeoutMillis; - } - - public void setSocketTimeoutMillis(int socketTimeoutMillis) { - this.socketTimeoutMillis = socketTimeoutMillis; - } - - public int getConnectTimeoutMillis() { - return connectTimeoutMillis; - } - - public void setConnectTimeoutMillis(int connectTimeoutMillis) { - this.connectTimeoutMillis = connectTimeoutMillis; - } - - public long getTimeToLive() { - return timeToLive; - } - - public void setTimeToLive(long timeToLive) { - this.timeToLive = timeToLive; - } - - public TimeUnit getTimeUnit() { - return timeUnit; - } - - public void setTimeUnit(TimeUnit timeUnit) { - this.timeUnit = timeUnit; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Host host = (Host) o; - return maxTotalConnections == host.maxTotalConnections && - maxPerRouteConnections == host.maxPerRouteConnections && - socketTimeoutMillis == host.socketTimeoutMillis && - connectTimeoutMillis == host.connectTimeoutMillis && - timeToLive == host.timeToLive && - timeUnit == host.timeUnit; - } - - @Override - public int hashCode() { - return Objects.hash(maxTotalConnections, maxPerRouteConnections, socketTimeoutMillis, connectTimeoutMillis, timeToLive, timeUnit); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("Host{"); - sb.append("maxTotalConnections=").append(maxTotalConnections); - sb.append(", maxPerRouteConnections=").append(maxPerRouteConnections); - sb.append(", socketTimeoutMillis=").append(socketTimeoutMillis); - sb.append(", connectTimeoutMillis=").append(connectTimeoutMillis); - sb.append(", timeToLive=").append(timeToLive); - sb.append(", timeUnit=").append(timeUnit); - sb.append('}'); - return sb.toString(); - } - } - - public static class HystrixSemaphore { - /** - * The maximum number of total semaphores for Hystrix. - */ - private int maxSemaphores = 100; - - public HystrixSemaphore() {} - - public HystrixSemaphore(int maxSemaphores) { - this.maxSemaphores = maxSemaphores; - } - - public int getMaxSemaphores() { - return maxSemaphores; - } - - public void setMaxSemaphores(int maxSemaphores) { - this.maxSemaphores = maxSemaphores; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - HystrixSemaphore that = (HystrixSemaphore) o; - return maxSemaphores == that.maxSemaphores; - } - - @Override - public int hashCode() { - return Objects.hash(maxSemaphores); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("HystrixSemaphore{"); - sb.append("maxSemaphores=").append(maxSemaphores); - sb.append('}'); - return sb.toString(); - } - } - - public static class HystrixThreadPool { - /** - * Flag to determine whether RibbonCommands should use separate thread pools for hystrix. - * By setting to true, RibbonCommands will be executed in a hystrix's thread pool that it is associated with. - * Each RibbonCommand will be associated with a thread pool according to its commandKey (serviceId). - * As default, all commands will be executed in a single thread pool whose threadPoolKey is "RibbonCommand". - * This property is only applicable when using THREAD as ribbonIsolationStrategy - */ - private boolean useSeparateThreadPools = false; - - /** - * A prefix for HystrixThreadPoolKey of hystrix's thread pool that is allocated to each service Id. - * This property is only applicable when using THREAD as ribbonIsolationStrategy and useSeparateThreadPools = true - */ - private String threadPoolKeyPrefix = ""; - - public boolean isUseSeparateThreadPools() { - return useSeparateThreadPools; - } - - public void setUseSeparateThreadPools(boolean useSeparateThreadPools) { - this.useSeparateThreadPools = useSeparateThreadPools; - } - - public String getThreadPoolKeyPrefix() { - return threadPoolKeyPrefix; - } - - public void setThreadPoolKeyPrefix(String threadPoolKeyPrefix) { - this.threadPoolKeyPrefix = threadPoolKeyPrefix; - } - } - - public String getServletPattern() { - String path = this.servletPath; - if (!path.startsWith("/")) { - path = "/" + path; - } - if (!path.contains("*")) { - path = path.endsWith("/") ? (path + "*") : (path + "/*"); - } - return path; - } - - public String getPrefix() { - return prefix; - } - - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - public boolean isStripPrefix() { - return stripPrefix; - } - - public void setStripPrefix(boolean stripPrefix) { - this.stripPrefix = stripPrefix; - } - - public Boolean getRetryable() { - return retryable; - } - - public void setRetryable(Boolean retryable) { - this.retryable = retryable; - } - - public Map getRoutes() { - return routes; - } - - public void setRoutes(Map routes) { - this.routes = routes; - } - - public boolean isAddProxyHeaders() { - return addProxyHeaders; - } - - public void setAddProxyHeaders(boolean addProxyHeaders) { - this.addProxyHeaders = addProxyHeaders; - } - - public boolean isAddHostHeader() { - return addHostHeader; - } - - public void setAddHostHeader(boolean addHostHeader) { - this.addHostHeader = addHostHeader; - } - - public Set getIgnoredServices() { - return ignoredServices; - } - - public void setIgnoredServices(Set ignoredServices) { - this.ignoredServices = ignoredServices; - } - - public Set getIgnoredPatterns() { - return ignoredPatterns; - } - - public void setIgnoredPatterns(Set ignoredPatterns) { - this.ignoredPatterns = ignoredPatterns; - } - - public boolean isIgnoreSecurityHeaders() { - return ignoreSecurityHeaders; - } - - public void setIgnoreSecurityHeaders(boolean ignoreSecurityHeaders) { - this.ignoreSecurityHeaders = ignoreSecurityHeaders; - } - - public boolean isForceOriginalQueryStringEncoding() { - return forceOriginalQueryStringEncoding; - } - - public void setForceOriginalQueryStringEncoding( - boolean forceOriginalQueryStringEncoding) { - this.forceOriginalQueryStringEncoding = forceOriginalQueryStringEncoding; - } - - public String getServletPath() { - return servletPath; - } - - public void setServletPath(String servletPath) { - this.servletPath = servletPath; - } - - public boolean isIgnoreLocalService() { - return ignoreLocalService; - } - - public void setIgnoreLocalService(boolean ignoreLocalService) { - this.ignoreLocalService = ignoreLocalService; - } - - public Host getHost() { - return host; - } - - public void setHost(Host host) { - this.host = host; - } - - public boolean isTraceRequestBody() { - return traceRequestBody; - } - - public void setTraceRequestBody(boolean traceRequestBody) { - this.traceRequestBody = traceRequestBody; - } - - public boolean isRemoveSemicolonContent() { - return removeSemicolonContent; - } - - public void setRemoveSemicolonContent(boolean removeSemicolonContent) { - this.removeSemicolonContent = removeSemicolonContent; - } - - public Set getSensitiveHeaders() { - return sensitiveHeaders; - } - - public void setSensitiveHeaders(Set sensitiveHeaders) { - this.sensitiveHeaders = sensitiveHeaders; - } - - public boolean isSslHostnameValidationEnabled() { - return sslHostnameValidationEnabled; - } - - public void setSslHostnameValidationEnabled(boolean sslHostnameValidationEnabled) { - this.sslHostnameValidationEnabled = sslHostnameValidationEnabled; - } - - public ExecutionIsolationStrategy getRibbonIsolationStrategy() { - return ribbonIsolationStrategy; - } - - public void setRibbonIsolationStrategy( - ExecutionIsolationStrategy ribbonIsolationStrategy) { - this.ribbonIsolationStrategy = ribbonIsolationStrategy; - } - - public HystrixSemaphore getSemaphore() { - return semaphore; - } - - public void setSemaphore(HystrixSemaphore semaphore) { - this.semaphore = semaphore; - } - - public HystrixThreadPool getThreadPool() { - return threadPool; - } - - public void setThreadPool(HystrixThreadPool threadPool) { - this.threadPool = threadPool; - } - - public boolean isSetContentLength() { - return setContentLength; - } - - public void setSetContentLength(boolean setContentLength) { - this.setContentLength = setContentLength; - } - - public boolean isIncludeDebugHeader() { - return includeDebugHeader; - } - - public void setIncludeDebugHeader(boolean includeDebugHeader) { - this.includeDebugHeader = includeDebugHeader; - } - - public int getInitialStreamBufferSize() { - return initialStreamBufferSize; - } - - public void setInitialStreamBufferSize(int initialStreamBufferSize) { - this.initialStreamBufferSize = initialStreamBufferSize; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ZuulProperties that = (ZuulProperties) o; - return addHostHeader == that.addHostHeader && - addProxyHeaders == that.addProxyHeaders && - forceOriginalQueryStringEncoding == that.forceOriginalQueryStringEncoding && - Objects.equals(host, that.host) && - Objects.equals(ignoredHeaders, that.ignoredHeaders) && - Objects.equals(ignoredPatterns, that.ignoredPatterns) && - Objects.equals(ignoredServices, that.ignoredServices) && - ignoreLocalService == that.ignoreLocalService && - ignoreSecurityHeaders == that.ignoreSecurityHeaders && - Objects.equals(prefix, that.prefix) && - removeSemicolonContent == that.removeSemicolonContent && - Objects.equals(retryable, that.retryable) && - Objects.equals(ribbonIsolationStrategy, that.ribbonIsolationStrategy) && - Objects.equals(routes, that.routes) && - Objects.equals(semaphore, that.semaphore) && - Objects.equals(sensitiveHeaders, that.sensitiveHeaders) && - Objects.equals(servletPath, that.servletPath) && - sslHostnameValidationEnabled == that.sslHostnameValidationEnabled && - stripPrefix == that.stripPrefix && - setContentLength == that.setContentLength && - includeDebugHeader == that.includeDebugHeader && - initialStreamBufferSize == that.initialStreamBufferSize && - Objects.equals(threadPool, that.threadPool) && - traceRequestBody == that.traceRequestBody; - } - - @Override - public int hashCode() { - return Objects.hash(addHostHeader, addProxyHeaders, forceOriginalQueryStringEncoding, - host, ignoredHeaders, ignoredPatterns, ignoredServices, ignoreLocalService, - ignoreSecurityHeaders, prefix, removeSemicolonContent, retryable, - ribbonIsolationStrategy, routes, semaphore, sensitiveHeaders, servletPath, - sslHostnameValidationEnabled, stripPrefix, threadPool, traceRequestBody, - setContentLength, includeDebugHeader, initialStreamBufferSize); - } - - @Override - public String toString() { - return new StringBuilder("ZuulProperties{") - .append("prefix='").append(prefix).append("', ") - .append("stripPrefix=").append(stripPrefix).append(", ") - .append("retryable=").append(retryable).append(", ") - .append("routes=").append(routes).append(", ") - .append("addProxyHeaders=").append(addProxyHeaders).append(", ") - .append("addHostHeader=").append(addHostHeader).append(", ") - .append("ignoredServices=").append(ignoredServices).append(", ") - .append("ignoredPatterns=").append(ignoredPatterns).append(", ") - .append("ignoredHeaders=").append(ignoredHeaders).append(", ") - .append("ignoreSecurityHeaders=").append(ignoreSecurityHeaders).append(", ") - .append("forceOriginalQueryStringEncoding=").append(forceOriginalQueryStringEncoding).append(", ") - .append("servletPath='").append(servletPath).append("', ") - .append("ignoreLocalService=").append(ignoreLocalService).append(", ") - .append("host=").append(host).append(", ") - .append("traceRequestBody=").append(traceRequestBody).append(", ") - .append("removeSemicolonContent=").append(removeSemicolonContent).append(", ") - .append("sensitiveHeaders=").append(sensitiveHeaders).append(", ") - .append("sslHostnameValidationEnabled=").append(sslHostnameValidationEnabled).append(", ") - .append("ribbonIsolationStrategy=").append(ribbonIsolationStrategy).append(", ") - .append("semaphore=").append(semaphore).append(", ") - .append("threadPool=").append(threadPool).append(", ") - .append("setContentLength=").append(setContentLength).append(", ") - .append("includeDebugHeader=").append(includeDebugHeader).append(", ") - .append("initialStreamBufferSize=").append(initialStreamBufferSize).append(", ") - .append("}").toString(); - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/DiscoveryClientRouteLocator.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/DiscoveryClientRouteLocator.java deleted file mode 100644 index d35deb4b..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/DiscoveryClientRouteLocator.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.discovery; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.netflix.zuul.filters.RefreshableRouteLocator; -import org.springframework.cloud.netflix.zuul.filters.RouteLocator; -import org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute; -import org.springframework.util.PatternMatchUtils; -import org.springframework.util.StringUtils; - -/** - * A {@link RouteLocator} that combines static, configured routes with those from a - * {@link DiscoveryClient}. The discovery client takes precedence. - * - * @author Spencer Gibb - * @author Dave Syer - */ -public class DiscoveryClientRouteLocator extends SimpleRouteLocator - implements RefreshableRouteLocator { - - private static final Log log = LogFactory.getLog(DiscoveryClientRouteLocator.class); - - public static final String DEFAULT_ROUTE = "/**"; - - private DiscoveryClient discovery; - - private ZuulProperties properties; - - private ServiceRouteMapper serviceRouteMapper; - - @Deprecated - public DiscoveryClientRouteLocator(String servletPath, DiscoveryClient discovery, - ZuulProperties properties) { - this(servletPath, discovery, properties, (ServiceInstance)null); - } - - public DiscoveryClientRouteLocator(String servletPath, DiscoveryClient discovery, - ZuulProperties properties, ServiceInstance localServiceInstance) { - super(servletPath, properties); - - if (properties.isIgnoreLocalService() && localServiceInstance != null) { - String localServiceId = localServiceInstance.getServiceId(); - if (!properties.getIgnoredServices().contains(localServiceId)) { - properties.getIgnoredServices().add(localServiceId); - } - } - this.serviceRouteMapper = new SimpleServiceRouteMapper(); - this.discovery = discovery; - this.properties = properties; - } - - @Deprecated - public DiscoveryClientRouteLocator(String servletPath, DiscoveryClient discovery, - ZuulProperties properties, ServiceRouteMapper serviceRouteMapper) { - this(servletPath, discovery, properties, (ServiceInstance)null); - this.serviceRouteMapper = serviceRouteMapper; - } - - public DiscoveryClientRouteLocator(String servletPath, DiscoveryClient discovery, - ZuulProperties properties, ServiceRouteMapper serviceRouteMapper, ServiceInstance localServiceInstance) { - this(servletPath, discovery, properties, localServiceInstance); - this.serviceRouteMapper = serviceRouteMapper; - } - - public void addRoute(String path, String location) { - this.properties.getRoutes().put(path, new ZuulRoute(path, location)); - refresh(); - } - - public void addRoute(ZuulRoute route) { - this.properties.getRoutes().put(route.getPath(), route); - refresh(); - } - - @Override - protected LinkedHashMap locateRoutes() { - LinkedHashMap routesMap = new LinkedHashMap<>(); - routesMap.putAll(super.locateRoutes()); - if (this.discovery != null) { - Map staticServices = new LinkedHashMap<>(); - for (ZuulRoute route : routesMap.values()) { - String serviceId = route.getServiceId(); - if (serviceId == null) { - serviceId = route.getId(); - } - if (serviceId != null) { - staticServices.put(serviceId, route); - } - } - // Add routes for discovery services by default - List services = this.discovery.getServices(); - String[] ignored = this.properties.getIgnoredServices() - .toArray(new String[0]); - for (String serviceId : services) { - // Ignore specifically ignored services and those that were manually - // configured - String key = "/" + mapRouteToService(serviceId) + "/**"; - if (staticServices.containsKey(serviceId) - && staticServices.get(serviceId).getUrl() == null) { - // Explicitly configured with no URL, cannot be ignored - // all static routes are already in routesMap - // Update location using serviceId if location is null - ZuulRoute staticRoute = staticServices.get(serviceId); - if (!StringUtils.hasText(staticRoute.getLocation())) { - staticRoute.setLocation(serviceId); - } - } - if (!PatternMatchUtils.simpleMatch(ignored, serviceId) - && !routesMap.containsKey(key)) { - // Not ignored - routesMap.put(key, new ZuulRoute(key, serviceId)); - } - } - } - 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 values = new LinkedHashMap<>(); - for (Entry 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; - } - - @Override - public void refresh() { - doRefresh(); - } - - protected String mapRouteToService(String serviceId) { - return this.serviceRouteMapper.apply(serviceId); - } - - protected void addConfiguredRoutes(Map routes) { - Map routeEntries = this.properties.getRoutes(); - for (ZuulRoute entry : routeEntries.values()) { - String route = entry.getPath(); - if (routes.containsKey(route)) { - log.warn("Overwriting route " + route + ": already defined by " - + routes.get(route)); - } - routes.put(route, entry); - } - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapper.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapper.java deleted file mode 100644 index 1b6de718..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapper.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.springframework.cloud.netflix.zuul.filters.discovery; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.springframework.util.StringUtils; - -/** - * @author Stéphane Leroy - * - * This service route mapper use Java 7 RegEx named group feature to rewrite a discovered - * service Id into a route. - * - * Ex : If we want to map service Id [rest-service-v1] to - * /v1/rest-service/** route service pattern : - * "(?.*)-(?v.*$)" route pattern : - * "${version}/${name}" - * - * This implementation uses Matcher.replaceFirst so only one match will be - * replaced. - */ -public class PatternServiceRouteMapper implements ServiceRouteMapper { - - /** - * A RegExp Pattern that extract needed information from a service ID. Ex : - * "(?.*)-(?v.*$)" - */ - private Pattern servicePattern; - /** - * A RegExp that refer to named groups define in servicePattern. Ex : - * "${version}/${name}" - */ - private String routePattern; - - public PatternServiceRouteMapper(String servicePattern, String routePattern) { - this.servicePattern = Pattern.compile(servicePattern); - this.routePattern = routePattern; - } - - /** - * Use servicePattern to extract groups and routePattern to construct the route. - * - * If there is no matches, the serviceId is returned. - * - * @param serviceId service discovered name - * @return route path - */ - @Override - public String apply(String serviceId) { - Matcher matcher = this.servicePattern.matcher(serviceId); - String route = matcher.replaceFirst(this.routePattern); - route = cleanRoute(route); - return (StringUtils.hasText(route) ? route : serviceId); - } - - /** - * Route with regex and replace can be a bit messy when used with conditional named - * group. We clean here first and trailing '/' and remove multiple consecutive '/' - * @param route - * @return - */ - private String cleanRoute(final String route) { - String routeToClean = route.replaceAll("/{2,}", "/"); - if (routeToClean.startsWith("/")) { - routeToClean = routeToClean.substring(1); - } - if (routeToClean.endsWith("/")) { - routeToClean = routeToClean.substring(0, routeToClean.length() - 1); - } - return routeToClean; - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/ServiceRouteMapper.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/ServiceRouteMapper.java deleted file mode 100644 index 6fb0083c..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/ServiceRouteMapper.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.springframework.cloud.netflix.zuul.filters.discovery; - -/** - * Provide a way to apply convention between routes and discovered services name. - * - * @author Stéphane LEROY - * - */ -public interface ServiceRouteMapper { - - /** - * Take a service Id (its discovered name) and return a route path. - * - * @param serviceId service discovered name - * @return route path - */ - String apply(String serviceId); -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/SimpleServiceRouteMapper.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/SimpleServiceRouteMapper.java deleted file mode 100644 index 151502ca..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/SimpleServiceRouteMapper.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.springframework.cloud.netflix.zuul.filters.discovery; - -/** - * @author Stéphane Leroy - * - * A simple passthru service route mapper. - */ -public class SimpleServiceRouteMapper implements ServiceRouteMapper { - @Override - public String apply(String serviceId) { - return serviceId; - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilter.java deleted file mode 100644 index 1cbdf4ae..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilter.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.springframework.cloud.netflix.zuul.filters.post; - -import com.netflix.util.Pair; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.netflix.zuul.filters.Route; -import org.springframework.cloud.netflix.zuul.filters.RouteLocator; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.http.HttpStatus; -import org.springframework.http.server.ServletServerHttpRequest; -import org.springframework.util.StringUtils; -import org.springframework.web.util.UriComponents; -import org.springframework.web.util.UriComponentsBuilder; -import org.springframework.web.util.UrlPathHelper; - -import java.net.URI; - -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SEND_RESPONSE_FILTER_ORDER; - -/** - * {@link ZuulFilter} Responsible for rewriting the Location header to be the Zuul URL - * - * @author Biju Kunjummen - */ -public class LocationRewriteFilter extends ZuulFilter { - - private final UrlPathHelper urlPathHelper = new UrlPathHelper(); - - @Autowired - private ZuulProperties zuulProperties; - - @Autowired - private RouteLocator routeLocator; - - private static final String LOCATION_HEADER = "Location"; - - public LocationRewriteFilter() { - } - - public LocationRewriteFilter(ZuulProperties zuulProperties, - RouteLocator routeLocator) { - this.routeLocator = routeLocator; - this.zuulProperties = zuulProperties; - } - - @Override - public String filterType() { - return POST_TYPE; - } - - @Override - public int filterOrder() { - return SEND_RESPONSE_FILTER_ORDER - 100; - } - - @Override - public boolean shouldFilter() { - RequestContext ctx = RequestContext.getCurrentContext(); - int statusCode = ctx.getResponseStatusCode(); - return HttpStatus.valueOf(statusCode).is3xxRedirection(); - } - - @Override - public Object run() { - RequestContext ctx = RequestContext.getCurrentContext(); - Route route = routeLocator.getMatchingRoute( - urlPathHelper.getPathWithinApplication(ctx.getRequest())); - - if (route != null) { - Pair lh = locationHeader(ctx); - if (lh != null) { - String location = lh.second(); - URI originalRequestUri = UriComponentsBuilder - .fromHttpRequest(new ServletServerHttpRequest(ctx.getRequest())) - .build().toUri(); - - UriComponentsBuilder redirectedUriBuilder = UriComponentsBuilder - .fromUriString(location); - - UriComponents redirectedUriComps = redirectedUriBuilder.build(); - - String newPath = getRestoredPath(this.zuulProperties, route, - redirectedUriComps); - - String modifiedLocation = redirectedUriBuilder - .scheme(originalRequestUri.getScheme()) - .host(originalRequestUri.getHost()) - .port(originalRequestUri.getPort()).replacePath(newPath).build() - .toUriString(); - - lh.setSecond(modifiedLocation); - } - } - return null; - } - - private String getRestoredPath(ZuulProperties zuulProperties, Route route, - UriComponents redirectedUriComps) { - StringBuilder path = new StringBuilder(); - String redirectedPathWithoutGlobal = downstreamHasGlobalPrefix(zuulProperties) - ? redirectedUriComps.getPath() - .substring(("/" + zuulProperties.getPrefix()).length()) - : redirectedUriComps.getPath(); - - if (downstreamHasGlobalPrefix(zuulProperties)) { - path.append("/" + zuulProperties.getPrefix()); - } - else { - path.append(zuulHasGlobalPrefix(zuulProperties) - ? "/" + zuulProperties.getPrefix() : ""); - } - - path.append(downstreamHasRoutePrefix(route) ? "" : "/" + route.getPrefix()) - .append(redirectedPathWithoutGlobal); - - return path.toString(); - } - - private boolean downstreamHasGlobalPrefix(ZuulProperties zuulProperties) { - return (!zuulProperties.isStripPrefix() - && StringUtils.hasText(zuulProperties.getPrefix())); - } - - private boolean zuulHasGlobalPrefix(ZuulProperties zuulProperties) { - return StringUtils.hasText(zuulProperties.getPrefix()); - } - - private boolean downstreamHasRoutePrefix(Route route) { - return (!route.isPrefixStripped() && StringUtils.hasText(route.getPrefix())); - } - - private Pair locationHeader(RequestContext ctx) { - if (ctx.getZuulResponseHeaders() != null) { - for (Pair pair : ctx.getZuulResponseHeaders()) { - if (pair.first().equals(LOCATION_HEADER)) { - return pair; - } - } - } - return null; - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilter.java deleted file mode 100644 index 03f7cb65..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilter.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.post; - -import javax.servlet.RequestDispatcher; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.netflix.zuul.util.ZuulRuntimeException; -import org.springframework.util.ReflectionUtils; -import org.springframework.util.StringUtils; - -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.exception.ZuulException; - -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ERROR_TYPE; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SEND_ERROR_FILTER_ORDER; - -/** - * Error {@link ZuulFilter} that forwards to /error (by default) if {@link RequestContext#getThrowable()} is not null. - * - * @author Spencer Gibb - */ -//TODO: move to error package in Edgware -public class SendErrorFilter extends ZuulFilter { - - private static final Log log = LogFactory.getLog(SendErrorFilter.class); - protected static final String SEND_ERROR_FILTER_RAN = "sendErrorFilter.ran"; - - @Value("${error.path:/error}") - private String errorPath; - - @Override - public String filterType() { - return ERROR_TYPE; - } - - @Override - public int filterOrder() { - return SEND_ERROR_FILTER_ORDER; - } - - @Override - public boolean shouldFilter() { - RequestContext ctx = RequestContext.getCurrentContext(); - // only forward to errorPath if it hasn't been forwarded to already - return ctx.getThrowable() != null - && !ctx.getBoolean(SEND_ERROR_FILTER_RAN, false); - } - - @Override - public Object run() { - try { - RequestContext ctx = RequestContext.getCurrentContext(); - ZuulException exception = findZuulException(ctx.getThrowable()); - HttpServletRequest request = ctx.getRequest(); - - request.setAttribute("javax.servlet.error.status_code", exception.nStatusCode); - - log.warn("Error during filtering", exception); - request.setAttribute("javax.servlet.error.exception", exception); - - if (StringUtils.hasText(exception.errorCause)) { - request.setAttribute("javax.servlet.error.message", exception.errorCause); - } - - RequestDispatcher dispatcher = request.getRequestDispatcher( - this.errorPath); - if (dispatcher != null) { - ctx.set(SEND_ERROR_FILTER_RAN, true); - if (!ctx.getResponse().isCommitted()) { - ctx.setResponseStatusCode(exception.nStatusCode); - dispatcher.forward(request, ctx.getResponse()); - } - } - } - catch (Exception ex) { - ReflectionUtils.rethrowRuntimeException(ex); - } - return null; - } - - ZuulException findZuulException(Throwable throwable) { - if (throwable.getCause() instanceof ZuulRuntimeException) { - // this was a failure initiated by one of the local filters - return (ZuulException) throwable.getCause().getCause(); - } - - if (throwable.getCause() instanceof ZuulException) { - // wrapped zuul exception - return (ZuulException) throwable.getCause(); - } - - if (throwable instanceof ZuulException) { - // exception thrown by zuul lifecycle - return (ZuulException) throwable; - } - - // fallback, should never get here - return new ZuulException(throwable, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null); - } - - public void setErrorPath(String errorPath) { - this.errorPath = errorPath; - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/SendResponseFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/SendResponseFilter.java deleted file mode 100644 index af5ee110..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/SendResponseFilter.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.post; - -import java.io.ByteArrayInputStream; -import java.io.Closeable; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.zip.GZIPInputStream; - -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.util.ReflectionUtils; - -import com.netflix.util.Pair; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.constants.ZuulHeaders; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.util.HTTPRequestUtils; - -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ROUTING_DEBUG_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SEND_RESPONSE_FILTER_ORDER; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.X_ZUUL_DEBUG_HEADER; - -/** - * Post {@link ZuulFilter} that writes responses from proxied requests to the current response. - * - * @author Spencer Gibb - * @author Dave Syer - * @author Ryan Baxter - */ -public class SendResponseFilter extends ZuulFilter { - - private static final Log log = LogFactory.getLog(SendResponseFilter.class); - - private boolean useServlet31 = true; - private ZuulProperties zuulProperties; - - private ThreadLocal buffers; - - @Deprecated - public SendResponseFilter() { - this(new ZuulProperties()); - } - - public SendResponseFilter(ZuulProperties zuulProperties) { - this.zuulProperties = zuulProperties; - // To support Servlet API 3.1 we need to check if setContentLengthLong exists - // minimum support in Spring 5 is 3.0 so we need to keep tihs - try { - HttpServletResponse.class.getMethod("setContentLengthLong", long.class); - } catch(NoSuchMethodException e) { - useServlet31 = false; - } - buffers = ThreadLocal.withInitial(() -> new byte[zuulProperties.getInitialStreamBufferSize()]); - } - - /* for testing */ boolean isUseServlet31() { - return useServlet31; - } - - @Override - public String filterType() { - return POST_TYPE; - } - - @Override - public int filterOrder() { - return SEND_RESPONSE_FILTER_ORDER; - } - - @Override - public boolean shouldFilter() { - RequestContext context = RequestContext.getCurrentContext(); - return context.getThrowable() == null - && (!context.getZuulResponseHeaders().isEmpty() - || context.getResponseDataStream() != null - || context.getResponseBody() != null); - } - - @Override - public Object run() { - try { - addResponseHeaders(); - writeResponse(); - } - catch (Exception ex) { - ReflectionUtils.rethrowRuntimeException(ex); - } - return null; - } - - 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(); - if (servletResponse.getCharacterEncoding() == null) { // only set if not set - servletResponse.setCharacterEncoding("UTF-8"); - } - OutputStream outStream = servletResponse.getOutputStream(); - InputStream is = null; - try { - if (RequestContext.getCurrentContext().getResponseBody() != null) { - String body = RequestContext.getCurrentContext().getResponseBody(); - writeResponse( - new ByteArrayInputStream( - body.getBytes(servletResponse.getCharacterEncoding())), - outStream); - return; - } - boolean isGzipRequested = false; - final String requestEncoding = context.getRequest() - .getHeader(ZuulHeaders.ACCEPT_ENCODING); - - if (requestEncoding != null - && HTTPRequestUtils.getInstance().isGzipped(requestEncoding)) { - isGzipRequested = true; - } - is = context.getResponseDataStream(); - InputStream inputStream = is; - if (is != null) { - if (context.sendZuulResponse()) { - // if origin response is gzipped, and client has not requested gzip, - // decompress stream - // before sending to client - // else, stream gzip directly to client - if (context.getResponseGZipped() && !isGzipRequested) { - // If origin tell it's GZipped but the content is ZERO bytes, - // don't try to uncompress - final Long len = context.getOriginContentLength(); - if (len == null || len > 0) { - try { - inputStream = new GZIPInputStream(is); - } - catch (java.util.zip.ZipException ex) { - log.debug( - "gzip expected but not " - + "received assuming unencoded response " - + RequestContext.getCurrentContext() - .getRequest().getRequestURL() - .toString()); - inputStream = is; - } - } - else { - // Already done : inputStream = is; - } - } - else if (context.getResponseGZipped() && isGzipRequested) { - servletResponse.setHeader(ZuulHeaders.CONTENT_ENCODING, "gzip"); - } - writeResponse(inputStream, outStream); - } - } - } - finally { - /** - * We must ensure that the InputStream provided by our upstream pooling mechanism is ALWAYS closed - * even in the case of wrapped streams, which are supplied by pooled sources such as Apache's - * PoolingHttpClientConnectionManager. In that particular case, the underlying HTTP connection will - * be returned back to the connection pool iif either close() is explicitly called, a read - * error occurs, or the end of the underlying stream is reached. If, however a write error occurs, we will - * end up leaking a connection from the pool without an explicit close() - * - * @author Johannes Edmeier - */ - if (is != null) { - try { - is.close(); - } - catch (Exception ex) { - log.warn("Error while closing upstream input stream", ex); - } - } - - try { - Object zuulResponse = RequestContext.getCurrentContext() - .get("zuulResponse"); - if (zuulResponse instanceof Closeable) { - ((Closeable) zuulResponse).close(); - } - outStream.flush(); - // The container will close the stream for us - } - catch (IOException ex) { - log.warn("Error while sending response to client: " + ex.getMessage()); - } - } - } - - private void writeResponse(InputStream zin, OutputStream out) throws Exception { - byte[] bytes = buffers.get(); - int bytesRead = -1; - while ((bytesRead = zin.read(bytes)) != -1) { - out.write(bytes, 0, bytesRead); - } - } - - private void addResponseHeaders() { - RequestContext context = RequestContext.getCurrentContext(); - HttpServletResponse servletResponse = context.getResponse(); - if (this.zuulProperties.isIncludeDebugHeader()) { - @SuppressWarnings("unchecked") - List rd = (List) context.get(ROUTING_DEBUG_KEY); - if (rd != null) { - StringBuilder debugHeader = new StringBuilder(); - for (String it : rd) { - debugHeader.append("[[[" + it + "]]]"); - } - servletResponse.addHeader(X_ZUUL_DEBUG_HEADER, debugHeader.toString()); - } - } - List> zuulResponseHeaders = context.getZuulResponseHeaders(); - if (zuulResponseHeaders != null) { - for (Pair it : zuulResponseHeaders) { - servletResponse.addHeader(it.first(), it.second()); - } - } - // Only inserts Content-Length if origin provides it and origin response is not - // gzipped - if (this.zuulProperties.isSetContentLength()) { - Long contentLength = context.getOriginContentLength(); - if ( contentLength != null && !context.getResponseGZipped()) { - if(useServlet31) { - servletResponse.setContentLengthLong(contentLength); - } else { - //Try and set some kind of content length if we can safely convert the Long to an int - if (isLongSafe(contentLength)) { - servletResponse.setContentLength(contentLength.intValue()); - } - } - } - } - } - - private boolean isLongSafe(long value) { - return value <= Integer.MAX_VALUE && value >= Integer.MIN_VALUE; - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/DebugFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/DebugFilter.java deleted file mode 100644 index 3f43d69d..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/DebugFilter.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.pre; - -import javax.servlet.http.HttpServletRequest; - -import com.netflix.config.DynamicBooleanProperty; -import com.netflix.config.DynamicPropertyFactory; -import com.netflix.config.DynamicStringProperty; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.constants.ZuulConstants; -import com.netflix.zuul.context.RequestContext; - -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.DEBUG_FILTER_ORDER; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; - -/** - * Pre {@link ZuulFilter} that sets {@link RequestContext} debug attributes to true if - * the "debug" request parameter is set. - * - * @author Spencer Gibb - */ -public class DebugFilter extends ZuulFilter { - - private static final DynamicBooleanProperty ROUTING_DEBUG = DynamicPropertyFactory - .getInstance().getBooleanProperty(ZuulConstants.ZUUL_DEBUG_REQUEST, false); - - private static final DynamicStringProperty DEBUG_PARAMETER = DynamicPropertyFactory - .getInstance().getStringProperty(ZuulConstants.ZUUL_DEBUG_PARAMETER, "debug"); - - @Override - public String filterType() { - return PRE_TYPE; - } - - @Override - public int filterOrder() { - return DEBUG_FILTER_ORDER; - } - - @Override - public boolean shouldFilter() { - HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); - if ("true".equals(request.getParameter(DEBUG_PARAMETER.get()))) { - return true; - } - return ROUTING_DEBUG.get(); - } - - @Override - public Object run() { - RequestContext ctx = RequestContext.getCurrentContext(); - ctx.setDebugRouting(true); - ctx.setDebugRequest(true); - return null; - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/FormBodyWrapperFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/FormBodyWrapperFilter.java deleted file mode 100644 index 5f1fef74..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/FormBodyWrapperFilter.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.pre; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.lang.reflect.Field; - -import javax.servlet.ServletInputStream; -import javax.servlet.ServletRequest; -import javax.servlet.ServletRequestWrapper; -import javax.servlet.http.HttpServletRequest; - -import org.springframework.cloud.netflix.zuul.util.RequestContentDataExtractor; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpOutputMessage; -import org.springframework.http.InvalidMediaTypeException; -import org.springframework.http.MediaType; -import org.springframework.http.converter.FormHttpMessageConverter; -import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; -import org.springframework.util.Assert; -import org.springframework.util.MultiValueMap; -import org.springframework.util.ReflectionUtils; -import org.springframework.web.servlet.DispatcherServlet; - -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.http.HttpServletRequestWrapper; -import com.netflix.zuul.http.ServletInputStreamWrapper; - -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; - -/** - * Pre {@link ZuulFilter} that parses form data and reencodes it for downstream services - * - * @author Dave Syer - */ -public class FormBodyWrapperFilter extends ZuulFilter { - - private FormHttpMessageConverter formHttpMessageConverter; - private Field requestField; - private Field servletRequestField; - - public FormBodyWrapperFilter() { - this(new AllEncompassingFormHttpMessageConverter()); - } - - public FormBodyWrapperFilter(FormHttpMessageConverter formHttpMessageConverter) { - this.formHttpMessageConverter = formHttpMessageConverter; - this.requestField = ReflectionUtils.findField(HttpServletRequestWrapper.class, - "req", HttpServletRequest.class); - this.servletRequestField = ReflectionUtils.findField(ServletRequestWrapper.class, - "request", ServletRequest.class); - Assert.notNull(this.requestField, - "HttpServletRequestWrapper.req field not found"); - Assert.notNull(this.servletRequestField, - "ServletRequestWrapper.request field not found"); - this.requestField.setAccessible(true); - this.servletRequestField.setAccessible(true); - } - - @Override - public String filterType() { - return PRE_TYPE; - } - - @Override - public int filterOrder() { - return FORM_BODY_WRAPPER_FILTER_ORDER; - } - - @Override - public boolean shouldFilter() { - 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 form data and only for multipart data in a - // DispatcherServlet handler - try { - MediaType mediaType = MediaType.valueOf(contentType); - return MediaType.APPLICATION_FORM_URLENCODED.includes(mediaType) - || (isDispatcherServletRequest(request) - && MediaType.MULTIPART_FORM_DATA.includes(mediaType)); - } - catch (InvalidMediaTypeException ex) { - return false; - } - } - - private boolean isDispatcherServletRequest(HttpServletRequest request) { - return request.getAttribute( - DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null; - } - - @Override - public Object run() { - RequestContext ctx = RequestContext.getCurrentContext(); - HttpServletRequest request = ctx.getRequest(); - FormBodyRequestWrapper wrapper = null; - if (request instanceof HttpServletRequestWrapper) { - HttpServletRequest wrapped = (HttpServletRequest) ReflectionUtils - .getField(this.requestField, request); - wrapper = new FormBodyRequestWrapper(wrapped); - ReflectionUtils.setField(this.requestField, request, wrapper); - if (request instanceof ServletRequestWrapper) { - ReflectionUtils.setField(this.servletRequestField, request, wrapper); - } - } - else { - wrapper = new FormBodyRequestWrapper(request); - ctx.setRequest(wrapper); - } - if (wrapper != null) { - ctx.getZuulRequestHeaders().put("content-type", wrapper.getContentType()); - } - return null; - } - - private class FormBodyRequestWrapper extends Servlet30RequestWrapper { - - private HttpServletRequest request; - - private volatile byte[] contentData; - - private MediaType contentType; - - private int contentLength; - - public FormBodyRequestWrapper(HttpServletRequest request) { - super(request); - this.request = request; - } - - @Override - public String getContentType() { - if (this.contentData == null) { - buildContentData(); - } - return this.contentType.toString(); - } - - @Override - public int getContentLength() { - if (super.getContentLength() <= 0) { - return super.getContentLength(); - } - if (this.contentData == null) { - buildContentData(); - } - return this.contentLength; - } - - public long getContentLengthLong() { - return getContentLength(); - } - - @Override - public ServletInputStream getInputStream() throws IOException { - if (this.contentData == null) { - buildContentData(); - } - return new ServletInputStreamWrapper(this.contentData); - } - - private synchronized void buildContentData() { - if (this.contentData != null) { - return; - } - try { - MultiValueMap builder = RequestContentDataExtractor.extract(this.request); - FormHttpOutputMessage data = new FormHttpOutputMessage(); - - this.contentType = MediaType.valueOf(this.request.getContentType()); - data.getHeaders().setContentType(this.contentType); - FormBodyWrapperFilter.this.formHttpMessageConverter.write(builder, this.contentType, data); - // copy new content type including multipart boundary - this.contentType = data.getHeaders().getContentType(); - byte[] input = data.getInput(); - this.contentLength = input.length; - this.contentData = input; - } - catch (Exception e) { - throw new IllegalStateException("Cannot convert form data", e); - } - } - - private class FormHttpOutputMessage implements HttpOutputMessage { - - private HttpHeaders headers = new HttpHeaders(); - private ByteArrayOutputStream output = new ByteArrayOutputStream(); - - @Override - public HttpHeaders getHeaders() { - return this.headers; - } - - @Override - public OutputStream getBody() throws IOException { - return this.output; - } - - public byte[] getInput() throws IOException { - this.output.flush(); - return this.output.toByteArray(); - } - - } - - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/PreDecorationFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/PreDecorationFilter.java deleted file mode 100644 index 84653571..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/PreDecorationFilter.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.pre; - -import java.net.MalformedURLException; -import java.net.URL; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelper; -import org.springframework.cloud.netflix.zuul.filters.Route; -import org.springframework.cloud.netflix.zuul.filters.RouteLocator; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; -import org.springframework.cloud.netflix.zuul.util.RequestUtils; -import org.springframework.http.HttpHeaders; -import org.springframework.util.StringUtils; -import org.springframework.web.util.UrlPathHelper; - -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; - -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORWARD_LOCATION_PREFIX; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORWARD_TO_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.HTTPS_PORT; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.HTTPS_SCHEME; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.HTTP_PORT; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.HTTP_SCHEME; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PROXY_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.REQUEST_URI_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.RETRYABLE_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVICE_HEADER; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVICE_ID_HEADER; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVICE_ID_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.X_FORWARDED_FOR_HEADER; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.X_FORWARDED_HOST_HEADER; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.X_FORWARDED_PORT_HEADER; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.X_FORWARDED_PREFIX_HEADER; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.X_FORWARDED_PROTO_HEADER; - -/** - * Pre {@link ZuulFilter} that determines where and how to route based on the supplied {@link RouteLocator}. - * Also sets various proxy related headers for downstream requests. - */ -public class PreDecorationFilter extends ZuulFilter { - - private static final Log log = LogFactory.getLog(PreDecorationFilter.class); - - /** - * @deprecated use {@link FilterConstants#PRE_DECORATION_FILTER_ORDER} - */ - @Deprecated - public static final int FILTER_ORDER = PRE_DECORATION_FILTER_ORDER; - - private RouteLocator routeLocator; - - private String dispatcherServletPath; - - private ZuulProperties properties; - - private UrlPathHelper urlPathHelper = new UrlPathHelper(); - - private ProxyRequestHelper proxyRequestHelper; - - public PreDecorationFilter(RouteLocator routeLocator, String dispatcherServletPath, ZuulProperties properties, - ProxyRequestHelper proxyRequestHelper) { - this.routeLocator = routeLocator; - this.properties = properties; - this.urlPathHelper.setRemoveSemicolonContent(properties.isRemoveSemicolonContent()); - this.dispatcherServletPath = dispatcherServletPath; - this.proxyRequestHelper = proxyRequestHelper; - } - - @Override - public int filterOrder() { - return PRE_DECORATION_FILTER_ORDER; - } - - @Override - public String filterType() { - return PRE_TYPE; - } - - @Override - public boolean shouldFilter() { - RequestContext ctx = RequestContext.getCurrentContext(); - return !ctx.containsKey(FORWARD_TO_KEY) // a filter has already forwarded - && !ctx.containsKey(SERVICE_ID_KEY); // a filter has already determined serviceId - } - - @Override - public Object run() { - RequestContext ctx = RequestContext.getCurrentContext(); - final String requestURI = this.urlPathHelper.getPathWithinApplication(ctx.getRequest()); - Route route = this.routeLocator.getMatchingRoute(requestURI); - if (route != null) { - String location = route.getLocation(); - if (location != null) { - ctx.put(REQUEST_URI_KEY, route.getPath()); - ctx.put(PROXY_KEY, route.getId()); - if (!route.isCustomSensitiveHeaders()) { - this.proxyRequestHelper - .addIgnoredHeaders(this.properties.getSensitiveHeaders().toArray(new String[0])); - } - else { - this.proxyRequestHelper.addIgnoredHeaders(route.getSensitiveHeaders().toArray(new String[0])); - } - - if (route.getRetryable() != null) { - ctx.put(RETRYABLE_KEY, route.getRetryable()); - } - - if (location.startsWith(HTTP_SCHEME+":") || location.startsWith(HTTPS_SCHEME+":")) { - ctx.setRouteHost(getUrl(location)); - ctx.addOriginResponseHeader(SERVICE_HEADER, location); - } - else if (location.startsWith(FORWARD_LOCATION_PREFIX)) { - ctx.set(FORWARD_TO_KEY, - StringUtils.cleanPath(location.substring(FORWARD_LOCATION_PREFIX.length()) + route.getPath())); - ctx.setRouteHost(null); - return null; - } - else { - // set serviceId for use in filters.route.RibbonRequest - ctx.set(SERVICE_ID_KEY, location); - ctx.setRouteHost(null); - ctx.addOriginResponseHeader(SERVICE_ID_HEADER, location); - } - if (this.properties.isAddProxyHeaders()) { - addProxyHeaders(ctx, route); - String xforwardedfor = ctx.getRequest().getHeader(X_FORWARDED_FOR_HEADER); - String remoteAddr = ctx.getRequest().getRemoteAddr(); - if (xforwardedfor == null) { - xforwardedfor = remoteAddr; - } - else if (!xforwardedfor.contains(remoteAddr)) { // Prevent duplicates - xforwardedfor += ", " + remoteAddr; - } - ctx.addZuulRequestHeader(X_FORWARDED_FOR_HEADER, xforwardedfor); - } - if (this.properties.isAddHostHeader()) { - ctx.addZuulRequestHeader(HttpHeaders.HOST, toHostHeader(ctx.getRequest())); - } - } - } - else { - log.warn("No route found for uri: " + requestURI); - - String fallBackUri = requestURI; - String fallbackPrefix = this.dispatcherServletPath; // default fallback - // servlet is - // DispatcherServlet - - if (RequestUtils.isZuulServletRequest()) { - // remove the Zuul servletPath from the requestUri - log.debug("zuulServletPath=" + this.properties.getServletPath()); - fallBackUri = fallBackUri.replaceFirst(this.properties.getServletPath(), ""); - log.debug("Replaced Zuul servlet path:" + fallBackUri); - } - else { - // remove the DispatcherServlet servletPath from the requestUri - log.debug("dispatcherServletPath=" + this.dispatcherServletPath); - fallBackUri = fallBackUri.replaceFirst(this.dispatcherServletPath, ""); - log.debug("Replaced DispatcherServlet servlet path:" + fallBackUri); - } - if (!fallBackUri.startsWith("/")) { - fallBackUri = "/" + fallBackUri; - } - String forwardURI = fallbackPrefix + fallBackUri; - forwardURI = forwardURI.replaceAll("//", "/"); - ctx.set(FORWARD_TO_KEY, forwardURI); - } - return null; - } - - private void addProxyHeaders(RequestContext ctx, Route route) { - HttpServletRequest request = ctx.getRequest(); - String host = toHostHeader(request); - String port = String.valueOf(request.getServerPort()); - String proto = request.getScheme(); - if (hasHeader(request, X_FORWARDED_HOST_HEADER)) { - host = request.getHeader(X_FORWARDED_HOST_HEADER) + "," + host; - } - if (!hasHeader(request, X_FORWARDED_PORT_HEADER)) { - if (hasHeader(request, X_FORWARDED_PROTO_HEADER)) { - StringBuilder builder = new StringBuilder(); - for (String previous : StringUtils.commaDelimitedListToStringArray(request.getHeader(X_FORWARDED_PROTO_HEADER))) { - if (builder.length()>0) { - builder.append(","); - } - builder.append(HTTPS_SCHEME.equals(previous) ? HTTPS_PORT : HTTP_PORT); - } - builder.append(",").append(port); - port = builder.toString(); - } - } else { - port = request.getHeader(X_FORWARDED_PORT_HEADER) + "," + port; - } - if (hasHeader(request, X_FORWARDED_PROTO_HEADER)) { - proto = request.getHeader(X_FORWARDED_PROTO_HEADER) + "," + proto; - } - ctx.addZuulRequestHeader(X_FORWARDED_HOST_HEADER, host); - ctx.addZuulRequestHeader(X_FORWARDED_PORT_HEADER, port); - ctx.addZuulRequestHeader(X_FORWARDED_PROTO_HEADER, proto); - addProxyPrefix(ctx, route); - } - - private boolean hasHeader(HttpServletRequest request, String name) { - return StringUtils.hasLength(request.getHeader(name)); - } - - private void addProxyPrefix(RequestContext ctx, Route route) { - String forwardedPrefix = ctx.getRequest().getHeader(X_FORWARDED_PREFIX_HEADER); - String contextPath = ctx.getRequest().getContextPath(); - String prefix = StringUtils.hasLength(forwardedPrefix) ? forwardedPrefix - : (StringUtils.hasLength(contextPath) ? contextPath : null); - if (StringUtils.hasText(route.getPrefix())) { - StringBuilder newPrefixBuilder = new StringBuilder(); - if (prefix != null) { - if (prefix.endsWith("/") && route.getPrefix().startsWith("/")) { - newPrefixBuilder.append(prefix, 0, prefix.length() - 1); - } - else { - newPrefixBuilder.append(prefix); - } - } - newPrefixBuilder.append(route.getPrefix()); - prefix = newPrefixBuilder.toString(); - } - if (prefix != null) { - ctx.addZuulRequestHeader(X_FORWARDED_PREFIX_HEADER, prefix); - } - } - - private String toHostHeader(HttpServletRequest request) { - int port = request.getServerPort(); - if ((port == HTTP_PORT && HTTP_SCHEME.equals(request.getScheme())) - || (port == HTTPS_PORT && HTTPS_SCHEME.equals(request.getScheme()))) { - return request.getServerName(); - } - else { - return request.getServerName() + ":" + port; - } - } - - private URL getUrl(String target) { - try { - return new URL(target); - } - catch (MalformedURLException ex) { - throw new IllegalStateException("Target URL is malformed", ex); - } - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/Servlet30RequestWrapper.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/Servlet30RequestWrapper.java deleted file mode 100644 index 32fdff0e..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/Servlet30RequestWrapper.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.pre; - -import com.netflix.zuul.http.HttpServletRequestWrapper; - -import javax.servlet.http.HttpServletRequest; - -/** - * A Servlet 3.0 compliant wrapper. - */ -class Servlet30RequestWrapper extends HttpServletRequestWrapper { - private HttpServletRequest request; - - Servlet30RequestWrapper(HttpServletRequest request) { - super(request); - this.request = request; - } - - /** - * There is a bug in zuul 1.2.2 where HttpServletRequestWrapper.getRequest returns a wrapped request rather than the raw one. - * @return the original HttpServletRequest - */ - @Override - public HttpServletRequest getRequest() { - return this.request; - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/Servlet30WrapperFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/Servlet30WrapperFilter.java deleted file mode 100644 index b7516415..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/Servlet30WrapperFilter.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.pre; - -import java.lang.reflect.Field; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.cloud.netflix.zuul.util.RequestUtils; -import org.springframework.util.Assert; -import org.springframework.util.ReflectionUtils; - -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.http.HttpServletRequestWrapper; - -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_30_WRAPPER_FILTER_ORDER; - -/** - * Pre {@link ZuulFilter} that wraps requests in a Servlet 3.0 compliant wrapper. - * Zuul's default wrapper is only Servlet 2.5 compliant. - * @author Spencer Gibb - */ -public class Servlet30WrapperFilter extends ZuulFilter { - - private Field requestField = null; - - public Servlet30WrapperFilter() { - this.requestField = ReflectionUtils.findField(HttpServletRequestWrapper.class, - "req", HttpServletRequest.class); - Assert.notNull(this.requestField, - "HttpServletRequestWrapper.req field not found"); - this.requestField.setAccessible(true); - } - - protected Field getRequestField() { - return this.requestField; - } - - @Override - public String filterType() { - return PRE_TYPE; - } - - @Override - public int filterOrder() { - return SERVLET_30_WRAPPER_FILTER_ORDER; - } - - @Override - public boolean shouldFilter() { - return true; // TODO: only if in servlet 3.0 env - } - - @Override - public Object run() { - RequestContext ctx = RequestContext.getCurrentContext(); - HttpServletRequest request = ctx.getRequest(); - if (request instanceof HttpServletRequestWrapper) { - request = (HttpServletRequest) ReflectionUtils.getField(this.requestField, - request); - ctx.setRequest(new Servlet30RequestWrapper(request)); - } - else if (RequestUtils.isDispatcherServletRequest()) { - // If it's going through the dispatcher we need to buffer the body - ctx.setRequest(new Servlet30RequestWrapper(request)); - } - return null; - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/ServletDetectionFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/ServletDetectionFilter.java deleted file mode 100644 index 7dae24ec..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/ServletDetectionFilter.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.pre; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.web.servlet.DispatcherServlet; - -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.http.HttpServletRequestWrapper; -import com.netflix.zuul.http.ZuulServlet; - -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.IS_DISPATCHER_SERVLET_REQUEST_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER; - -/** - * Detects whether a request is ran through the {@link DispatcherServlet} or {@link ZuulServlet}. - * The purpose was to detect this up-front at the very beginning of Zuul filter processing - * and rely on this information in all filters. - * RequestContext is used such that the information is accessible to classes - * which do not have a request reference. - * @author Adrian Ivan - */ -public class ServletDetectionFilter extends ZuulFilter { - - public ServletDetectionFilter() { - } - - @Override - public String filterType() { - return PRE_TYPE; - } - - /** - * Must run before other filters that rely on the difference between - * DispatcherServlet and ZuulServlet. - */ - @Override - public int filterOrder() { - return SERVLET_DETECTION_FILTER_ORDER; - } - - @Override - public boolean shouldFilter() { - return true; - } - - @Override - public Object run() { - RequestContext ctx = RequestContext.getCurrentContext(); - HttpServletRequest request = ctx.getRequest(); - if (!(request instanceof HttpServletRequestWrapper) - && isDispatcherServletRequest(request)) { - ctx.set(IS_DISPATCHER_SERVLET_REQUEST_KEY, true); - } else { - ctx.set(IS_DISPATCHER_SERVLET_REQUEST_KEY, false); - } - - return null; - } - - private boolean isDispatcherServletRequest(HttpServletRequest request) { - return request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null; - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/FallbackProvider.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/FallbackProvider.java deleted file mode 100644 index 38047924..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/FallbackProvider.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.route; - -import org.springframework.http.client.ClientHttpResponse; - -/** - * Provides fallback when a failure occurs on a route. - * - * @author Ryan Baxter - * @author Dominik Mostek - */ -public interface FallbackProvider { - - /** - * The route this fallback will be used for. - * @return The route the fallback will be used for. - */ - public String getRoute(); - - /** - * Provides a fallback response based on the cause of the failed execution. - * - * @param route The route the fallback is for - * @param cause cause of the main method failure, may be null - * @return the fallback response - */ - ClientHttpResponse fallbackResponse(String route, Throwable cause); -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommand.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommand.java deleted file mode 100644 index 72f5dff0..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommand.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route; - -import java.io.InputStream; -import java.net.URI; -import java.util.List; - -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibbonCommand; -import org.springframework.http.HttpMethod; -import org.springframework.util.MultiValueMap; -import com.netflix.client.config.IClientConfig; -import com.netflix.client.http.HttpRequest; -import com.netflix.client.http.HttpResponse; -import com.netflix.niws.client.http.RestClient; - -import static org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer.Runner.customize; - -/** - * Hystrix wrapper around Eureka Ribbon command - * - * see original - */ -@SuppressWarnings("deprecation") -public class RestClientRibbonCommand extends AbstractRibbonCommand { - - public RestClientRibbonCommand(String commandKey, RestClient client, - RibbonCommandContext context, ZuulProperties zuulProperties) { - super(commandKey, client, context, zuulProperties); - } - - public RestClientRibbonCommand(String commandKey, RestClient client, - RibbonCommandContext context, ZuulProperties zuulProperties, - FallbackProvider zuulFallbackProvider) { - super(commandKey, client, context, zuulProperties, zuulFallbackProvider); - } - - public RestClientRibbonCommand(String commandKey, RestClient client, - RibbonCommandContext context, ZuulProperties zuulProperties, - FallbackProvider zuulFallbackProvider, IClientConfig config) { - super(commandKey, client, context, zuulProperties, zuulFallbackProvider, config); - } - - @Deprecated - public RestClientRibbonCommand(String commandKey, RestClient restClient, - HttpRequest.Verb verb, String uri, Boolean retryable, - MultiValueMap headers, MultiValueMap params, - InputStream requestEntity) { - this(commandKey, restClient, new RibbonCommandContext(commandKey, verb.verb(), - uri, retryable, headers, params, requestEntity), new ZuulProperties()); - } - - @Override - protected HttpRequest createRequest() throws Exception { - final InputStream requestEntity; - // ApacheHttpClient4Handler does not support body in delete requests - if (getContext().getMethod().equalsIgnoreCase(HttpMethod.DELETE.toString())) { - requestEntity = null; - } else { - requestEntity = this.context.getRequestEntity(); - } - - HttpRequest.Builder builder = HttpRequest.newBuilder() - .verb(getVerb(this.context.getMethod())).uri(this.context.uri()) - .entity(requestEntity); - - if (this.context.getRetryable() != null) { - builder.setRetriable(this.context.getRetryable()); - } - - for (String name : this.context.getHeaders().keySet()) { - List values = this.context.getHeaders().get(name); - for (String value : values) { - builder.header(name, value); - } - } - for (String name : this.context.getParams().keySet()) { - List values = this.context.getParams().get(name); - for (String value : values) { - builder.queryParams(name, value); - } - } - - customizeRequest(builder); - - return builder.build(); - } - - protected void customizeRequest(HttpRequest.Builder requestBuilder) { - customize(this.context.getRequestCustomizers(), requestBuilder); - } - - @Deprecated - public URI getUri() { - return this.context.uri(); - } - - @SuppressWarnings("unused") - @Deprecated - public HttpRequest.Verb getVerb() { - return getVerb(this.context.getVerb()); - } - - protected static HttpRequest.Verb getVerb(String method) { - if (method == null) - return HttpRequest.Verb.GET; - try { - return HttpRequest.Verb.valueOf(method.toUpperCase()); - } - catch (IllegalArgumentException e) { - return HttpRequest.Verb.GET; - } - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommandFactory.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommandFactory.java deleted file mode 100644 index c190705f..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommandFactory.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route; - -import java.util.Collections; -import java.util.Set; - -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibbonCommandFactory; - -import com.netflix.client.http.HttpRequest; -import com.netflix.niws.client.http.RestClient; - -/** - * @author Spencer Gibb - * @author Ryan Baxter - */ -public class RestClientRibbonCommandFactory extends AbstractRibbonCommandFactory { - - private SpringClientFactory clientFactory; - - private ZuulProperties zuulProperties; - - public RestClientRibbonCommandFactory(SpringClientFactory clientFactory) { - this(clientFactory, new ZuulProperties(), Collections.emptySet()); - } - - public RestClientRibbonCommandFactory(SpringClientFactory clientFactory, - ZuulProperties zuulProperties, - Set zuulFallbackProviders) { - super(zuulFallbackProviders); - this.clientFactory = clientFactory; - this.zuulProperties = zuulProperties; - } - - @Override - @SuppressWarnings("deprecation") - public RestClientRibbonCommand create(RibbonCommandContext context) { - String serviceId = context.getServiceId(); - FallbackProvider fallbackProvider = getFallbackProvider(serviceId); - RestClient restClient = this.clientFactory.getClient(serviceId, - RestClient.class); - return new RestClientRibbonCommand(context.getServiceId(), restClient, context, - this.zuulProperties, fallbackProvider, clientFactory.getClientConfig(serviceId)); - } - - public SpringClientFactory getClientFactory() { - return clientFactory; - } - - public void setZuulProperties(ZuulProperties zuulProperties) { - this.zuulProperties = zuulProperties; - } - - protected static HttpRequest.Verb getVerb(String method) { - return RestClientRibbonCommand.getVerb(method); - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonCommand.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonCommand.java deleted file mode 100644 index 519a0f84..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonCommand.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.route; - -import com.netflix.hystrix.HystrixExecutable; -import org.springframework.http.client.ClientHttpResponse; - -/** - * @author Spencer Gibb - */ -public interface RibbonCommand extends HystrixExecutable { -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonCommandFactory.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonCommandFactory.java deleted file mode 100644 index 48cbaf49..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonCommandFactory.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.route; - -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; - -/** - * @author Spencer Gibb - */ -public interface RibbonCommandFactory { - - T create(RibbonCommandContext context); - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilter.java deleted file mode 100644 index 5d4d8285..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilter.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.route; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer; -import org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelper; -import org.springframework.cloud.netflix.zuul.util.ZuulRuntimeException; -import org.springframework.http.HttpStatus; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.util.MultiValueMap; - -import com.netflix.client.ClientException; -import com.netflix.hystrix.exception.HystrixRuntimeException; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.exception.ZuulException; - -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.REQUEST_ENTITY_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.RETRYABLE_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.RIBBON_ROUTING_FILTER_ORDER; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ROUTE_TYPE; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVICE_ID_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.LOAD_BALANCER_KEY; - -/** - * Route {@link ZuulFilter} that uses Ribbon, Hystrix and pluggable http clients to send requests. - * ServiceIds are found in the {@link RequestContext} attribute {@link org.springframework.cloud.netflix.zuul.filters.support.FilterConstants#SERVICE_ID_KEY}. - * - * @author Spencer Gibb - * @author Dave Syer - * @author Ryan Baxter - */ -public class RibbonRoutingFilter extends ZuulFilter { - - private static final Log log = LogFactory.getLog(RibbonRoutingFilter.class); - - protected ProxyRequestHelper helper; - protected RibbonCommandFactory ribbonCommandFactory; - protected List requestCustomizers; - private boolean useServlet31 = true; - - public RibbonRoutingFilter(ProxyRequestHelper helper, - RibbonCommandFactory ribbonCommandFactory, - List requestCustomizers) { - this.helper = helper; - this.ribbonCommandFactory = ribbonCommandFactory; - this.requestCustomizers = requestCustomizers; - // To support Servlet API 3.1 we need to check if getContentLengthLong exists - // Spring 5 minimum support is 3.0, so this stays - try { - HttpServletRequest.class.getMethod("getContentLengthLong"); - } catch(NoSuchMethodException e) { - useServlet31 = false; - } - } - - public RibbonRoutingFilter(RibbonCommandFactory ribbonCommandFactory) { - this(new ProxyRequestHelper(), ribbonCommandFactory, null); - } - - /* for testing */ boolean isUseServlet31() { - return useServlet31; - } - - @Override - public String filterType() { - return ROUTE_TYPE; - } - - @Override - public int filterOrder() { - return RIBBON_ROUTING_FILTER_ORDER; - } - - @Override - public boolean shouldFilter() { - RequestContext ctx = RequestContext.getCurrentContext(); - return (ctx.getRouteHost() == null && ctx.get(SERVICE_ID_KEY) != null - && ctx.sendZuulResponse()); - } - - @Override - public Object run() { - RequestContext context = RequestContext.getCurrentContext(); - this.helper.addIgnoredHeaders(); - try { - RibbonCommandContext commandContext = buildCommandContext(context); - ClientHttpResponse response = forward(commandContext); - setResponse(response); - return response; - } - catch (ZuulException ex) { - throw new ZuulRuntimeException(ex); - } - catch (Exception ex) { - throw new ZuulRuntimeException(ex); - } - } - - protected RibbonCommandContext buildCommandContext(RequestContext context) { - HttpServletRequest request = context.getRequest(); - - MultiValueMap headers = this.helper - .buildZuulRequestHeaders(request); - MultiValueMap params = this.helper - .buildZuulRequestQueryParams(request); - String verb = getVerb(request); - InputStream requestEntity = getRequestBody(request); - if (request.getContentLength() < 0 && !verb.equalsIgnoreCase("GET")) { - context.setChunkedRequestBody(); - } - - String serviceId = (String) context.get(SERVICE_ID_KEY); - Boolean retryable = (Boolean) context.get(RETRYABLE_KEY); - Object loadBalancerKey = context.get(LOAD_BALANCER_KEY); - - String uri = this.helper.buildZuulRequestURI(request); - - // remove double slashes - uri = uri.replace("//", "/"); - - long contentLength = useServlet31 ? request.getContentLengthLong(): request.getContentLength(); - - return new RibbonCommandContext(serviceId, verb, uri, retryable, headers, params, - requestEntity, this.requestCustomizers, contentLength, loadBalancerKey); - } - - protected ClientHttpResponse forward(RibbonCommandContext context) throws Exception { - Map info = this.helper.debug(context.getMethod(), - context.getUri(), context.getHeaders(), context.getParams(), - context.getRequestEntity()); - - RibbonCommand command = this.ribbonCommandFactory.create(context); - try { - ClientHttpResponse response = command.execute(); - this.helper.appendDebug(info, response.getRawStatusCode(), response.getHeaders()); - return response; - } - catch (HystrixRuntimeException ex) { - return handleException(info, ex); - } - - } - - protected ClientHttpResponse handleException(Map info, - HystrixRuntimeException ex) throws ZuulException { - int statusCode = HttpStatus.INTERNAL_SERVER_ERROR.value(); - Throwable cause = ex; - String message = ex.getFailureType().toString(); - - ClientException clientException = findClientException(ex); - if (clientException == null) { - clientException = findClientException(ex.getFallbackException()); - } - - if (clientException != null) { - if (clientException - .getErrorType() == ClientException.ErrorType.SERVER_THROTTLED) { - statusCode = HttpStatus.SERVICE_UNAVAILABLE.value(); - } - cause = clientException; - message = clientException.getErrorType().toString(); - } - info.put("status", String.valueOf(statusCode)); - throw new ZuulException(cause, "Forwarding error", statusCode, message); - } - - protected ClientException findClientException(Throwable t) { - if (t == null) { - return null; - } - if (t instanceof ClientException) { - return (ClientException) t; - } - return findClientException(t.getCause()); - } - - protected InputStream getRequestBody(HttpServletRequest request) { - InputStream requestEntity = null; - try { - requestEntity = (InputStream) RequestContext.getCurrentContext() - .get(REQUEST_ENTITY_KEY); - if (requestEntity == null) { - requestEntity = request.getInputStream(); - } - } - catch (IOException ex) { - log.error("Error during getRequestBody", ex); - } - return requestEntity; - } - - protected String getVerb(HttpServletRequest request) { - String method = request.getMethod(); - if (method == null) { - return "GET"; - } - return method; - } - - protected void setResponse(ClientHttpResponse resp) - throws ClientException, IOException { - RequestContext.getCurrentContext().set("zuulResponse", resp); - this.helper.setResponse(resp.getRawStatusCode(), - resp.getBody() == null ? null : resp.getBody(), resp.getHeaders()); - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/SendForwardFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/SendForwardFilter.java deleted file mode 100644 index e8a31d03..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/SendForwardFilter.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.route; - -import javax.servlet.RequestDispatcher; - -import org.springframework.util.ReflectionUtils; - -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; - -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORWARD_TO_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ROUTE_TYPE; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SEND_FORWARD_FILTER_ORDER; - -/** - * Route {@link ZuulFilter} that forwards requests using the {@link RequestDispatcher}. - * Forwarding location is located in the {@link RequestContext} attribute {@link org.springframework.cloud.netflix.zuul.filters.support.FilterConstants#FORWARD_TO_KEY}. - * Useful for forwarding to endpoints in the current application. - * - * @author Dave Syer - */ -public class SendForwardFilter extends ZuulFilter { - - protected static final String SEND_FORWARD_FILTER_RAN = "sendForwardFilter.ran"; - - @Override - public String filterType() { - return ROUTE_TYPE; - } - - @Override - public int filterOrder() { - return SEND_FORWARD_FILTER_ORDER; - } - - @Override - public boolean shouldFilter() { - RequestContext ctx = RequestContext.getCurrentContext(); - return ctx.containsKey(FORWARD_TO_KEY) - && !ctx.getBoolean(SEND_FORWARD_FILTER_RAN, false); - } - - @Override - public Object run() { - try { - RequestContext ctx = RequestContext.getCurrentContext(); - String path = (String) ctx.get(FORWARD_TO_KEY); - RequestDispatcher dispatcher = ctx.getRequest().getRequestDispatcher(path); - if (dispatcher != null) { - ctx.set(SEND_FORWARD_FILTER_RAN, true); - if (!ctx.getResponse().isCommitted()) { - dispatcher.forward(ctx.getRequest(), ctx.getResponse()); - ctx.getResponse().flushBuffer(); - } - } - } - catch (Exception ex) { - ReflectionUtils.rethrowRuntimeException(ex); - } - return null; - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilter.java deleted file mode 100644 index 54555017..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilter.java +++ /dev/null @@ -1,384 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.route; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.Header; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.client.config.CookieSpecs; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.conn.HttpClientConnectionManager; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.InputStreamEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.message.BasicHeader; -import org.apache.http.message.BasicHttpEntityEnclosingRequest; -import org.apache.http.message.BasicHttpRequest; -import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory; -import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory; -import org.springframework.cloud.context.environment.EnvironmentChangeEvent; -import org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelper; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.Host; -import org.springframework.cloud.netflix.zuul.util.ZuulRuntimeException; -import org.springframework.context.event.EventListener; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.util.StringUtils; - -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; - -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.REQUEST_ENTITY_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ROUTE_TYPE; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SIMPLE_HOST_ROUTING_FILTER_ORDER; - -/** - * Route {@link ZuulFilter} that sends requests to predetermined URLs via apache - * {@link HttpClient}. URLs are found in {@link RequestContext#getRouteHost()}. - * - * @author Spencer Gibb - * @author Dave Syer - * @author Bilal Alp - * @author Gang Li - */ -public class SimpleHostRoutingFilter extends ZuulFilter { - - private static final Log log = LogFactory.getLog(SimpleHostRoutingFilter.class); - - private final Timer connectionManagerTimer = new Timer( - "SimpleHostRoutingFilter.connectionManagerTimer", true); - - private boolean sslHostnameValidationEnabled; - private boolean forceOriginalQueryStringEncoding; - - private ProxyRequestHelper helper; - private Host hostProperties; - private ApacheHttpClientConnectionManagerFactory connectionManagerFactory; - private ApacheHttpClientFactory httpClientFactory; - private HttpClientConnectionManager connectionManager; - private CloseableHttpClient httpClient; - private boolean customHttpClient = false; - - @EventListener - public void onPropertyChange(EnvironmentChangeEvent event) { - if(!customHttpClient) { - boolean createNewClient = false; - - for (String key : event.getKeys()) { - if (key.startsWith("zuul.host.")) { - createNewClient = true; - break; - } - } - - if (createNewClient) { - try { - SimpleHostRoutingFilter.this.httpClient.close(); - } catch (IOException ex) { - log.error("error closing client", ex); - } - SimpleHostRoutingFilter.this.httpClient = newClient(); - } - } - } - - public SimpleHostRoutingFilter(ProxyRequestHelper helper, ZuulProperties properties, - ApacheHttpClientConnectionManagerFactory connectionManagerFactory, - ApacheHttpClientFactory httpClientFactory) { - this.helper = helper; - this.hostProperties = properties.getHost(); - this.sslHostnameValidationEnabled = properties.isSslHostnameValidationEnabled(); - this.forceOriginalQueryStringEncoding = properties - .isForceOriginalQueryStringEncoding(); - this.connectionManagerFactory = connectionManagerFactory; - this.httpClientFactory = httpClientFactory; - } - - public SimpleHostRoutingFilter(ProxyRequestHelper helper, ZuulProperties properties, - CloseableHttpClient httpClient) { - this.helper = helper; - this.hostProperties = properties.getHost(); - this.sslHostnameValidationEnabled = properties.isSslHostnameValidationEnabled(); - this.forceOriginalQueryStringEncoding = properties - .isForceOriginalQueryStringEncoding(); - this.httpClient = httpClient; - this.customHttpClient = true; - } - - @PostConstruct - private void initialize() { - if(!customHttpClient) { - this.connectionManager = connectionManagerFactory.newConnectionManager( - !this.sslHostnameValidationEnabled, - this.hostProperties.getMaxTotalConnections(), - this.hostProperties.getMaxPerRouteConnections(), - this.hostProperties.getTimeToLive(), this.hostProperties.getTimeUnit(), - null); - this.httpClient = newClient(); - this.connectionManagerTimer.schedule(new TimerTask() { - @Override - public void run() { - if (SimpleHostRoutingFilter.this.connectionManager == null) { - return; - } - SimpleHostRoutingFilter.this.connectionManager.closeExpiredConnections(); - } - }, 30000, 5000); - } - } - - @PreDestroy - public void stop() { - this.connectionManagerTimer.cancel(); - } - - @Override - public String filterType() { - return ROUTE_TYPE; - } - - @Override - public int filterOrder() { - return SIMPLE_HOST_ROUTING_FILTER_ORDER; - } - - @Override - public boolean shouldFilter() { - return RequestContext.getCurrentContext().getRouteHost() != null - && RequestContext.getCurrentContext().sendZuulResponse(); - } - - @Override - public Object run() { - RequestContext context = RequestContext.getCurrentContext(); - HttpServletRequest request = context.getRequest(); - MultiValueMap headers = this.helper - .buildZuulRequestHeaders(request); - MultiValueMap params = this.helper - .buildZuulRequestQueryParams(request); - String verb = getVerb(request); - InputStream requestEntity = getRequestBody(request); - if (request.getContentLength() < 0) { - context.setChunkedRequestBody(); - } - - String uri = this.helper.buildZuulRequestURI(request); - this.helper.addIgnoredHeaders(); - - try { - CloseableHttpResponse response = forward(this.httpClient, verb, uri, request, - headers, params, requestEntity); - setResponse(response); - } - catch (Exception ex) { - throw new ZuulRuntimeException(ex); - } - return null; - } - - protected HttpClientConnectionManager getConnectionManager() { - return connectionManager; - } - - protected CloseableHttpClient newClient() { - final RequestConfig requestConfig = RequestConfig.custom() - .setSocketTimeout(this.hostProperties.getSocketTimeoutMillis()) - .setConnectTimeout(this.hostProperties.getConnectTimeoutMillis()) - .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); - return httpClientFactory.createBuilder(). - setDefaultRequestConfig(requestConfig). - setConnectionManager(this.connectionManager).disableRedirectHandling().build(); - } - - private CloseableHttpResponse forward(CloseableHttpClient httpclient, String verb, - String uri, HttpServletRequest request, MultiValueMap headers, - MultiValueMap params, InputStream requestEntity) - throws Exception { - Map info = this.helper.debug(verb, uri, headers, params, - requestEntity); - URL host = RequestContext.getCurrentContext().getRouteHost(); - HttpHost httpHost = getHttpHost(host); - uri = StringUtils.cleanPath((host.getPath() + uri).replaceAll("/{2,}", "/")); - int contentLength = request.getContentLength(); - - ContentType contentType = null; - - if (request.getContentType() != null) { - contentType = ContentType.parse(request.getContentType()); - } - - InputStreamEntity entity = new InputStreamEntity(requestEntity, contentLength, - contentType); - - HttpRequest httpRequest = buildHttpRequest(verb, uri, entity, headers, params, - request); - try { - log.debug(httpHost.getHostName() + " " + httpHost.getPort() + " " - + httpHost.getSchemeName()); - CloseableHttpResponse zuulResponse = forwardRequest(httpclient, httpHost, - httpRequest); - this.helper.appendDebug(info, zuulResponse.getStatusLine().getStatusCode(), - revertHeaders(zuulResponse.getAllHeaders())); - return zuulResponse; - } - finally { - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - // httpclient.getConnectionManager().shutdown(); - } - } - - protected HttpRequest buildHttpRequest(String verb, String uri, - InputStreamEntity entity, MultiValueMap headers, - MultiValueMap params, HttpServletRequest request) { - HttpRequest httpRequest; - String uriWithQueryString = uri + (this.forceOriginalQueryStringEncoding - ? getEncodedQueryString(request) : this.helper.getQueryString(params)); - - switch (verb.toUpperCase()) { - case "POST": - HttpPost httpPost = new HttpPost(uriWithQueryString); - httpRequest = httpPost; - httpPost.setEntity(entity); - break; - case "PUT": - HttpPut httpPut = new HttpPut(uriWithQueryString); - httpRequest = httpPut; - httpPut.setEntity(entity); - break; - case "PATCH": - HttpPatch httpPatch = new HttpPatch(uriWithQueryString); - httpRequest = httpPatch; - httpPatch.setEntity(entity); - break; - case "DELETE": - BasicHttpEntityEnclosingRequest entityRequest = new BasicHttpEntityEnclosingRequest( - verb, uriWithQueryString); - httpRequest = entityRequest; - entityRequest.setEntity(entity); - break; - default: - httpRequest = new BasicHttpRequest(verb, uriWithQueryString); - log.debug(uriWithQueryString); - } - - httpRequest.setHeaders(convertHeaders(headers)); - return httpRequest; - } - - private String getEncodedQueryString(HttpServletRequest request) { - String query = request.getQueryString(); - return (query != null) ? "?" + query : ""; - } - - private MultiValueMap revertHeaders(Header[] headers) { - MultiValueMap map = new LinkedMultiValueMap<>(); - for (Header header : headers) { - String name = header.getName(); - if (!map.containsKey(name)) { - map.put(name, new ArrayList()); - } - map.get(name).add(header.getValue()); - } - return map; - } - - private Header[] convertHeaders(MultiValueMap headers) { - List

list = new ArrayList<>(); - for (String name : headers.keySet()) { - for (String value : headers.get(name)) { - list.add(new BasicHeader(name, value)); - } - } - return list.toArray(new BasicHeader[0]); - } - - private CloseableHttpResponse forwardRequest(CloseableHttpClient httpclient, - HttpHost httpHost, HttpRequest httpRequest) throws IOException { - return httpclient.execute(httpHost, httpRequest); - } - - private HttpHost getHttpHost(URL host) { - HttpHost httpHost = new HttpHost(host.getHost(), host.getPort(), - host.getProtocol()); - return httpHost; - } - - protected InputStream getRequestBody(HttpServletRequest request) { - InputStream requestEntity = null; - try { - requestEntity = (InputStream) RequestContext.getCurrentContext().get(REQUEST_ENTITY_KEY); - if (requestEntity == null) { - requestEntity = request.getInputStream(); - } - } - catch (IOException ex) { - log.error("error during getRequestBody", ex); - } - return requestEntity; - } - - private String getVerb(HttpServletRequest request) { - String sMethod = request.getMethod(); - return sMethod.toUpperCase(); - } - - private void setResponse(HttpResponse response) throws IOException { - RequestContext.getCurrentContext().set("zuulResponse", response); - this.helper.setResponse(response.getStatusLine().getStatusCode(), - response.getEntity() == null ? null : response.getEntity().getContent(), - revertHeaders(response.getAllHeaders())); - } - - /** - * Add header names to exclude from proxied response in the current request. - * @param names - */ - protected void addIgnoredHeaders(String... names) { - this.helper.addIgnoredHeaders(names); - } - - /** - * Determines whether the filter enables the validation for ssl hostnames. - * @return true if enabled - */ - boolean isSslHostnameValidationEnabled() { - return this.sslHostnameValidationEnabled; - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommand.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommand.java deleted file mode 100644 index ca24c4ee..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommand.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.apache; - -import org.springframework.cloud.netflix.ribbon.apache.RibbonApacheHttpRequest; -import org.springframework.cloud.netflix.ribbon.apache.RibbonApacheHttpResponse; -import org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; -import org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibbonCommand; -import com.netflix.client.config.IClientConfig; - -/** - * @author Spencer Gibb - * @author Ryan Baxter - */ -public class HttpClientRibbonCommand extends AbstractRibbonCommand { - - public HttpClientRibbonCommand(final String commandKey, - final RibbonLoadBalancingHttpClient client, - final RibbonCommandContext context, - final ZuulProperties zuulProperties) { - super(commandKey, client, context, zuulProperties); - } - - public HttpClientRibbonCommand(final String commandKey, - final RibbonLoadBalancingHttpClient client, - final RibbonCommandContext context, - final ZuulProperties zuulProperties, - final FallbackProvider zuulFallbackProvider) { - super(commandKey, client, context, zuulProperties, zuulFallbackProvider); - } - - public HttpClientRibbonCommand(final String commandKey, - final RibbonLoadBalancingHttpClient client, - final RibbonCommandContext context, - final ZuulProperties zuulProperties, - final FallbackProvider zuulFallbackProvider, - final IClientConfig config) { - super(commandKey, client, context, zuulProperties, zuulFallbackProvider, config); - } - - @Override - protected RibbonApacheHttpRequest createRequest() throws Exception { - return new RibbonApacheHttpRequest(this.context); - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFactory.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFactory.java deleted file mode 100644 index 92842247..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFactory.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.route.apache; - -import java.util.Collections; -import java.util.Set; - -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; -import org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibbonCommandFactory; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; - -/** - * @author Christian Lohmann - * @author Ryan Baxter - */ -public class HttpClientRibbonCommandFactory extends AbstractRibbonCommandFactory { - - private final SpringClientFactory clientFactory; - - private final ZuulProperties zuulProperties; - - public HttpClientRibbonCommandFactory(SpringClientFactory clientFactory, ZuulProperties zuulProperties) { - this(clientFactory, zuulProperties, Collections.emptySet()); - } - - public HttpClientRibbonCommandFactory(SpringClientFactory clientFactory, ZuulProperties zuulProperties, - Set fallbackProviders) { - super(fallbackProviders); - this.clientFactory = clientFactory; - this.zuulProperties = zuulProperties; - } - - @Override - public HttpClientRibbonCommand create(final RibbonCommandContext context) { - FallbackProvider zuulFallbackProvider = getFallbackProvider(context.getServiceId()); - final String serviceId = context.getServiceId(); - final RibbonLoadBalancingHttpClient client = this.clientFactory.getClient( - serviceId, RibbonLoadBalancingHttpClient.class); - client.setLoadBalancer(this.clientFactory.getLoadBalancer(serviceId)); - - return new HttpClientRibbonCommand(serviceId, client, context, zuulProperties, zuulFallbackProvider, - clientFactory.getClientConfig(serviceId)); - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommand.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommand.java deleted file mode 100644 index 2434fafb..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommand.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.okhttp; - -import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpLoadBalancingClient; -import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpRibbonRequest; -import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpRibbonResponse; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; -import org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibbonCommand; -import com.netflix.client.config.IClientConfig; - -/** - * @author Spencer Gibb - * @author Ryan Baxter - */ -public class OkHttpRibbonCommand extends AbstractRibbonCommand { - - public OkHttpRibbonCommand(final String commandKey, - final OkHttpLoadBalancingClient client, - final RibbonCommandContext context, - final ZuulProperties zuulProperties) { - super(commandKey, client, context, zuulProperties); - } - - public OkHttpRibbonCommand(final String commandKey, - final OkHttpLoadBalancingClient client, - final RibbonCommandContext context, - final ZuulProperties zuulProperties, - final FallbackProvider zuulFallbackProvider) { - super(commandKey, client, context, zuulProperties, zuulFallbackProvider); - } - - public OkHttpRibbonCommand(final String commandKey, - final OkHttpLoadBalancingClient client, - final RibbonCommandContext context, - final ZuulProperties zuulProperties, - final FallbackProvider zuulFallbackProvider, - final IClientConfig config) { - super(commandKey, client, context, zuulProperties, zuulFallbackProvider, config); - } - - @Override - protected OkHttpRibbonRequest createRequest() throws Exception { - return new OkHttpRibbonRequest(this.context); - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFactory.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFactory.java deleted file mode 100644 index 2070816b..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFactory.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.route.okhttp; - -import java.util.Collections; -import java.util.Set; - -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpLoadBalancingClient; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; -import org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibbonCommandFactory; - -/** - * @author Spencer Gibb - * @author Ryan Baxter - */ -public class OkHttpRibbonCommandFactory extends AbstractRibbonCommandFactory { - - private SpringClientFactory clientFactory; - - private ZuulProperties zuulProperties; - - public OkHttpRibbonCommandFactory(SpringClientFactory clientFactory, ZuulProperties zuulProperties) { - this(clientFactory, zuulProperties, Collections.emptySet()); - } - - public OkHttpRibbonCommandFactory(SpringClientFactory clientFactory, ZuulProperties zuulProperties, - Set zuulFallbackProviders) { - super(zuulFallbackProviders); - this.clientFactory = clientFactory; - this.zuulProperties = zuulProperties; - } - - @Override - public OkHttpRibbonCommand create(final RibbonCommandContext context) { - final String serviceId = context.getServiceId(); - FallbackProvider fallbackProvider = getFallbackProvider(serviceId); - final OkHttpLoadBalancingClient client = this.clientFactory.getClient( - serviceId, OkHttpLoadBalancingClient.class); - client.setLoadBalancer(this.clientFactory.getLoadBalancer(serviceId)); - - return new OkHttpRibbonCommand(serviceId, client, context, zuulProperties, fallbackProvider, - clientFactory.getClientConfig(serviceId)); - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/support/AbstractRibbonCommand.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/support/AbstractRibbonCommand.java deleted file mode 100644 index 33b0aa79..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/support/AbstractRibbonCommand.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.support; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonHttpResponse; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.route.RibbonCommand; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; -import org.springframework.http.client.ClientHttpResponse; -import com.netflix.client.AbstractLoadBalancerAwareClient; -import com.netflix.client.ClientRequest; -import com.netflix.client.config.IClientConfig; -import com.netflix.client.config.IClientConfigKey; -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.HystrixCommandKey; -import com.netflix.hystrix.HystrixCommandProperties; -import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy; -import com.netflix.hystrix.HystrixThreadPoolKey; -import com.netflix.zuul.constants.ZuulConstants; -import com.netflix.zuul.context.RequestContext; - -/** - * @author Spencer Gibb - */ -public abstract class AbstractRibbonCommand, RQ extends ClientRequest, RS extends HttpResponse> - extends HystrixCommand implements RibbonCommand { - - private static final Log LOGGER = LogFactory.getLog(AbstractRibbonCommand.class); - protected final LBC client; - protected RibbonCommandContext context; - protected FallbackProvider zuulFallbackProvider; - protected IClientConfig config; - - public AbstractRibbonCommand(LBC client, RibbonCommandContext context, - ZuulProperties zuulProperties) { - this("default", client, context, zuulProperties); - } - - public AbstractRibbonCommand(String commandKey, LBC client, - RibbonCommandContext context, ZuulProperties zuulProperties) { - this(commandKey, client, context, zuulProperties, null); - } - - public AbstractRibbonCommand(String commandKey, LBC client, - RibbonCommandContext context, ZuulProperties zuulProperties, - FallbackProvider fallbackProvider) { - this(commandKey, client, context, zuulProperties, fallbackProvider, null); - } - - public AbstractRibbonCommand(String commandKey, LBC client, - RibbonCommandContext context, ZuulProperties zuulProperties, - FallbackProvider fallbackProvider, IClientConfig config) { - this(getSetter(commandKey, zuulProperties, config), client, context, fallbackProvider, config); - } - - protected AbstractRibbonCommand(Setter setter, LBC client, - RibbonCommandContext context, - FallbackProvider fallbackProvider, IClientConfig config) { - super(setter); - this.client = client; - this.context = context; - this.zuulFallbackProvider = fallbackProvider; - this.config = config; - } - - protected static HystrixCommandProperties.Setter createSetter(IClientConfig config, String commandKey, ZuulProperties zuulProperties) { - DynamicPropertyFactory dynamicPropertyFactory = DynamicPropertyFactory.getInstance(); - int defaultHystrixTimeout = dynamicPropertyFactory.getIntProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", - 0).get(); - int commandHystrixTimeout = dynamicPropertyFactory.getIntProperty("hystrix.command." + commandKey + ".execution.isolation.thread.timeoutInMilliseconds", - 0).get(); - int ribbonReadTimeout = config == null ? RibbonClientConfiguration.DEFAULT_READ_TIMEOUT : - config.get(IClientConfigKey.Keys.ReadTimeout, RibbonClientConfiguration.DEFAULT_READ_TIMEOUT).intValue(); - int ribbonConnectTimeout = config == null ? RibbonClientConfiguration.DEFAULT_CONNECT_TIMEOUT : - config.get(IClientConfigKey.Keys.ConnectTimeout, RibbonClientConfiguration.DEFAULT_CONNECT_TIMEOUT).intValue(); - int ribbonTimeout = ribbonConnectTimeout + ribbonReadTimeout; - int hystrixTimeout; - if(commandHystrixTimeout > 0) { - hystrixTimeout = commandHystrixTimeout; - } - else if( defaultHystrixTimeout > 0) { - hystrixTimeout = defaultHystrixTimeout; - } else { - hystrixTimeout = ribbonTimeout; - } - if(hystrixTimeout < ribbonTimeout) { - LOGGER.warn("The Hystrix timeout of " + hystrixTimeout + "ms for the command " + commandKey + - " is set lower than the combination of the Ribbon read and connect timeout, " + ribbonTimeout + "ms."); - } - return HystrixCommandProperties.Setter().withExecutionIsolationStrategy( - zuulProperties.getRibbonIsolationStrategy()).withExecutionTimeoutInMilliseconds(hystrixTimeout); - } - - @Deprecated - //TODO remove in 2.0.x - protected static Setter getSetter(final String commandKey, ZuulProperties zuulProperties) { - return getSetter(commandKey, zuulProperties, null); - } - - protected static Setter getSetter(final String commandKey, - ZuulProperties zuulProperties, IClientConfig config) { - - // @formatter:off - Setter commandSetter = Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RibbonCommand")) - .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey)); - final HystrixCommandProperties.Setter setter = createSetter(config, commandKey, zuulProperties); - if (zuulProperties.getRibbonIsolationStrategy() == ExecutionIsolationStrategy.SEMAPHORE){ - final String name = ZuulConstants.ZUUL_EUREKA + commandKey + ".semaphore.maxSemaphores"; - // we want to default to semaphore-isolation since this wraps - // 2 others commands that are already thread isolated - final DynamicIntProperty value = DynamicPropertyFactory.getInstance() - .getIntProperty(name, zuulProperties.getSemaphore().getMaxSemaphores()); - setter.withExecutionIsolationSemaphoreMaxConcurrentRequests(value.get()); - } else if (zuulProperties.getThreadPool().isUseSeparateThreadPools()) { - final String threadPoolKey = zuulProperties.getThreadPool().getThreadPoolKeyPrefix() + commandKey; - commandSetter.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(threadPoolKey)); - } - - return commandSetter.andCommandPropertiesDefaults(setter); - // @formatter:on - } - - @Override - protected ClientHttpResponse run() throws Exception { - final RequestContext context = RequestContext.getCurrentContext(); - - RQ request = createRequest(); - RS response = this.client.executeWithLoadBalancer(request, config); - - context.set("ribbonResponse", response); - - // Explicitly close the HttpResponse if the Hystrix command timed out to - // release the underlying HTTP connection held by the response. - // - if (this.isResponseTimedOut()) { - if (response != null) { - response.close(); - } - } - - return new RibbonHttpResponse(response); - } - - @Override - protected ClientHttpResponse getFallback() { - if(zuulFallbackProvider != null) { - return getFallbackResponse(); - } - return super.getFallback(); - } - - protected ClientHttpResponse getFallbackResponse() { - Throwable cause = getFailedExecutionException(); - cause = cause == null ? getExecutionException() : cause; - return zuulFallbackProvider.fallbackResponse(context.getServiceId(), cause); - } - - public LBC getClient() { - return client; - } - - public RibbonCommandContext getContext() { - return context; - } - - protected abstract RQ createRequest() throws Exception; -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/support/AbstractRibbonCommandFactory.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/support/AbstractRibbonCommandFactory.java deleted file mode 100644 index f71c944e..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/support/AbstractRibbonCommandFactory.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.support; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; -import org.springframework.cloud.netflix.zuul.filters.route.RibbonCommandFactory; - -/** - * @author Ryan Baxter - */ -public abstract class AbstractRibbonCommandFactory implements RibbonCommandFactory { - - private Map fallbackProviderCache; - private FallbackProvider defaultFallbackProvider = null; - - public AbstractRibbonCommandFactory(Set fallbackProviders){ - this.fallbackProviderCache = new HashMap<>(); - for(FallbackProvider provider : fallbackProviders) { - String route = provider.getRoute(); - if("*".equals(route) || route == null) { - defaultFallbackProvider = provider; - } else { - fallbackProviderCache.put(route, provider); - } - } - } - - protected FallbackProvider getFallbackProvider(String route) { - FallbackProvider provider = fallbackProviderCache.get(route); - if(provider == null) { - provider = defaultFallbackProvider; - } - return provider; - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/support/FilterConstants.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/support/FilterConstants.java deleted file mode 100644 index a2c24b3a..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/support/FilterConstants.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.support; - -import org.springframework.cloud.netflix.zuul.filters.pre.DebugFilter; -import org.springframework.cloud.netflix.zuul.filters.pre.Servlet30WrapperFilter; -import org.springframework.cloud.netflix.zuul.filters.route.SendForwardFilter; - -import com.netflix.zuul.ZuulFilter; - -/** - * @author Spencer Gibb - */ -public class FilterConstants { - - // KEY constants ----------------------------------- - - /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in {@link org.springframework.cloud.netflix.zuul.filters.pre.ServletDetectionFilter} - */ - public static final String IS_DISPATCHER_SERVLET_REQUEST_KEY = "isDispatcherServletRequest"; - - /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in {@link org.springframework.cloud.netflix.zuul.filters.route.SendForwardFilter} - */ - public static final String FORWARD_TO_KEY = "forward.to"; - - /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in TODO: determine use - */ - public static final String PROXY_KEY = "proxy"; - - /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in {@link org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter} - */ - public static final String REQUEST_ENTITY_KEY = "requestEntity"; - - /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in to override the path of the request. - */ - public static final String REQUEST_URI_KEY = "requestURI"; - - /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in {@link org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter} - */ - public static final String RETRYABLE_KEY = "retryable"; - - /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in {@link org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter} - */ - public static final String ROUTING_DEBUG_KEY = "routingDebug"; - - /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in {@link org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter} - */ - public static final String SERVICE_ID_KEY = "serviceId"; - - /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in {@link org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter} - */ - public static final String LOAD_BALANCER_KEY = "loadBalancerKey"; - - // ORDER constants ----------------------------------- - - /** - * Filter Order for {@link DebugFilter#filterOrder()} - */ - public static final int DEBUG_FILTER_ORDER = 1; - - /** - * Filter Order for {@link org.springframework.cloud.netflix.zuul.filters.pre.FormBodyWrapperFilter#filterOrder()} - */ - public static final int FORM_BODY_WRAPPER_FILTER_ORDER = -1; - - /** - * Filter Order for {@link org.springframework.cloud.netflix.zuul.filters.pre.PreDecorationFilter} - */ - public static final int PRE_DECORATION_FILTER_ORDER = 5; - - /** - * Filter Order for {@link org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter#filterOrder()} - */ - public static final int RIBBON_ROUTING_FILTER_ORDER = 10; - - /** - * Filter Order for {@link org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilter#filterOrder()} - */ - public static final int SEND_ERROR_FILTER_ORDER = 0; - - /** - * Filter Order for {@link SendForwardFilter#filterOrder()} - */ - public static final int SEND_FORWARD_FILTER_ORDER = 500; - - /** - * Filter Order for {@link org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter#filterOrder()} - */ - public static final int SEND_RESPONSE_FILTER_ORDER = 1000; - - /** - * Filter Order for {@link org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter#filterOrder()} - */ - public static final int SIMPLE_HOST_ROUTING_FILTER_ORDER = 100; - - /** - * filter order for {@link Servlet30WrapperFilter#filterOrder()} - */ - public static final int SERVLET_30_WRAPPER_FILTER_ORDER = -2; - - /** - * filter order for {@link org.springframework.cloud.netflix.zuul.filters.pre.ServletDetectionFilter#filterOrder()} - */ - public static final int SERVLET_DETECTION_FILTER_ORDER = -3; - - // Zuul Filter TYPE constants ----------------------------------- - - /** - * {@link ZuulFilter#filterType()} error type. - */ - public static final String ERROR_TYPE = "error"; - - /** - * {@link ZuulFilter#filterType()} post type. - */ - public static final String POST_TYPE = "post"; - - /** - * {@link ZuulFilter#filterType()} pre type. - */ - public static final String PRE_TYPE = "pre"; - - /** - * {@link ZuulFilter#filterType()} route type. - */ - public static final String ROUTE_TYPE = "route"; - - // OTHER constants ----------------------------------- - - /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in {@link org.springframework.cloud.netflix.zuul.filters.route.SendForwardFilter} - */ - public static final String FORWARD_LOCATION_PREFIX = "forward:"; - - /** - * default http port - */ - public static final int HTTP_PORT = 80; - - /** - * default https port - */ - public static final int HTTPS_PORT = 443; - - /** - * http url scheme - */ - public static final String HTTP_SCHEME = "http"; - - /** - * https url scheme - */ - public static final String HTTPS_SCHEME = "https"; - - // HEADER constants ----------------------------------- - - /** - * X-* Header for the matching url. Used when routes use a url rather than serviceId - */ - public static final String SERVICE_HEADER = "X-Zuul-Service"; - - /** - * X-* Header for the matching serviceId - */ - public static final String SERVICE_ID_HEADER = "X-Zuul-ServiceId"; - - /** - * X-Forwarded-For Header - */ - public static final String X_FORWARDED_FOR_HEADER = "X-Forwarded-For"; - - /** - * X-Forwarded-Host Header - */ - public static final String X_FORWARDED_HOST_HEADER = "X-Forwarded-Host"; - - /** - * X-Forwarded-Prefix Header - */ - public static final String X_FORWARDED_PREFIX_HEADER = "X-Forwarded-Prefix"; - - /** - * X-Forwarded-Port Header - */ - public static final String X_FORWARDED_PORT_HEADER = "X-Forwarded-Port"; - - /** - * X-Forwarded-Proto Header - */ - public static final String X_FORWARDED_PROTO_HEADER = "X-Forwarded-Proto"; - - /** - * X-Zuul-Debug Header - */ - public static final String X_ZUUL_DEBUG_HEADER = "X-Zuul-Debug-Header"; - - private FilterConstants() { - throw new AssertionError("Must not instantiate constant utility class"); - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/DefaultCounterFactory.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/DefaultCounterFactory.java deleted file mode 100644 index e6dda312..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/DefaultCounterFactory.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.metrics; - -import com.netflix.zuul.monitoring.CounterFactory; - -import io.micrometer.core.instrument.MeterRegistry; - -/** - * A counter based monitoring factory that uses {@link MeterRegistry} to increment counters. - * - * @author Anastasiia Smirnova - */ -public class DefaultCounterFactory extends CounterFactory { - - private final MeterRegistry meterRegistry; - - public DefaultCounterFactory(MeterRegistry meterRegistry) { - this.meterRegistry = meterRegistry; - } - - @Override - public void increment(String name) { - this.meterRegistry.counter(name).increment(); - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/EmptyCounterFactory.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/EmptyCounterFactory.java deleted file mode 100644 index 319502c8..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/EmptyCounterFactory.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.metrics; - -import com.netflix.zuul.monitoring.CounterFactory; - -/** - * A counter based monitoring factory that does nothing. - * - * @author Anastasiia Smirnova - */ -public class EmptyCounterFactory extends CounterFactory { - @Override - public void increment(String name) { - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/EmptyTracerFactory.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/EmptyTracerFactory.java deleted file mode 100644 index e46bcbe5..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/EmptyTracerFactory.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.metrics; - -import com.netflix.zuul.monitoring.Tracer; -import com.netflix.zuul.monitoring.TracerFactory; - -/** - * A time based monitoring factory that does nothing. - * - * @author Anastasiia Smirnova - */ -public class EmptyTracerFactory extends TracerFactory { - - private final EmptyTracer emptyTracer = new EmptyTracer(); - - @Override - public Tracer startMicroTracer(String name) { - return emptyTracer; - } - - private static final class EmptyTracer implements Tracer { - @Override - public void setName(String name) { - } - - @Override - public void stopAndLog() { - } - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/RequestContentDataExtractor.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/RequestContentDataExtractor.java deleted file mode 100644 index 5ff6d2a6..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/RequestContentDataExtractor.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.util; - -import org.springframework.core.io.InputStreamResource; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.util.StringUtils; -import org.springframework.web.multipart.MultipartFile; -import org.springframework.web.multipart.MultipartHttpServletRequest; - -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.util.HashSet; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; - -public class RequestContentDataExtractor { - public static MultiValueMap extract(HttpServletRequest request) throws IOException { - return (request instanceof MultipartHttpServletRequest) ? - extractFromMultipartRequest((MultipartHttpServletRequest) request) : - extractFromRequest(request); - } - - private static MultiValueMap extractFromRequest(HttpServletRequest request) throws IOException { - MultiValueMap builder = new LinkedMultiValueMap<>(); - Set queryParams = findQueryParams(request); - - for (Entry entry : request.getParameterMap().entrySet()) { - String key = entry.getKey(); - - if (!queryParams.contains(key) && entry.getValue() != null) { - for (String value : entry.getValue()) { - builder.add(key, value); - } - } - } - - return builder; - } - - private static MultiValueMap extractFromMultipartRequest(MultipartHttpServletRequest request) - throws IOException { - MultiValueMap builder = new LinkedMultiValueMap<>(); - Set queryParams = findQueryParams(request); - - for (Entry entry : request.getParameterMap().entrySet()) { - String key = entry.getKey(); - - if (!queryParams.contains(key)) { - for (String value : entry.getValue()) { - HttpHeaders headers = new HttpHeaders(); - String type = request.getMultipartContentType(key); - - if (type != null) { - headers.setContentType(MediaType.valueOf(type)); - } - - builder.add(key, new HttpEntity<>(value, headers)); - } - } - } - - for (Entry> parts : request.getMultiFileMap().entrySet()) { - for (MultipartFile file : parts.getValue()) { - HttpHeaders headers = new HttpHeaders(); - headers.setContentDispositionFormData(file.getName(), file.getOriginalFilename()); - if (file.getContentType() != null) { - headers.setContentType(MediaType.valueOf(file.getContentType())); - } - - HttpEntity entity = new HttpEntity<>(new InputStreamResource(file.getInputStream()), headers); - builder.add(parts.getKey(), entity); - } - } - - return builder; - } - - private static Set findQueryParams(HttpServletRequest request) { - Set result = new HashSet<>(); - String query = request.getQueryString(); - - if (query != null) { - for (String value : StringUtils.tokenizeToStringArray(query, "&")) { - if (value.contains("=")) { - value = value.substring(0, value.indexOf("=")); - } - result.add(value); - } - } - - return result; - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/RequestUtils.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/RequestUtils.java deleted file mode 100644 index fd1e7caf..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/RequestUtils.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.util; - -import com.netflix.zuul.context.RequestContext; - -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.IS_DISPATCHER_SERVLET_REQUEST_KEY; - -public class RequestUtils { - - /** - * @deprecated use {@link org.springframework.cloud.netflix.zuul.filters.support.FilterConstants#IS_DISPATCHER_SERVLET_REQUEST_KEY} - */ - @Deprecated - public static final String IS_DISPATCHERSERVLETREQUEST = IS_DISPATCHER_SERVLET_REQUEST_KEY; - - public static boolean isDispatcherServletRequest() { - return RequestContext.getCurrentContext().getBoolean(IS_DISPATCHER_SERVLET_REQUEST_KEY); - } - - public static boolean isZuulServletRequest() { - //extra check for dispatcher since ZuulServlet can run from ZuulController - return !isDispatcherServletRequest() && RequestContext.getCurrentContext().getZuulEngineRan(); - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/ZuulRuntimeException.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/ZuulRuntimeException.java deleted file mode 100644 index d10bd4ac..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/ZuulRuntimeException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.util; - -import com.netflix.zuul.exception.ZuulException; -import org.springframework.http.HttpStatus; - -/** - * @author Spencer Gibb - */ -public class ZuulRuntimeException extends RuntimeException { - - public ZuulRuntimeException(ZuulException cause) { - super(cause); - } - - public ZuulRuntimeException(Exception ex) { - this(new ZuulException(ex, HttpStatus.INTERNAL_SERVER_ERROR.value(), null)); - } -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/web/ZuulController.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/web/ZuulController.java deleted file mode 100644 index d8fe936d..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/web/ZuulController.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.web; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.mvc.ServletWrappingController; - -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.http.ZuulServlet; - -/** - * @author Spencer Gibb - */ -public class ZuulController extends ServletWrappingController { - - public ZuulController() { - setServletClass(ZuulServlet.class); - setServletName("zuul"); - setSupportedMethods((String[]) null); // Allow all - } - - @Override - public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { - try { - // We don't care about the other features of the base class, just want to - // handle the request - return super.handleRequestInternal(request, response); - } - finally { - // @see com.netflix.zuul.context.ContextLifecycleFilter.doFilter - RequestContext.getCurrentContext().unset(); - } - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/web/ZuulHandlerMapping.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/web/ZuulHandlerMapping.java deleted file mode 100644 index 94697f90..00000000 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/web/ZuulHandlerMapping.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.web; - -import java.util.Collection; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.boot.web.servlet.error.ErrorController; -import org.springframework.cloud.netflix.zuul.filters.RefreshableRouteLocator; -import org.springframework.cloud.netflix.zuul.filters.Route; -import org.springframework.cloud.netflix.zuul.filters.RouteLocator; -import org.springframework.util.AntPathMatcher; -import org.springframework.util.PathMatcher; -import org.springframework.web.cors.CorsConfiguration; -import org.springframework.web.servlet.HandlerExecutionChain; -import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping; - -import com.netflix.zuul.context.RequestContext; - -/** - * MVC HandlerMapping that maps incoming request paths to remote services. - * - * @author Spencer Gibb - * @author Dave Syer - * @author João Salavessa - * @author Biju Kunjummen - */ -public class ZuulHandlerMapping extends AbstractUrlHandlerMapping { - - private final RouteLocator routeLocator; - - private final ZuulController zuul; - - private ErrorController errorController; - - private PathMatcher pathMatcher = new AntPathMatcher(); - - private volatile boolean dirty = true; - - public ZuulHandlerMapping(RouteLocator routeLocator, ZuulController zuul) { - this.routeLocator = routeLocator; - this.zuul = zuul; - setOrder(-200); - } - - @Override - protected HandlerExecutionChain getCorsHandlerExecutionChain(HttpServletRequest request, - HandlerExecutionChain chain, CorsConfiguration config) { - if (config == null) { - // Allow CORS requests to go to the backend - return chain; - } - return super.getCorsHandlerExecutionChain(request, chain, config); - } - - public void setErrorController(ErrorController errorController) { - this.errorController = errorController; - } - - public void setDirty(boolean dirty) { - this.dirty = dirty; - if (this.routeLocator instanceof RefreshableRouteLocator) { - ((RefreshableRouteLocator) this.routeLocator).refresh(); - } - } - - @Override - protected Object lookupHandler(String urlPath, HttpServletRequest request) throws Exception { - if (this.errorController != null && urlPath.equals(this.errorController.getErrorPath())) { - return null; - } - if (isIgnoredPath(urlPath, this.routeLocator.getIgnoredPaths())) return null; - RequestContext ctx = RequestContext.getCurrentContext(); - if (ctx.containsKey("forward.to")) { - return null; - } - if (this.dirty) { - synchronized (this) { - if (this.dirty) { - registerHandlers(); - this.dirty = false; - } - } - } - return super.lookupHandler(urlPath, request); - } - - private boolean isIgnoredPath(String urlPath, Collection ignored) { - if (ignored != null) { - for (String ignoredPath : ignored) { - if (this.pathMatcher.match(ignoredPath, urlPath)) { - return true; - } - } - } - return false; - } - - private void registerHandlers() { - Collection routes = this.routeLocator.getRoutes(); - if (routes.isEmpty()) { - this.logger.warn("No routes found from RouteLocator"); - } - else { - for (Route route : routes) { - registerHandler(route.getFullPath(), this.zuul); - } - } - } - -} diff --git a/spring-cloud-netflix-zuul/src/main/resources/META-INF/spring.factories b/spring-cloud-netflix-zuul/src/main/resources/META-INF/spring.factories deleted file mode 100644 index ac5fe607..00000000 --- a/spring-cloud-netflix-zuul/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,3 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -org.springframework.cloud.netflix.zuul.ZuulServerAutoConfiguration,\ -org.springframework.cloud.netflix.zuul.ZuulProxyAutoConfiguration diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ContextPathZuulProxyApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ContextPathZuulProxyApplicationTests.java deleted file mode 100644 index bc9de6b9..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ContextPathZuulProxyApplicationTests.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute; -import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import com.netflix.zuul.context.RequestContext; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = ContextPathZuulProxyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { - "server.servlet.contextPath: /app" }) -@DirtiesContext -public class ContextPathZuulProxyApplicationTests { - - @LocalServerPort - private int port; - - @Autowired - private TestRestTemplate testRestTemplate; - - @Autowired - private DiscoveryClientRouteLocator routes; - - @Autowired - private RoutesEndpoint endpoint; - - @Before - public void setTestRequestContext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void getOnSelfViaSimpleHostRoutingFilter() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app/local"); - this.endpoint.reset(); - ResponseEntity result = testRestTemplate.exchange( - "http://localhost:" + this.port + "/app/self/1", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Gotten 1!", result.getBody()); - } - - @Test - public void stripPrefixFalseAppendsPath() { - this.routes.addRoute(new ZuulRoute("strip", "/strip/**", "strip", - "http://localhost:" + this.port + "/app/local", false, false, null)); - this.endpoint.reset(); - ResponseEntity result = testRestTemplate.exchange( - "http://localhost:" + this.port + "/app/strip", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - // Prefix not stripped to it goes to /local/strip - assertEquals("Gotten strip!", result.getBody()); - } - -} - -// Don't use @SpringBootApplication because we don't want to component scan -@Configuration -@EnableAutoConfiguration -@RestController -@EnableZuulProxy -class ContextPathZuulProxyApplication { - - @RequestMapping(value = "/local/{id}", method = RequestMethod.GET) - public String get(@PathVariable String id) { - return "Gotten " + id + "!"; - } - -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FiltersEndpointTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FiltersEndpointTests.java deleted file mode 100644 index 7751f236..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FiltersEndpointTests.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul; - -import java.util.List; -import java.util.Map; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Bean; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.netflix.zuul.ZuulFilter; - -import static org.hibernate.validator.internal.util.Contracts.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * Tests for Filters endpoint - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT) -@DirtiesContext -public class FiltersEndpointTests { - - @Autowired - private FiltersEndpoint endpoint; - - @Test - public void getFilters() { - final Map>> filters = endpoint.invoke(); - - boolean foundFilter = false; - - if (filters.containsKey("sample")) { - for (Map filterInfo : filters.get("sample")) { - if (TestFilter.class.getName().equals(filterInfo.get("class"))) { - foundFilter = true; - - // Verify filter's attributes - assertEquals(0, filterInfo.get("order")); - - break; // the search is over - } - } - } - - assertTrue(foundFilter, "Could not find expected sample filter from filters endpoint"); - } - -} - -@SpringBootConfiguration -@EnableAutoConfiguration -@EnableZuulProxy -class FiltersEndpointApplication { - - @Bean - public ZuulFilter sampleFilter() { - return new TestFilter(); - } - -} - -class TestFilter extends ZuulFilter { - @Override - public String filterType() { - return "sample"; - } - - @Override - public boolean shouldFilter() { - return true; - } - - @Override - public Object run() { - return null; - } - - @Override - public int filterOrder() { - return 0; - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FormZuulProxyApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FormZuulProxyApplicationTests.java deleted file mode 100644 index d4f8e436..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FormZuulProxyApplicationTests.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import java.io.IOException; - -import javax.inject.Inject; -import javax.servlet.http.Part; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.actuate.web.trace.HttpTraceRepository; -import org.springframework.boot.actuate.web.trace.InMemoryHttpTraceRepository; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.cloud.netflix.ribbon.StaticServerList; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; - -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; - -import static java.nio.charset.Charset.defaultCharset; -import static org.junit.Assert.assertEquals; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; -import static org.springframework.util.StreamUtils.copyToString; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = FormZuulProxyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { - "zuul.routes.simplefzpat:/simplefzpat/**" }) -@DirtiesContext -public class FormZuulProxyApplicationTests { - - @Inject - private TestRestTemplate restTemplate; - - @Before - public void setTestRequestContext() { - RequestContext.testSetCurrentContext(new RequestContext()); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void postWithForm() { - MultiValueMap form = new LinkedMultiValueMap<>(); - form.set("foo", "bar"); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - - ResponseEntity result = sendPost("/simplefzpat/form", form, headers); - - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {foo=[bar]}", result.getBody()); - } - - @Test - public void postWithMultipartForm() { - MultiValueMap form = new LinkedMultiValueMap<>(); - form.set("foo", "bar"); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - - ResponseEntity result = sendPost("/simplefzpat/form", form, headers); - - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {foo=[bar]}", result.getBody()); - } - - @Test - public void postWithMultipartFile() { - MultiValueMap form = new LinkedMultiValueMap<>(); - - HttpHeaders part = new HttpHeaders(); - part.setContentType(MediaType.TEXT_PLAIN); - part.setContentDispositionFormData("file", "foo.txt"); - - form.set("foo", new HttpEntity<>("bar".getBytes(), part)); - - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - - ResponseEntity result = sendPost("/simplefzpat/file", form, headers); - - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! bar", result.getBody()); - } - - @Test - public void postWithMultipartFileAndForm() { - MultiValueMap form = new LinkedMultiValueMap<>(); - - HttpHeaders part = new HttpHeaders(); - part.setContentType(MediaType.TEXT_PLAIN); - part.setContentDispositionFormData("file", "foo.txt"); - form.set("foo", new HttpEntity<>("bar".getBytes(), part)); - - form.set("field", "data"); - - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - - ResponseEntity result = sendPost("/simplefzpat/fileandform", form, headers); - - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! bar!field!data", result.getBody()); - } - - @Test - public void postWithMultipartApplicationJson() { - MultiValueMap form = new LinkedMultiValueMap<>(); - - HttpHeaders partHeaders = new HttpHeaders(); - partHeaders.setContentType(MediaType.APPLICATION_JSON); - form.set("field", new HttpEntity<>("{foo=[bar]}", partHeaders)); - - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - - ResponseEntity result = sendPost("/simplefzpat/json", form, headers); - - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {foo=[bar]} as application/json", result.getBody()); - } - - @Test - public void postWithUTF8Form() { - MultiValueMap form = new LinkedMultiValueMap<>(); - - form.set("foo", "bar"); - - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.valueOf( - MediaType.APPLICATION_FORM_URLENCODED_VALUE + "; charset=UTF-8")); - - ResponseEntity result = sendPost("/simplefzpat/form", form, headers); - - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {foo=[bar]}", result.getBody()); - } - - @Test - public void postWithUrlParams() throws Exception { - MultiValueMap form = new LinkedMultiValueMap<>(); - - form.set("foo", "bar"); - - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.valueOf( - MediaType.APPLICATION_FORM_URLENCODED_VALUE + "; charset=UTF-8")); - - ResponseEntity result = sendPost("/simplefzpat/form?uriParam=uriValue", form, headers); - - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {uriParam=[uriValue], foo=[bar]}", result.getBody()); - } - - @Test - public void getWithUrlParams() throws Exception { - ResponseEntity result = sendGet("/simplefzpat/form?uriParam=uriValue"); - - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {uriParam=[uriValue]}", result.getBody()); - } - - private ResponseEntity sendPost(String url, MultiValueMap form, - HttpHeaders headers) { - return restTemplate.postForEntity(url, new HttpEntity<>(form, headers), - String.class); - } - - private ResponseEntity sendGet(String url) { - return restTemplate.getForEntity(url, String.class); - } -} - -// Don't use @SpringBootApplication because we don't want to component scan -@Configuration -@EnableAutoConfiguration -@RestController -@EnableZuulProxy -@RibbonClients({ - @RibbonClient(name = "simplefzpat", configuration = FormRibbonClientConfiguration.class) }) -class FormZuulProxyApplication { - - @RequestMapping(value = "/form", method = RequestMethod.POST) - public String accept(@RequestParam MultiValueMap form) - throws IOException { - return "Posted! " + form; - } - - @RequestMapping(value = "/form", method = RequestMethod.GET) - public String get(@RequestParam MultiValueMap form) - throws IOException { - return "Posted! " + form; - } - - // TODO: Why does this not work if you add @RequestParam as above? - @RequestMapping(value = "/file", method = RequestMethod.POST) - public String file(@RequestParam(required = false) MultipartFile file) - throws IOException { - - return "Posted! " + copyToString(file.getInputStream(), defaultCharset()); - } - - @RequestMapping(value = "/fileandform", method = RequestMethod.POST) - public String fileAndForm(@RequestParam MultipartFile file, - @RequestParam String field) throws IOException { - - return "Posted! " + copyToString(file.getInputStream(), defaultCharset()) - + "!field!" + field; - } - - @RequestMapping(value = "/json", method = RequestMethod.POST) - public String fileAndJson(@RequestPart Part field) throws IOException { - - return "Posted! " + copyToString(field.getInputStream(), defaultCharset()) - + " as " + field.getContentType(); - } - - @Bean - public ZuulFilter sampleFilter() { - return new ZuulFilter() { - - @Override - public String filterType() { - return PRE_TYPE; - } - - @Override - public boolean shouldFilter() { - return true; - } - - @Override - public Object run() { - return null; - } - - @Override - public int filterOrder() { - return 0; - } - - }; - } - - @Bean - public HttpTraceRepository traceRepository() { - return new InMemoryHttpTraceRepository(); - } - - public static void main(String[] args) { - } - -} - -// Load balancer with fixed server list for "simplefzpat" pointing to localhost -@Configuration -class FormRibbonClientConfiguration { - - @LocalServerPort - private int port; - - @Bean - public ServerList ribbonServerList() { - return new StaticServerList<>(new Server("localhost", this.port)); - } - -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FormZuulServletProxyApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FormZuulServletProxyApplicationTests.java deleted file mode 100644 index eedc8265..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FormZuulServletProxyApplicationTests.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.web.trace.HttpTraceRepository; -import org.springframework.boot.actuate.web.trace.InMemoryHttpTraceRepository; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.cloud.netflix.ribbon.StaticServerList; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; - -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; - -import static org.junit.Assert.assertEquals; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = FormZuulServletProxyApplication.class, webEnvironment = RANDOM_PORT, - properties = {"zuul.routes[simplefzspat].path:/simplefzspat/**", "zuul.routes[simplefzspat].serviceId:simplefzspat"}) -@DirtiesContext -public class FormZuulServletProxyApplicationTests { - - @Autowired - private TestRestTemplate testRestTemplate; - - @Before - public void setTestRequestContext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @After - public void unsetTestRequestContext() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void postWithForm() { - MultiValueMap form = new LinkedMultiValueMap<>(); - form.set("foo", "bar"); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - ResponseEntity result = testRestTemplate.exchange("/zuul/simplefzspat/form", - HttpMethod.POST, new HttpEntity<>(form, headers), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {foo=[bar]}", result.getBody()); - } - - @Test - public void postWithMultipartForm() { - MultiValueMap form = new LinkedMultiValueMap<>(); - form.set("foo", "bar"); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - ResponseEntity result = testRestTemplate.exchange("/zuul/simplefzspat/form", - HttpMethod.POST, new HttpEntity<>(form, headers), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {foo=[bar]}", result.getBody()); - } - - @Test - public void postWithMultipartFile() { - MultiValueMap form = new LinkedMultiValueMap<>(); - HttpHeaders part = new HttpHeaders(); - part.setContentType(MediaType.TEXT_PLAIN); - part.setContentDispositionFormData("file", "foo.txt"); - form.set("foo", new HttpEntity<>("bar".getBytes(), part)); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - headers.set("Transfer-Encoding", "chunked"); - headers.setContentLength(-1); - ResponseEntity result = testRestTemplate.exchange("/zuul/simplefzspat/file", - HttpMethod.POST, new HttpEntity<>(form, headers), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! bar", result.getBody()); - } - - @Test - public void postWithUTF8Form() { - MultiValueMap form = new LinkedMultiValueMap<>(); - form.set("foo", "bar"); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.valueOf( - MediaType.APPLICATION_FORM_URLENCODED_VALUE + "; charset=UTF-8")); - ResponseEntity result = testRestTemplate.exchange("/zuul/simplefzspat/form", - HttpMethod.POST, new HttpEntity<>(form, headers), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {foo=[bar]}", result.getBody()); - } -} - -// Don't use @SpringBootApplication because we don't want to component scan -@Configuration -@EnableAutoConfiguration -@RestController -@EnableZuulProxy -@RibbonClients(@RibbonClient(name = "simplefzspat", configuration = ServletFormRibbonClientConfiguration.class)) -class FormZuulServletProxyApplication { - - private static final Log log = LogFactory.getLog(FormZuulServletProxyApplication.class); - - @RequestMapping(value = "/form", method = RequestMethod.POST) - public String accept(@RequestParam MultiValueMap form) - throws IOException { - return "Posted! " + form; - } - - // TODO: Why does this not work if you add @RequestParam as above? - @RequestMapping(value = "/file", method = RequestMethod.POST) - public String file(@RequestParam(required = false) MultipartFile file) - throws IOException { - byte[] bytes = new byte[0]; - if (file != null) { - if (file.getSize() > 1024) { - bytes = new byte[1024]; - InputStream inputStream = file.getInputStream(); - inputStream.read(bytes); - byte[] buffer = new byte[1024 * 1024 * 10]; - while (inputStream.read(buffer) >= 0) { - log.info("Read more bytes"); - } - } - else { - bytes = file.getBytes(); - } - } - return "Posted! " + new String(bytes); - } - - @Bean - public ZuulFilter sampleFilter() { - return new ZuulFilter() { - - @Override - public String filterType() { - return PRE_TYPE; - } - - @Override - public boolean shouldFilter() { - return true; - } - - @Override - public Object run() { - return null; - } - - @Override - public int filterOrder() { - return 0; - } - - }; - } - - @Bean - public HttpTraceRepository traceRepository() { - return new InMemoryHttpTraceRepository(); - } - -} - -// Load balancer with fixed server list for "simplefzspat" pointing to localhost -@Configuration -class ServletFormRibbonClientConfiguration { - - @LocalServerPort - private int port; - - @Bean - public ServerList ribbonServerList() { - return new StaticServerList<>(new Server("localhost", this.port)); - } - -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RetryableZuulProxyApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RetryableZuulProxyApplicationTests.java deleted file mode 100644 index 0c716eb3..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RetryableZuulProxyApplicationTests.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.StaticServerList; -import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import static org.junit.Assert.assertEquals; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = RetryableZuulProxyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { - "zuul.routes[simplerzpat].path: /simplerzpat/**", "zuul.routes[simplerzpat].retryable: true", - "zuul.routes[simplerzpat].serviceId: simplerzpat", "ribbon.OkToRetryOnAllOperations: true", - "simplerzpat.ribbon.retryableStatusCodes: 404" }) -@DirtiesContext -public class RetryableZuulProxyApplicationTests { - - @Autowired - private TestRestTemplate testRestTemplate; - - @Autowired - @SuppressWarnings("unused") - private DiscoveryClientRouteLocator routes; - - @Autowired - @SuppressWarnings("unused") - private RoutesEndpoint endpoint; - - @Before - public void setTestRequestContext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void postWithForm() { - MultiValueMap form = new LinkedMultiValueMap(); - form.set("foo", "bar"); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - ResponseEntity result = testRestTemplate.exchange("/simplerzpat/poster", - HttpMethod.POST, new HttpEntity<>(form, headers), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {foo=[bar]}", result.getBody()); - } - -} - -// Don't use @SpringBootApplication because we don't want to component scan -@Configuration -@EnableAutoConfiguration -@RestController -@EnableZuulProxy -@RibbonClient(name = "simplerzpat", configuration = RetryableRibbonClientConfiguration.class) -class RetryableZuulProxyApplication { - - @RequestMapping(value = "/poster", method = RequestMethod.POST) - public String delete(@RequestBody MultiValueMap form) { - return "Posted! " + form; - } - - @Bean - public ZuulFilter sampleFilter() { - return new ZuulFilter() { - @Override - public String filterType() { - return PRE_TYPE; - } - - @Override - public boolean shouldFilter() { - return true; - } - - @Override - public Object run() { - return null; - } - - @Override - public int filterOrder() { - return 0; - } - }; - } - -} - -// Load balancer with fixed server list for "simplerzpat" pointing to localhost -@Configuration -class RetryableRibbonClientConfiguration { - - @LocalServerPort - private int port; - - @Bean - public ServerList ribbonServerList() { - return new StaticServerList<>(new Server("localhost", this.port), - new Server("failed-localhost", this.port)); - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointDetailsTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointDetailsTests.java deleted file mode 100644 index e99af749..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointDetailsTests.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.zuul.filters.Route; -import org.springframework.cloud.netflix.zuul.filters.RouteLocator; -import org.springframework.context.ApplicationEventPublisher; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -/** - * @author Ryan Baxter - * @author Gregor Zurowski - */ -@SpringBootTest -@RunWith(MockitoJUnitRunner.class) -public class RoutesEndpointDetailsTests { - private RouteLocator locator; - private RoutesEndpoint endpoint; - @Mock - private ApplicationEventPublisher publisher; - - @Before - public void setUp() { - this.locator = new RouteLocator() { - @Override - public Collection getIgnoredPaths() { - return null; - } - - @Override - public List getRoutes() { - List routes = new ArrayList<>(); - routes.add(new Route("foo", "foopath", "foolocation", null, true, Collections.EMPTY_SET)); - routes.add(new Route("bar", "barpath", "barlocation", "bar-prefix", true, Collections.EMPTY_SET)); - return routes; - } - - @Override - public Route getMatchingRoute(String path) { - return null; - } - }; - endpoint = spy(new RoutesEndpoint(locator)); - } - - @Test - public void reset() throws Exception { - this.endpoint.setApplicationEventPublisher(publisher); - Map result = new HashMap<>(); - for(Route r : locator.getRoutes()) { - result.put(r.getFullPath(), r.getLocation()); - } - assertEquals(result , endpoint.reset()); - verify(endpoint, times(1)).invoke(); - verify(publisher, times(1)).publishEvent(isA(RoutesRefreshedEvent.class)); - } - - @Test - public void routeDetails() throws Exception { - Map results = new HashMap<>(); - for (Route route : locator.getRoutes()) { - results.put(route.getFullPath(), new RoutesEndpoint.RouteDetails(route)); - } - assertEquals(results, this.endpoint.invokeRouteDetails(RoutesEndpoint.FORMAT_DETAILS)); - verify(endpoint, times(1)).invokeRouteDetails(); - } - -} \ No newline at end of file diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointIntegrationTests.java deleted file mode 100644 index 41ba8f56..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointIntegrationTests.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import java.util.Map; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.context.ApplicationListener; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.bind.annotation.RestController; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author Ryan Baxter - * @author Gregor Zurowski - */ -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT, - value = {"zuul.routes.sslservice.url=https://localhost:8443", "management.security.enabled=false", "management.endpoints.web.expose=*"}) -@DirtiesContext -public class RoutesEndpointIntegrationTests { - private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); - - @Autowired - private TestRestTemplate restTemplate; - - @Autowired - private SimpleZuulProxyApplication.RoutesRefreshListener refreshListener; - - @Test - @SuppressWarnings("unchecked") - public void getRoutesTest() { - Map routes = restTemplate.getForObject(BASE_PATH + "/routes", Map.class); - assertEquals("https://localhost:8443", routes.get("/sslservice/**")); - } - - @Test - @SuppressWarnings("unchecked") - public void postRoutesTest() { - Map routes = restTemplate.postForObject(BASE_PATH + "/routes", null, Map.class); - assertEquals("https://localhost:8443", routes.get("/sslservice/**")); - assertTrue(refreshListener.wasCalled()); - } - - @Test - public void getRouteDetailsTest() { - ResponseEntity> responseEntity = restTemplate.exchange( - BASE_PATH + "/routes/details", HttpMethod.GET, null, new ParameterizedTypeReference>() { - }); - - assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); - - RoutesEndpoint.RouteDetails details = responseEntity.getBody().get("/sslservice/**"); - assertThat(details.getPath(), is("/**")); - assertThat(details.getFullPath(), is("/sslservice/**")); - assertThat(details.getLocation(), is("https://localhost:8443")); - assertThat(details.getPrefix(), is("/sslservice")); - assertTrue(details.isPrefixStripped()); - } - - @Configuration - @EnableAutoConfiguration - @RestController - @EnableZuulProxy - static class SimpleZuulProxyApplication { - @Component - static class RoutesRefreshListener implements ApplicationListener { - private boolean called = false; - @Override - public void onApplicationEvent(RoutesRefreshedEvent routesRefreshedEvent) { - called = true; - } - - public boolean wasCalled() { - return called; - } - } - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointTests.java deleted file mode 100644 index ffe2de8f..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointTests.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.cloud.netflix.zuul.filters.Route; -import org.springframework.cloud.netflix.zuul.filters.RouteLocator; - -import static org.junit.Assert.assertEquals; - -/** - * @author Ryan Baxter - * @author Gregor Zurowski - */ -public class RoutesEndpointTests { - - private RouteLocator locator; - - @Before - public void setUp() { - this.locator = new RouteLocator() { - @Override - public Collection getIgnoredPaths() { - return null; - } - - @Override - public List getRoutes() { - List routes = new ArrayList<>(); - routes.add(new Route("foo", "foopath", "foolocation", null, true, Collections.EMPTY_SET)); - routes.add(new Route("bar", "barpath", "barlocation", "/bar-prefix", true, Collections.EMPTY_SET)); - return routes; - } - - @Override - public Route getMatchingRoute(String path) { - return null; - } - }; - } - - @Test - public void testInvoke() { - RoutesEndpoint endpoint = new RoutesEndpoint(locator); - Map result = new HashMap(); - for(Route r : locator.getRoutes()) { - result.put(r.getFullPath(), r.getLocation()); - } - assertEquals(result , endpoint.invoke()); - } - - @Test - public void testInvokeRouteDetails() { - RoutesEndpoint endpoint = new RoutesEndpoint(locator); - Map results = new HashMap<>(); - for (Route route : locator.getRoutes()) { - results.put(route.getFullPath(), new RoutesEndpoint.RouteDetails(route)); - } - assertEquals(results, endpoint.invokeRouteDetails()); - } - -} \ No newline at end of file diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ServletPathZuulProxyApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ServletPathZuulProxyApplicationTests.java deleted file mode 100644 index b1cecc39..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ServletPathZuulProxyApplicationTests.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import java.net.URI; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute; -import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import com.netflix.zuul.context.RequestContext; - -import static org.junit.Assert.assertEquals; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = ServletPathZuulProxyApplicationTests.ServletPathZuulProxyApplication.class, webEnvironment = RANDOM_PORT, properties = { - "server.servlet.path: /app" }) -@DirtiesContext -public class ServletPathZuulProxyApplicationTests { - - @LocalServerPort - private int port; - - @Autowired - private TestRestTemplate testRestTemplate; - - @Autowired - private DiscoveryClientRouteLocator routes; - - @Autowired - private RoutesEndpoint endpoint; - - @Before - public void setTestRequestContext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void getOnSelfViaSimpleHostRoutingFilter() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app/local"); - this.endpoint.reset(); - ResponseEntity result = testRestTemplate.exchange("/app/self/1", - HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Gotten 1!", result.getBody()); - } - - @Test - public void optionsOnRawEndpoint() throws Exception { - ResponseEntity result = testRestTemplate.exchange( - RequestEntity.options(new URI("/app/local/1")) - .header("Origin", "http://localhost:9000") - .header("Access-Control-Request-Method", "GET").build(), - String.class); - HttpHeaders httpHeaders = result.getHeaders(); - - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("*", httpHeaders.getFirst("Access-Control-Allow-Origin")); - } - - @Test - public void optionsOnSelf() throws Exception { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app/local"); - this.endpoint.reset(); - ResponseEntity result = testRestTemplate.exchange( - RequestEntity.options(new URI("/app/self/1")) - .header("Origin", "http://localhost:9000") - .header("Access-Control-Request-Method", "GET").build(), - String.class); - HttpHeaders httpHeaders = result.getHeaders(); - - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("*", httpHeaders.getFirst("Access-Control-Allow-Origin")); - } - - @Test - public void contentOnRawEndpoint() throws Exception { - ResponseEntity result = testRestTemplate.exchange( - RequestEntity.get(new URI("/app/local/1")).build(), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Gotten 1!", result.getBody()); - } - - @Test - public void stripPrefixFalseAppendsPath() { - this.routes.addRoute(new ZuulRoute("strip", "/strip/**", "strip", - "http://localhost:" + this.port + "/app/local", false, false, null)); - this.endpoint.reset(); - ResponseEntity result = testRestTemplate.exchange("/app/strip", - HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - // Prefix not stripped to it goes to /local/strip - assertEquals("Gotten strip!", result.getBody()); - } - - // Don't use @SpringBootApplication because we don't want to component scan - @Configuration - @EnableAutoConfiguration - @RestController - @EnableZuulProxy - static class ServletPathZuulProxyApplication { - - @RequestMapping(value = "/local/{id}", method = RequestMethod.GET) - @CrossOrigin(origins = "*") - public String get(@PathVariable String id) { - return "Gotten " + id + "!"; - } - - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/SimpleZuulProxyApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/SimpleZuulProxyApplicationTests.java deleted file mode 100644 index 2bd02c0c..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/SimpleZuulProxyApplicationTests.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import java.net.URI; -import java.net.URISyntaxException; - -import javax.servlet.http.HttpServletRequest; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import com.netflix.zuul.context.RequestContext; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = SimpleZuulProxyApplicationTests.SimpleZuulProxyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { - "zuul.forceOriginalQueryStringEncoding: true" }) -@DirtiesContext -public class SimpleZuulProxyApplicationTests { - - @LocalServerPort - private int port; - - @Autowired - private TestRestTemplate testRestTemplate; - - @Autowired - private DiscoveryClientRouteLocator routes; - - @Autowired - private RoutesEndpoint endpoint; - - @Before - public void setTestRequestContext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - - this.routes.addRoute("/foo/**", "http://localhost:" + this.port + "/bar"); - this.endpoint.reset(); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void getOnSelfViaSimpleHostRoutingFilter() { - ResponseEntity result = executeSimpleRequest(HttpMethod.GET); - - assertResponseCodeAndBody(result, "get bar"); - } - - @Test - public void postOnSelfViaSimpleHostRoutingFilter() { - ResponseEntity result = executeSimpleRequest(HttpMethod.POST); - - assertResponseCodeAndBody(result, "post bar"); - } - - @Test - public void putOnSelfViaSimpleHostRoutingFilter() { - ResponseEntity result = executeSimpleRequest(HttpMethod.PUT); - - assertResponseCodeAndBody(result, "put bar"); - } - - @Test - public void patchOnSelfViaSimpleHostRoutingFilter() { - ResponseEntity result = executeSimpleRequest(HttpMethod.PATCH); - - assertResponseCodeAndBody(result, "patch bar"); - } - - @Test - public void deleteOnSelfViaSimpleHostRoutingFilter() { - ResponseEntity result = executeSimpleRequest(HttpMethod.DELETE); - - assertResponseCodeAndBody(result, "delete bar"); - } - - @Test - public void getOnSelfWithComplexQueryParam() throws URISyntaxException { - String encodedQueryString = "foo=%7B%22project%22%3A%22stream%22%2C%22logger%22%3A%22javascript%22%2C%22platform%22%3A%22javascript%22%2C%22request%22%3A%7B%22url%22%3A%22https%3A%2F%2Ffoo%2Fadmin"; - ResponseEntity result = testRestTemplate.exchange( - new URI("/foo?" + encodedQueryString), HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals(encodedQueryString, result.getBody()); - } - - private void assertResponseCodeAndBody(ResponseEntity result, - String expectedBody) { - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals(expectedBody, result.getBody()); - } - - private ResponseEntity executeSimpleRequest(HttpMethod httpMethod) { - ResponseEntity result = testRestTemplate.exchange("/foo?id=bar", - httpMethod, new HttpEntity<>((Void) null), String.class); - return result; - } - - // Don't use @SpringBootApplication because we don't want to component scan - @Configuration - @EnableAutoConfiguration - @RestController - @EnableZuulProxy - static class SimpleZuulProxyApplication { - - @RequestMapping(value = "/bar", method = RequestMethod.GET) - public String get(@RequestParam String id) { - return "get " + id; - } - - @RequestMapping(value = "/bar", method = RequestMethod.GET, params = { "foo" }) - public String complexGet(@RequestParam String foo, HttpServletRequest request) { - return request.getQueryString(); - } - - @RequestMapping(value = "/bar", method = RequestMethod.POST) - public String post(@RequestParam String id) { - return "post " + id; - } - - @RequestMapping(value = "/bar", method = RequestMethod.PUT) - public String put(@RequestParam String id) { - return "put " + id; - } - - @RequestMapping(value = "/bar", method = RequestMethod.DELETE) - public String delete(@RequestParam String id) { - return "delete " + id; - } - - @RequestMapping(value = "/bar", method = RequestMethod.PATCH) - public String patch(@RequestParam String id) { - return "patch " + id; - } - - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/SimpleZuulServerApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/SimpleZuulServerApplicationTests.java deleted file mode 100644 index b72675ad..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/SimpleZuulServerApplicationTests.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.cloud.netflix.zuul.filters.RouteLocator; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = SimpleZuulServerApplication.class, webEnvironment = RANDOM_PORT, - properties = "zuul.routes[testclient]:/testing123/**") -@DirtiesContext -public class SimpleZuulServerApplicationTests { - - @LocalServerPort - private int port; - - @Autowired - private TestRestTemplate testRestTemplate; - - @Autowired - private RouteLocator routes; - - private String getRoute(String path) { - return this.routes.getMatchingRoute(path).getLocation(); - } - - @Before - public void setTestRequestContext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void bindRoute() { - assertNotNull(getRoute("/testing123/**")); - } - - @Test - public void getOnSelf() { - ResponseEntity result = testRestTemplate.exchange("/", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Hello world", result.getBody()); - } - - @Test - public void getOnSelfViaFilter() { - ResponseEntity result = testRestTemplate.exchange("/testing123/1", - HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - } - -} - -// Don't use @SpringBootApplication because we don't want to component scan -@Configuration -@EnableAutoConfiguration -@RestController -@EnableZuulServer -class SimpleZuulServerApplication { - - @RequestMapping("/local") - public String local() { - return "Hello local"; - } - - @RequestMapping("/") - public String home() { - return "Hello world"; - } - - @Bean - public ZuulFilter sampleFilter() { - return new ZuulFilter() { - @Override - public String filterType() { - return PRE_TYPE; - } - - @Override - public boolean shouldFilter() { - return true; - } - - @Override - public Object run() { - return null; - } - - @Override - public int filterOrder() { - return 0; - } - }; - } - - public static void main(String[] args) { - SpringApplication.run(SimpleZuulServerApplication.class, args); - } - -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulFilterInitializerTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulFilterInitializerTests.java deleted file mode 100644 index 64e1ab71..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulFilterInitializerTests.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.util.ReflectionUtils; - -import com.netflix.zuul.FilterLoader; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.filters.FilterRegistry; -import com.netflix.zuul.monitoring.CounterFactory; -import com.netflix.zuul.monitoring.TracerFactory; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; - -public class ZuulFilterInitializerTests { - - private Map filters = getFilters(); - private CounterFactory counterFactory = mock(CounterFactory.class); - private TracerFactory tracerFactory = mock(TracerFactory.class); - private FilterLoader filterLoader = new FilterLoader(); - private FilterRegistry filterRegistry = getFilterRegistry(); - - private final ZuulFilterInitializer initializer = new ZuulFilterInitializer(filters, - counterFactory, tracerFactory, filterLoader, filterRegistry); - - @Test - public void shouldSetupOnContextInitializedEvent() throws Exception { - initializer.contextInitialized(); - - assertEquals(tracerFactory, TracerFactory.instance()); - assertEquals(counterFactory, CounterFactory.instance()); - assertThat(filterRegistry.getAllFilters()) - .containsAll(filters.values()); - } - - @Test - public void shouldCleanupOnContextDestroyed() throws Exception { - initializer.contextDestroyed(); - - assertEquals(null, ReflectionTestUtils.getField(TracerFactory.class, "INSTANCE")); - assertEquals(null, - ReflectionTestUtils.getField(CounterFactory.class, "INSTANCE")); - assertTrue(FilterRegistry.instance().getAllFilters().isEmpty()); - assertTrue(getHashFiltersByType().isEmpty()); - } - - private Map getHashFiltersByType() { - Field field = ReflectionUtils.findField(FilterLoader.class, "hashFiltersByType"); - ReflectionUtils.makeAccessible(field); - return (Map) ReflectionUtils.getField(field, FilterLoader.getInstance()); - } - - private Map getFilters() { - Map filters = new HashMap<>(); - filters.put("key1", mock(ZuulFilter.class)); - filters.put("key2", mock(ZuulFilter.class)); - return filters; - } - - private FilterRegistry getFilterRegistry() { - try { - Constructor constructor = FilterRegistry.class - .getDeclaredConstructor(new Class[0]); - constructor.setAccessible(true); - return constructor.newInstance(new Object[0]); - } - catch (Exception e) { - throw new RuntimeException(e); - } - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyApplicationTests.java deleted file mode 100644 index 6b28c47f..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyApplicationTests.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.zuul.context.RequestContext; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.StaticServerList; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = ZuulProxyApplicationTests.ZuulProxyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT, properties = { - "zuul.routes.simplezpat:/simplezpat/**", "logging.level.org.apache.http: DEBUG" }) -@DirtiesContext -public class ZuulProxyApplicationTests { - - @LocalServerPort - private int port; - - @Before - public void setTestRequestcontext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void getHasCorrectTransferEncoding() { - ResponseEntity result = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/simplezpat/transferencoding", - String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("missing", result.getBody()); - } - - @Test - public void postHasCorrectTransferEncoding() { - ResponseEntity result = new TestRestTemplate().postForEntity( - "http://localhost:" + this.port + "/simplezpat/transferencoding", - new HttpEntity<>("hello"), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("missing", result.getBody()); - } - - // Don't use @SpringBootApplication because we don't want to component scan - @Configuration - @EnableAutoConfiguration - @RestController - @EnableZuulProxy - @RibbonClient(name = "simplezpat", configuration = TestRibbonClientConfiguration.class) - static class ZuulProxyApplication { - - @RequestMapping(value = "/transferencoding", method = RequestMethod.GET) - public String get( - @RequestHeader(name = "Transfer-Encoding", required = false) String transferEncoding) { - if (transferEncoding == null) { - return "missing"; - } - return transferEncoding; - } - - @RequestMapping(value = "/transferencoding", method = RequestMethod.POST) - public String post( - @RequestHeader(name = "Transfer-Encoding", required = false) String transferEncoding, - @RequestBody String hello) { - if (transferEncoding == null) { - return "missing"; - } - return transferEncoding; - } - - } - - // Load balancer with fixed server list for "simplezpat" pointing to localhost - @Configuration - static class TestRibbonClientConfiguration { - - @LocalServerPort - private int port; - - @Bean - public ServerList ribbonServerList() { - return new StaticServerList<>(new Server("localhost", this.port)); - } - - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyAutoConfigurationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyAutoConfigurationTests.java deleted file mode 100644 index c374d823..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyAutoConfigurationTests.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.zuul.filters.CompositeRouteLocator; -import org.springframework.cloud.netflix.zuul.filters.RouteLocator; -import org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * To test the auto-configuration of Zuul Proxy - * - * @author Biju Kunjummen - * - */ - -@RunWith(SpringRunner.class) -@SpringBootTest -@DirtiesContext -public class ZuulProxyAutoConfigurationTests { - - @Autowired - private RouteLocator routeLocator; - - @Autowired(required = false) - private RibbonRoutingFilter ribbonRoutingFilter; - - @Test - public void testAutoConfiguredBeans() { - assertThat(routeLocator).isInstanceOf(CompositeRouteLocator.class); - assertThat(this.ribbonRoutingFilter).isNotNull(); - } - - @Configuration - @EnableAutoConfiguration - @EnableZuulProxy - static class TestConfig { - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyConfigurationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyConfigurationTests.java deleted file mode 100644 index 67b087b4..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyConfigurationTests.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; - -import org.junit.Test; -import org.springframework.boot.autoconfigure.web.ServerProperties; -import org.springframework.boot.test.util.EnvironmentTestUtils; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.zuul.filters.route.RestClientRibbonCommandFactory; -import org.springframework.cloud.netflix.zuul.filters.route.RibbonCommandFactory; -import org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFactory; -import org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommandFactory; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; - -/** - * @author Spencer Gibb - * @author Biju Kunjummen - */ -public class ZuulProxyConfigurationTests { - - @Test - public void testDefaultsToApacheHttpClient() { - testClient(HttpClientRibbonCommandFactory.class, null); - testClient(HttpClientRibbonCommandFactory.class, "ribbon.httpclient.enabled=true"); - } - - @Test - public void testEnableRestClient() { - testClient(RestClientRibbonCommandFactory.class, "ribbon.restclient.enabled=true"); - } - - @Test - public void testEnableOkHttpClient() { - testClient(OkHttpRibbonCommandFactory.class, "ribbon.okhttp.enabled=true"); - } - - void testClient(Class clientType, String property) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - context.register(TestConfig.class, ZuulProxyMarkerConfiguration.class, - ZuulProxyAutoConfiguration.class); - if (property != null) { - EnvironmentTestUtils.addEnvironment(context, property); - } - context.refresh(); - RibbonCommandFactory factory = context.getBean(RibbonCommandFactory.class); - assertThat("RibbonCommandFactory is wrong type for property: " + property, factory, is(instanceOf(clientType))); - context.close(); - } - - static class TestConfig { - @Bean - ServerProperties serverProperties() { - return new ServerProperties(); - } - - @Bean - SpringClientFactory springClientFactory() { - return mock(SpringClientFactory.class); - } - - @Bean - DiscoveryClient discoveryClient() { - return mock(DiscoveryClient.class); - } - } - -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulServerAutoConfigurationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulServerAutoConfigurationTests.java deleted file mode 100644 index 95c8f8c1..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulServerAutoConfigurationTests.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.zuul.filters.CompositeRouteLocator; -import org.springframework.cloud.netflix.zuul.filters.RouteLocator; -import org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * To test the auto-configuration of Zuul Proxy - * - * @author Biju Kunjummen - * - */ - -@RunWith(SpringRunner.class) -@SpringBootTest -public class ZuulServerAutoConfigurationTests { - - @Autowired - private RouteLocator routeLocator; - - @Autowired(required = false) - private RibbonRoutingFilter ribbonRoutingFilter; - - @Test - public void testAutoConfiguredBeans() { - assertThat(routeLocator).isInstanceOf(CompositeRouteLocator.class); - assertThat(ribbonRoutingFilter).isNull(); - } - - - @Configuration - @EnableAutoConfiguration - @EnableZuulServer - static class TestConfig { - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/CompositeRouteLocatorTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/CompositeRouteLocatorTests.java deleted file mode 100644 index abe5b3f4..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/CompositeRouteLocatorTests.java +++ /dev/null @@ -1,97 +0,0 @@ -package org.springframework.cloud.netflix.zuul.filters; - -import static java.util.Arrays.asList; -import static org.hamcrest.CoreMatchers.hasItems; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.junit.Test; - -/** - * @author Johannes Edmeier - */ -public class CompositeRouteLocatorTests { - private CompositeRouteLocator locator; - - public CompositeRouteLocatorTests() { - List locators = new ArrayList<>(); - locators.add(new TestRouteLocator(asList("ign1"), - asList(createRoute("1", "/pathA")))); - locators.add( - new TestRouteLocator(asList("ign1", "ign2"), - asList(createRoute("2", "/pathA"), createRoute("2", "/pathB")))); - this.locator = new CompositeRouteLocator(locators); - } - - @Test - public void test_getIgnoredPaths() { - assertThat(locator.getIgnoredPaths(), hasItems("ign1", "ign2")); - - } - - @Test - public void test_getRoutes() { - assertThat(locator.getRoutes(), - hasItems(createRoute("1", "/pathA"), createRoute("2", "/pathB"))); - } - - @Test - public void test_getMatchingRoute() { - assertThat(locator.getMatchingRoute("/pathA"), notNullValue()); - assertThat(locator.getMatchingRoute("/pathA").getId(), is("1")); - assertThat("Locator 1 should take precedence", locator.getMatchingRoute("/pathB").getId(), - is("2")); - assertThat(locator.getMatchingRoute("/pathNot"), nullValue()); - } - - @Test - public void test_refresh() { - RefreshableRouteLocator mock = mock(RefreshableRouteLocator.class); - new CompositeRouteLocator(asList(mock)).refresh(); - verify(mock).refresh(); - } - - private Route createRoute(String id, String path) { - return new Route(id, path, null, null, false, Collections.emptySet()); - } - - private static class TestRouteLocator implements RouteLocator { - private Collection ignoredPaths; - private List routes; - - public TestRouteLocator(Collection ignoredPaths, List routes) { - this.ignoredPaths = ignoredPaths; - this.routes = routes; - } - - @Override - public Collection getIgnoredPaths() { - return this.ignoredPaths; - } - - @Override - public List getRoutes() { - return this.routes; - } - - @Override - public Route getMatchingRoute(String path) { - for (Route route : routes) { - if (path.startsWith(route.getPath())) { - return route; - } - } - return null; - } - - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/CustomHostRoutingFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/CustomHostRoutingFilterTests.java deleted file mode 100644 index d7a8250d..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/CustomHostRoutingFilterTests.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters; - -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.http.client.config.CookieSpecs; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory; -import org.springframework.cloud.commons.httpclient.DefaultApacheHttpClientFactory; -import org.springframework.cloud.netflix.feign.ribbon.FeignRibbonClientAutoConfiguration; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.cloud.netflix.zuul.RoutesEndpoint; -import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; -import org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; - -import com.netflix.zuul.context.RequestContext; - -import static junit.framework.TestCase.assertFalse; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = SampleCustomZuulProxyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { - "server.servlet.contextPath: /app" }) -@DirtiesContext -public class CustomHostRoutingFilterTests { - - @Value("${local.server.port}") - private int port; - - @Autowired - private DiscoveryClientRouteLocator routes; - - @Autowired - private RoutesEndpoint endpoint; - - @Before - public void setTestRequestcontext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void getOnSelfViaCustomHostRoutingFilter() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app"); - this.endpoint.reset(); - ResponseEntity result = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/app/self/get/1", String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Get 1", result.getBody()); - } - - @Test - public void postOnSelfViaCustomHostRoutingFilter() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app"); - this.endpoint.reset(); - MultiValueMap params = new LinkedMultiValueMap<>(); - params.add("id", "2"); - ResponseEntity result = new TestRestTemplate().postForEntity( - "http://localhost:" + this.port + "/app/self/post", params, String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Post 2", result.getBody()); - } - - @Test - public void putOnSelfViaCustomHostRoutingFilter() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app"); - this.endpoint.reset(); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/app/self/put/3", HttpMethod.PUT, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Put 3", result.getBody()); - } - - @Test - public void patchOnSelfViaCustomHostRoutingFilter() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app"); - this.endpoint.reset(); - MultiValueMap params = new LinkedMultiValueMap<>(); - params.add("patch", "5"); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/app/self/patch/4", HttpMethod.PATCH, - new HttpEntity<>(params), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Patch 45", result.getBody()); - } - - @Test - public void getOnSelfIgnoredHeaders() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app"); - this.endpoint.reset(); - ResponseEntity result = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/app/self/get/1", String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertTrue(result.getHeaders().containsKey("X-NotIgnored")); - assertFalse(result.getHeaders().containsKey("X-Ignored")); - } - - @Test - public void getOnSelfWithSessionCookie() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app"); - this.endpoint.reset(); - - RestTemplate restTemplate = new RestTemplate(); - - ResponseEntity result1 = restTemplate.getForEntity( - "http://localhost:" + this.port + "/app/self/cookie/1", String.class); - - ResponseEntity result2 = restTemplate.getForEntity( - "http://localhost:" + this.port + "/app/self/cookie/2", String.class); - - assertEquals("SetCookie 1", result1.getBody()); - assertEquals("GetCookie 1", result2.getBody()); - } - -} - -@Configuration -@EnableAutoConfiguration -@RestController -class SampleCustomZuulProxyApplication { - - @RequestMapping(value = "/get/{id}", method = RequestMethod.GET) - public String get(@PathVariable String id, HttpServletResponse response) { - response.setHeader("X-Ignored", "foo"); - response.setHeader("X-NotIgnored", "bar"); - return "Get " + id; - } - - @RequestMapping(value = "/cookie/{id}", method = RequestMethod.GET) - public String getWithCookie(@PathVariable String id, HttpSession session) { - Object testCookie = session.getAttribute("testCookie"); - if (testCookie != null) { - return "GetCookie " + testCookie; - } - session.setAttribute("testCookie", id); - return "SetCookie " + id; - } - - @RequestMapping(value = "/post", method = RequestMethod.POST) - public String post(@RequestParam("id") String id) { - return "Post " + id; - } - - @RequestMapping(value = "/put/{id}", method = RequestMethod.PUT) - public String put(@PathVariable String id) { - return "Put " + id; - } - - @RequestMapping(value = "/patch/{id}", method = RequestMethod.PATCH) - public String patch(@PathVariable String id, @RequestParam("patch") String patch) { - return "Patch " + id + patch; - } - - public static void main(String[] args) { - SpringApplication.run(SampleCustomZuulProxyApplication.class, args); - } - - @Configuration - @EnableZuulProxy - @AutoConfigureBefore({FeignRibbonClientAutoConfiguration.class}) - protected static class CustomZuulProxyConfig { - - @Bean - public ApacheHttpClientFactory customHttpClientFactory(HttpClientBuilder builder) { - return new CustomApacheHttpClientFactory(builder); - } - - @Bean - public CloseableHttpClient closeableClient() { - return HttpClients.custom() - .setDefaultCookieStore(new BasicCookieStore()) - .setDefaultRequestConfig(RequestConfig.custom() - .setCookieSpec(CookieSpecs.DEFAULT).build()) - .build(); - } - - @Bean - public SimpleHostRoutingFilter simpleHostRoutingFilter(ProxyRequestHelper helper, - ZuulProperties zuulProperties, CloseableHttpClient httpClient) { - return new CustomHostRoutingFilter(helper, zuulProperties, httpClient); - } - - private class CustomHostRoutingFilter extends SimpleHostRoutingFilter { - public CustomHostRoutingFilter(ProxyRequestHelper helper, - ZuulProperties zuulProperties, CloseableHttpClient httpClient) { - super(helper, zuulProperties, httpClient); - } - - @Override - public Object run() { - super.addIgnoredHeaders("X-Ignored"); - return super.run(); - } - } - - - private class CustomApacheHttpClientFactory extends DefaultApacheHttpClientFactory { - public CustomApacheHttpClientFactory(HttpClientBuilder builder) { - super(builder); - } - } - } - -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/ProxyRequestHelperTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/ProxyRequestHelperTests.java deleted file mode 100644 index d8e6c809..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/ProxyRequestHelperTests.java +++ /dev/null @@ -1,352 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters; - -import java.io.IOException; -import java.util.List; - -import com.netflix.zuul.context.RequestContext; - -import org.assertj.core.api.Assertions; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; - -import org.springframework.boot.actuate.web.trace.HttpTrace; -import org.springframework.boot.actuate.web.trace.HttpTraceRepository; -import org.springframework.boot.actuate.web.trace.InMemoryHttpTraceRepository; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; - -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.MockitoAnnotations.initMocks; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.REQUEST_URI_KEY; - -/** - * @author Spencer Gibb - */ -public class ProxyRequestHelperTests { - - @Mock - private HttpTraceRepository traceRepository; - - @Before - public void init() { - initMocks(this); - } - - @Before - public void setTestRequestcontext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void debug() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); - request.setContent("{}".getBytes()); - request.addHeader("singleName", "singleValue"); - request.addHeader("multiName", "multiValue1"); - request.addHeader("multiName", "multiValue2"); - RequestContext.getCurrentContext().setRequest(request); - - TraceProxyRequestHelper helper = new TraceProxyRequestHelper(); - this.traceRepository = new InMemoryHttpTraceRepository(); - helper.setTraces(this.traceRepository); - - MultiValueMap headers = helper.buildZuulRequestHeaders(request); - - helper.debug("POST", "http://example.com", headers, - new LinkedMultiValueMap<>(), request.getInputStream()); - HttpTrace actual = this.traceRepository.findAll().get(0); - Assertions.assertThat(actual.getRequest().getHeaders()).containsKeys("singleName", "multiName"); - } - - @Test - public void shouldDebugBodyDisabled() throws Exception { - RequestContext context = RequestContext.getCurrentContext(); - - ProxyRequestHelper helper = new ProxyRequestHelper(); - helper.setTraceRequestBody(false); - - assertThat("shouldDebugBody wrong", helper.shouldDebugBody(context), is(false)); - } - - @Test - public void shouldDebugBodyChunked() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); - RequestContext context = RequestContext.getCurrentContext(); - context.setChunkedRequestBody(); - context.setRequest(request); - - ProxyRequestHelper helper = new ProxyRequestHelper(); - - assertThat("shouldDebugBody wrong", helper.shouldDebugBody(context), is(false)); - } - - @Test - public void shouldDebugBodyServlet() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); - RequestContext context = RequestContext.getCurrentContext(); - context.setZuulEngineRan(); - context.setRequest(request); - - ProxyRequestHelper helper = new ProxyRequestHelper(); - - assertThat("shouldDebugBody wrong", helper.shouldDebugBody(context), is(false)); - } - - @Test - public void shouldDebugBodyNullContentType() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); - request.setContentType(null); - RequestContext context = RequestContext.getCurrentContext(); - context.setRequest(request); - - ProxyRequestHelper helper = new ProxyRequestHelper(); - - assertThat("shouldDebugBody wrong", helper.shouldDebugBody(context), is(true)); - } - - @Test - public void shouldDebugBodyNullRequest() throws Exception { - RequestContext context = RequestContext.getCurrentContext(); - - ProxyRequestHelper helper = new ProxyRequestHelper(); - - assertThat("shouldDebugBody wrong", helper.shouldDebugBody(context), is(true)); - } - - @Test - public void shouldDebugBodyNotMultitypeContentType() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); - request.setContentType(MediaType.APPLICATION_JSON_VALUE); - RequestContext context = RequestContext.getCurrentContext(); - context.setRequest(request); - - ProxyRequestHelper helper = new ProxyRequestHelper(); - - assertThat("shouldDebugBody wrong", helper.shouldDebugBody(context), is(true)); - } - - @Test - public void shouldDebugBodyMultitypeContentType() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); - request.setContentType(MediaType.MULTIPART_FORM_DATA_VALUE); - RequestContext context = RequestContext.getCurrentContext(); - context.setRequest(request); - - ProxyRequestHelper helper = new ProxyRequestHelper(); - - assertThat("shouldDebugBody wrong", helper.shouldDebugBody(context), is(false)); - } - - @Test - public void buildZuulRequestHeadersWork() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - request.addHeader("singleName", "singleValue"); - request.addHeader("multiName", "multiValue1"); - request.addHeader("multiName", "multiValue2"); - - TraceProxyRequestHelper helper = new TraceProxyRequestHelper(); - helper.setTraces(this.traceRepository); - - MultiValueMap headers = helper.buildZuulRequestHeaders(request); - List singleName = headers.get("singleName"); - assertThat(singleName, is(notNullValue())); - assertThat(singleName.size(), is(1)); - - List multiName = headers.get("multiName"); - assertThat(multiName, is(notNullValue())); - assertThat(multiName.size(), is(2)); - - List missingName = headers.get("missingName"); - assertThat(missingName, is(nullValue())); - - } - - @Test - public void buildZuulRequestHeadersRequestsGzipAndOnlyGzip() { - MockHttpServletRequest request = new MockHttpServletRequest("", "/"); - - ProxyRequestHelper helper = new ProxyRequestHelper(); - - MultiValueMap headers = helper.buildZuulRequestHeaders(request); - - List acceptEncodings = headers.get("accept-encoding"); - assertThat(acceptEncodings, hasSize(1)); - assertThat(acceptEncodings, contains("gzip")); - } - - @Test - public void setResponseLowercase() throws IOException { - MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); - MockHttpServletResponse response = new MockHttpServletResponse(); - - RequestContext context = RequestContext.getCurrentContext(); - context.setRequest(request); - context.setResponse(response); - - ProxyRequestHelper helper = new ProxyRequestHelper(); - - MultiValueMap headers = new HttpHeaders(); - headers.add(HttpHeaders.CONTENT_ENCODING.toLowerCase(), "gzip"); - - helper.setResponse(200, request.getInputStream(), headers); - assertTrue(context.getResponseGZipped()); - } - - @Test - public void setResponseUppercase() throws IOException { - MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); - MockHttpServletResponse response = new MockHttpServletResponse(); - - RequestContext context = RequestContext.getCurrentContext(); - context.setRequest(request); - context.setResponse(response); - - ProxyRequestHelper helper = new ProxyRequestHelper(); - - MultiValueMap headers = new HttpHeaders(); - headers.add(HttpHeaders.CONTENT_ENCODING, "gzip"); - - helper.setResponse(200, request.getInputStream(), headers); - assertTrue(context.getResponseGZipped()); - } - - @Test - public void getQueryString() { - MultiValueMap params = new LinkedMultiValueMap<>(); - params.add("a", "1234"); - params.add("b", "5678"); - - String queryString = new ProxyRequestHelper().getQueryString(params); - - assertThat(queryString, is("?a=1234&b=5678")); - } - - @Test - public void getQueryStringWithEmptyParam() { - MultiValueMap params = new LinkedMultiValueMap<>(); - params.add("wsdl", ""); - - String queryString = new ProxyRequestHelper().getQueryString(params); - - assertThat(queryString, is("?wsdl")); - } - - @Test - public void getQueryStringEncoded() { - MultiValueMap params = new LinkedMultiValueMap<>(); - params.add("foo", "weird#chars"); - - String queryString = new ProxyRequestHelper().getQueryString(params); - - assertThat(queryString, is("?foo=weird%23chars")); - } - - @Test - public void getQueryParamNameWithColon() { - MultiValueMap params = new LinkedMultiValueMap<>(); - params.add("foo:bar", "baz"); - params.add("foobar", "bam"); - params.add("foo\fbar", "bat"); // form feed is the colon replacement char - - String queryString = new ProxyRequestHelper().getQueryString(params); - - assertThat(queryString, is("?foo:bar=baz&foobar=bam&foo%0Cbar=bat")); - } - - @Test - public void buildZuulRequestURIWithUTF8() throws Exception { - String encodedURI = "/resource/esp%C3%A9cial-char"; - String decodedURI = "/resource/espécial-char"; - - MockHttpServletRequest request = new MockHttpServletRequest("GET", encodedURI); - request.setCharacterEncoding("UTF-8"); - final RequestContext context = RequestContext.getCurrentContext(); - context.setRequest(request); - context.set(REQUEST_URI_KEY, decodedURI); - - final String requestURI = new ProxyRequestHelper().buildZuulRequestURI(request); - assertThat(requestURI, equalTo(encodedURI)); - } - - @Test - public void buildZuulRequestURIWithDefaultEncoding() { - String encodedURI = "/resource/esp%E9cial-char"; - String decodedURI = "/resource/espécial-char"; - - MockHttpServletRequest request = new MockHttpServletRequest("GET", encodedURI); - final RequestContext context = RequestContext.getCurrentContext(); - context.setRequest(request); - context.set(REQUEST_URI_KEY, decodedURI); - - final String requestURI = new ProxyRequestHelper().buildZuulRequestURI(request); - assertThat(requestURI, equalTo(encodedURI)); - } - - @Test - public void getUTF8Url() { - String requestURI = "/oléדרעק"; - String encodedRequestURI = "/ol%C3%A9%D7%93%D7%A8%D7%A2%D7%A7"; - MockHttpServletRequest request = new MockHttpServletRequest("GET", requestURI); - request.setCharacterEncoding("UTF-8"); - - RequestContext context = RequestContext.getCurrentContext(); - context.set(REQUEST_URI_KEY, requestURI); - - ProxyRequestHelper helper = new ProxyRequestHelper(); - - String uri = helper.buildZuulRequestURI(request); - - assertThat(uri, is(encodedRequestURI)); - } - - @Test - public void getDefaultEncodingUrl() { - String requestURI = "/oléדרעק"; - String encodedRequestURI = "/ol%E9%3F%3F%3F%3F"; - MockHttpServletRequest request = new MockHttpServletRequest("GET", requestURI); - - RequestContext context = RequestContext.getCurrentContext(); - context.set(REQUEST_URI_KEY, requestURI); - - ProxyRequestHelper helper = new ProxyRequestHelper(); - - String uri = helper.buildZuulRequestURI(request); - - assertThat(uri, is(encodedRequestURI)); - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/SimpleRouteLocatorTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/SimpleRouteLocatorTests.java deleted file mode 100644 index 2f4ef1f0..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/SimpleRouteLocatorTests.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2013-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.collection.IsCollectionWithSize.hasSize; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import org.junit.Test; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute; - -/** - * @author Tom Cawley - */ -public class SimpleRouteLocatorTests { - private ZuulProperties zuul = new ZuulProperties(); - - public SimpleRouteLocatorTests() { - } - - @Test - public void test_getRoutesDefaultRouteAcceptor() { - RouteLocator locator = new SimpleRouteLocator("/", this.zuul); - this.zuul.getRoutes().clear(); - this.zuul.getRoutes().put("foo", new ZuulRoute("/foo/**", "foo")); - - assertThat(locator.getRoutes(), hasItem(createRoute("foo", "/**", "/foo"))); - } - - @Test - public void test_getRoutesFilterRouteAcceptor() { - RouteLocator locator = new FilteringRouteLocator("/", this.zuul); - this.zuul.getRoutes().clear(); - this.zuul.getRoutes().put("foo", new ZuulRoute("/foo/**", "foo")); - this.zuul.getRoutes().put("bar", new ZuulRoute("/bar/**", "bar")); - - final List routes = locator.getRoutes(); - assertThat(routes, hasItem(createRoute("bar", "/**", "/bar"))); - assertThat(routes, hasSize(1)); - } - - @Test - public void testStripPrefix() { - ZuulProperties properties = new ZuulProperties(); - properties.setPrefix("/test"); - properties.setStripPrefix(true); - RouteLocator locator = new FilteringRouteLocator("/", properties); - properties.getRoutes().put("testservicea", new ZuulRoute("/testservicea/**", "testservicea")); - assertEquals("/test/testservicea/**", locator.getRoutes().get(0).getFullPath()); - } - - @Test - public void testPrefix() { - ZuulProperties properties = new ZuulProperties(); - properties.setPrefix("/test/"); - RouteLocator locator = new FilteringRouteLocator("/", properties); - properties.getRoutes().put("testservicea", new ZuulRoute("/testservicea/**", "testservicea")); - assertEquals("/test/testservicea/**", locator.getRoutes().get(0).getFullPath()); - } - - @Test - public void test_getMatchingRouteFilterRouteAcceptor() { - RouteLocator locator = new FilteringRouteLocator("/", this.zuul); - this.zuul.getRoutes().clear(); - this.zuul.getRoutes().put("foo", new ZuulRoute("/foo/**", "foo")); - this.zuul.getRoutes().put("bar", new ZuulRoute("/bar/**", "bar")); - - assertThat(locator.getMatchingRoute("/foo/1"), nullValue()); - assertThat(locator.getMatchingRoute("/bar/1"), is(createRoute("bar", "/1", "/bar"))); - } - - private Route createRoute(String id, String path, String prefix) { - return new Route(id, path, id, prefix, false, null); - } - - private static class FilteringRouteLocator extends SimpleRouteLocator { - public FilteringRouteLocator(String servletPath, ZuulProperties properties) { - super(servletPath, properties); - } - - @Override - public List getRoutes() { - List values = new ArrayList<>(); - - for (Entry entry : getRoutesMap().entrySet()) { - ZuulRoute route = entry.getValue(); - if (acceptRoute(route)) { - String path = route.getPath(); - values.add(getRoute(route, path)); - } - } - return values; - } - - private boolean acceptRoute(ZuulRoute route) { - return route != null && !(route.getId().equals("foo")); - } - - protected Route getRoute(ZuulRoute route, String path) { - if (acceptRoute(route)) { - return super.getRoute(route, path); - } - return null; - } - - // For testing, expose as public so we can call getRoutesMap() directly. - @Override - public Map getRoutesMap() { - return super.getRoutesMap(); - } - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/ZuulPropertiesTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/ZuulPropertiesTests.java deleted file mode 100644 index 1f0c271c..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/ZuulPropertiesTests.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters; - -import java.util.Arrays; -import java.util.Collections; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - * @author Dave Syer - * @author Mathias Düsterhöft - */ -public class ZuulPropertiesTests { - - private ZuulProperties zuul; - - @Before - public void setup() { - this.zuul = new ZuulProperties(); - } - - @After - public void teardown() { - this.zuul = null; - } - - @Test - public void defaultIgnoredHeaders() { - assertThat(this.zuul.isIgnoreSecurityHeaders()).isTrue(); - assertThat(this.zuul.getIgnoredHeaders()) - .containsAll(ZuulProperties.SECURITY_HEADERS); - } - - @Test - public void securityHeadersNotIgnored() { - zuul.setIgnoreSecurityHeaders(false); - - assertTrue(this.zuul.getIgnoredHeaders().isEmpty()); - } - - @Test - public void addIgnoredHeaders() { - this.zuul.setIgnoredHeaders(Collections.singleton("x-foo")); - assertTrue(this.zuul.getIgnoredHeaders().contains("x-foo")); - } - - @Test - public void defaultSensitiveHeaders() { - ZuulRoute route = new ZuulRoute("foo"); - this.zuul.getRoutes().put("foo", route); - assertTrue(this.zuul.getRoutes().get("foo").getSensitiveHeaders().isEmpty()); - assertTrue(this.zuul.getSensitiveHeaders() - .containsAll(Arrays.asList("Cookie", "Set-Cookie", "Authorization"))); - assertFalse(route.isCustomSensitiveHeaders()); - } - - @Test - public void addSensitiveHeaders() { - this.zuul.setSensitiveHeaders(Collections.singleton("x-bar")); - ZuulRoute route = new ZuulRoute("foo"); - route.setSensitiveHeaders(Collections.singleton("x-foo")); - this.zuul.getRoutes().put("foo", route); - ZuulRoute foo = this.zuul.getRoutes().get("foo"); - assertTrue(foo.getSensitiveHeaders().contains("x-foo")); - assertFalse(foo.getSensitiveHeaders().contains("Cookie")); - assertTrue(foo.isCustomSensitiveHeaders()); - assertTrue(this.zuul.getSensitiveHeaders().contains("x-bar")); - assertFalse(this.zuul.getSensitiveHeaders().contains("Cookie")); - } - - @Test - public void createWithSensitiveHeaders() { - this.zuul.setSensitiveHeaders(Collections.singleton("x-bar")); - ZuulRoute route = new ZuulRoute("foo", "/path", "foo", "/path", - false, false, Collections.singleton("x-foo")); - this.zuul.getRoutes().put("foo", route); - ZuulRoute foo = this.zuul.getRoutes().get("foo"); - assertTrue(foo.getSensitiveHeaders().contains("x-foo")); - assertFalse(foo.getSensitiveHeaders().contains("Cookie")); - assertTrue(foo.isCustomSensitiveHeaders()); - assertTrue(this.zuul.getSensitiveHeaders().contains("x-bar")); - assertFalse(this.zuul.getSensitiveHeaders().contains("Cookie")); - } - - @Test - public void defaultHystrixThreadPool() { - assertFalse(this.zuul.getThreadPool().isUseSeparateThreadPools()); - assertEquals("", this.zuul.getThreadPool().getThreadPoolKeyPrefix()); - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/DiscoveryClientRouteLocatorTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/DiscoveryClientRouteLocatorTests.java deleted file mode 100644 index 0b07485b..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/DiscoveryClientRouteLocatorTests.java +++ /dev/null @@ -1,745 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.discovery; - -import java.net.URI; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.client.serviceregistry.Registration; -import org.springframework.cloud.netflix.zuul.filters.Route; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute; -import org.springframework.cloud.netflix.zuul.util.RequestUtils; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.netflix.zuul.context.RequestContext; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.MockitoAnnotations.initMocks; - -/** - * @author Spencer Gibb - * @author Dave Syer - */ -public class DiscoveryClientRouteLocatorTests { - - public static final String IGNOREDSERVICE = "ignoredservice"; - - public static final String IGNOREDPATTERN = "/foo/**"; - - public static final String ASERVICE = "aservice"; - - public static final String MYSERVICE = "myservice"; - - @Mock - private ConfigurableEnvironment env; - - @Mock - private DiscoveryClient discovery; - - private ZuulProperties properties = new ZuulProperties(); - - public static class RegexMapper { - private boolean enabled = false; - - private String servicePattern = "(?.*)-(?v.*$)"; - - private String routePattern = "${version}/${name}"; - - public RegexMapper() { - } - - public RegexMapper(boolean enabled, String servicePattern, String routePattern) { - this.enabled = enabled; - this.servicePattern = servicePattern; - this.routePattern = routePattern; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getServicePattern() { - return servicePattern; - } - - public void setServicePattern(String servicePattern) { - this.servicePattern = servicePattern; - } - - public String getRoutePattern() { - return routePattern; - } - - public void setRoutePattern(String routePattern) { - this.routePattern = routePattern; - } - } - - private RegexMapper regexMapper = new RegexMapper(); - - @Before - public void init() { - initMocks(this); - setTestRequestcontext(); // re-initialize Zuul context for each test - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void testGetMatchingPath() throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.getRoutes().put("foo", new ZuulRoute("/foo/**")); - this.properties.init(); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("foo", route.getId()); - } - - @Test - public void testGetMatchingPathWithPrefix() throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.getRoutes().put("foo", new ZuulRoute("/foo/**")); - this.properties.setPrefix("/proxy"); - this.properties.init(); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/1", route.getPath()); - } - - @Test - public void testGetMatchingPathWithServletPath() throws Exception { - setTestRequestcontext(); - RequestContext.getCurrentContext().set(RequestUtils.IS_DISPATCHERSERVLETREQUEST, - true); - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/app", - this.discovery, this.properties); - this.properties.getRoutes().put("foo", new ZuulRoute("/foo/**")); - this.properties.init(); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/app/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/1", route.getPath()); - } - - @Test - public void testGetMatchingPathWithZuulServletPath() throws Exception { - RequestContext.getCurrentContext().setZuulEngineRan(); - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/app", - this.discovery, this.properties); - this.properties.getRoutes().put("foo", new ZuulRoute("/foo/**")); - this.properties.init(); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/zuul/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/1", route.getPath()); - - } - - @Test - public void testGetMatchingPathWithNoPrefixStripping() throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.getRoutes().put("foo", - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.properties.setStripPrefix(false); - this.properties.setPrefix("/proxy"); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/proxy/foo/1", route.getPath()); - } - - @Test - public void testGetMatchingPathWithLocalPrefixStripping() throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.getRoutes().put("foo", new ZuulRoute("/foo/**", "foo")); - this.properties.setStripPrefix(false); - this.properties.setPrefix("/proxy"); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/proxy/1", route.getPath()); - } - - @Test - public void testGetMatchingPathWithGlobalPrefixStripping() throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.getRoutes().put("foo", - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.properties.setPrefix("/proxy"); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/foo/1", route.getPath()); - } - - @Test - public void testGetMatchingPathWithGlobalPrefixStrippingAndServletPath() - throws Exception { - RequestContext.getCurrentContext().set(RequestUtils.IS_DISPATCHERSERVLETREQUEST, - true); - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/app", - this.discovery, this.properties); - this.properties.getRoutes().put("foo", - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.properties.setPrefix("/proxy"); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/app/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/foo/1", route.getPath()); - } - - @Test - public void testGetMatchingPathWithGlobalPrefixStrippingAndZuulServletPath() - throws Exception { - RequestContext.getCurrentContext().setZuulEngineRan(); - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.getRoutes().put("foo", - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.properties.setPrefix("/proxy"); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/zuul/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/foo/1", route.getPath()); - } - - @Test - public void testGetMatchingPathWithRoutePrefixStripping() throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - ZuulRoute zuulRoute = new ZuulRoute("/foo/**"); - zuulRoute.setStripPrefix(true); - this.properties.getRoutes().put("foo", zuulRoute); - this.properties.init(); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/1", route.getPath()); - } - - @Test - public void testGetMatchingPathWithoutMatchingIgnoredPattern() throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.setIgnoredPatterns(Collections.singleton(IGNOREDPATTERN)); - this.properties.getRoutes().put("bar", new ZuulRoute("/bar/**")); - this.properties.init(); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/bar/1"); - assertEquals("bar", route.getLocation()); - assertEquals("bar", route.getId()); - } - - @Test - public void testGetMatchingPathWithMatchingIgnoredPattern() throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.setIgnoredPatterns(Collections.singleton(IGNOREDPATTERN)); - this.properties.getRoutes().put("foo", new ZuulRoute("/foo/**")); - this.properties.init(); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/foo/1"); - assertNull("routes did not ignore " + IGNOREDPATTERN, route); - } - - @Test - public void testGetMatchingPathWithMatchingIgnoredPatternWithPrefix() - throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.setIgnoredPatterns(Collections.singleton(IGNOREDPATTERN)); - this.properties.getRoutes().put("foo", new ZuulRoute("/foo/**")); - this.properties.setPrefix("/proxy"); - this.properties.init(); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/1", route.getPath()); - } - - @Test - public void testGetMatchingPathWithMatchingIgnoredPatternWithServletPath() - throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/app", - this.discovery, this.properties); - this.properties.setIgnoredPatterns(Collections.singleton(IGNOREDPATTERN)); - this.properties.getRoutes().put("foo", new ZuulRoute("/foo/**")); - this.properties.init(); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/app/foo/1"); - assertNull("routes did not ignore " + IGNOREDPATTERN, route); - } - - @Test - public void testGetMatchingPathWithoutMatchingIgnoredPatternWithNoPrefixStripping() - throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.setIgnoredPatterns(Collections.singleton(IGNOREDPATTERN)); - this.properties.getRoutes().put("foo", - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.properties.setStripPrefix(false); - this.properties.setPrefix("/proxy"); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/proxy/foo/1", route.getPath()); - } - - @Test - public void testGetMatchingPathWithMatchingIgnoredPatternWithNoPrefixStripping() - throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties - .setIgnoredPatterns(Collections.singleton("/proxy" + IGNOREDPATTERN)); - this.properties.getRoutes().put("foo", - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.properties.setStripPrefix(false); - this.properties.setPrefix("/proxy"); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertNull("routes did not ignore " + "/proxy" + IGNOREDPATTERN, route); - } - - @Test - public void testGetMatchingPathWithoutMatchingIgnoredPatternWithLocalPrefixStripping() - throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.setIgnoredPatterns(Collections.singleton(IGNOREDPATTERN)); - this.properties.getRoutes().put("foo", new ZuulRoute("/foo/**", "foo")); - this.properties.setStripPrefix(false); - this.properties.setPrefix("/proxy"); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/proxy/1", route.getPath()); - } - - @Test - public void testGetMatchingPathWithMatchingIgnoredPatternWithLocalPrefixStripping() - throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties - .setIgnoredPatterns(Collections.singleton("/proxy" + IGNOREDPATTERN)); - this.properties.getRoutes().put("foo", new ZuulRoute("/foo/**", "foo")); - this.properties.setStripPrefix(false); - this.properties.setPrefix("/proxy"); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertNull("routes did not ignore " + "/proxy" + IGNOREDPATTERN, route); - } - - @Test - public void testGetMatchingPathWithoutMatchingIgnoredPatternWithGlobalPrefixStripping() - throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.setIgnoredPatterns(Collections.singleton(IGNOREDPATTERN)); - this.properties.getRoutes().put("foo", - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.properties.setPrefix("/proxy"); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/foo/1", route.getPath()); - } - - @Test - public void testGetMatchingPathWithMatchingIgnoredPatternWithGlobalPrefixStripping() - throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties - .setIgnoredPatterns(Collections.singleton("/proxy" + IGNOREDPATTERN)); - this.properties.getRoutes().put("foo", - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.properties.setPrefix("/proxy"); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertNull("routes did not ignore " + "/proxy" + IGNOREDPATTERN, route); - } - - @Test - public void testGetMatchingPathWithMatchingIgnoredPatternWithRoutePrefixStripping() - throws Exception { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - ZuulRoute zuulRoute = new ZuulRoute("/foo/**"); - zuulRoute.setStripPrefix(true); - this.properties.setIgnoredPatterns(Collections.singleton(IGNOREDPATTERN)); - this.properties.getRoutes().put("foo", zuulRoute); - this.properties.init(); - routeLocator.getRoutes(); // force refresh - Route route = routeLocator.getMatchingRoute("/foo/1"); - assertNull("routes did not ignore " + IGNOREDPATTERN, route); - } - - @Test - public void testGetRoutes() { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.getRoutes().put(ASERVICE, new ZuulRoute("/" + ASERVICE + "/**")); - this.properties.init(); - List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); - assertMapping(routesMap, ASERVICE); - } - - @Test - public void testGetRoutesWithMapping() { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.getRoutes().put(ASERVICE, - new ZuulRoute("/" + ASERVICE + "/**", ASERVICE)); - this.properties.setPrefix("/foo"); - - List routesMap = routeLocator.getRoutes(); - assertMapping(routesMap, ASERVICE, "foo/" + ASERVICE); - } - - @Test - public void testGetPhysicalRoutes() { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.getRoutes().put(ASERVICE, - new ZuulRoute("/" + ASERVICE + "/**", "http://" + ASERVICE)); - List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); - assertMapping(routesMap, "http://" + ASERVICE, ASERVICE); - } - - @Test - public void testGetDefaultRoute() { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.getRoutes().put(ASERVICE, new ZuulRoute("/**", ASERVICE)); - List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); - assertDefaultMapping(routesMap, ASERVICE); - } - - @Test - public void testGetDefaultPhysicalRoute() { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.getRoutes().put(ASERVICE, - new ZuulRoute("/**", "http://" + ASERVICE)); - List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); - assertDefaultMapping(routesMap, "http://" + ASERVICE); - } - - @Test - public void testIgnoreRoutes() { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.setIgnoredServices(Collections.singleton(IGNOREDSERVICE)); - given(this.discovery.getServices()) - .willReturn(Collections.singletonList(IGNOREDSERVICE)); - List routesMap = routeLocator.getRoutes(); - assertNull("routes did not ignore " + IGNOREDSERVICE, - getRoute(routesMap, getMapping(IGNOREDSERVICE))); - } - - @Test - public void testIgnoreRoutesWithPattern() { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.setIgnoredServices(Collections.singleton("ignore*")); - given(this.discovery.getServices()) - .willReturn(Collections.singletonList(IGNOREDSERVICE)); - List routesMap = routeLocator.getRoutes(); - assertNull("routes did not ignore " + IGNOREDSERVICE, - getRoute(routesMap, getMapping(IGNOREDSERVICE))); - } - - @Test - public void testIgnoreAllRoutes() { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.setIgnoredServices(Collections.singleton("*")); - given(this.discovery.getServices()) - .willReturn(Collections.singletonList(IGNOREDSERVICE)); - List routesMap = routeLocator.getRoutes(); - assertNull("routes did not ignore " + IGNOREDSERVICE, - getRoute(routesMap, getMapping(IGNOREDSERVICE))); - } - - @Test - public void testIgnoredRouteIncludedIfConfiguredAndDiscovered() { - this.properties.getRoutes().put("foo", new ZuulRoute("/foo/**")); - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.setIgnoredServices(Collections.singleton("*")); - given(this.discovery.getServices()).willReturn(Collections.singletonList("foo")); - List routesMap = routeLocator.getRoutes(); - assertNotNull("routes ignored foo", getRoute(routesMap, "/foo/**")); - } - - @Test - public void testIgnoredRoutePropertiesRemain() { - ZuulRoute route = new ZuulRoute("/foo/**"); - route.setStripPrefix(true); - route.setRetryable(Boolean.TRUE); - this.properties.getRoutes().put("foo", route); - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.setIgnoredServices(Collections.singleton("*")); - given(this.discovery.getServices()).willReturn(Collections.singletonList("foo")); - LinkedHashMap routes = routeLocator.locateRoutes(); - ZuulRoute actual = routes.get("/foo/**"); - assertNotNull("routes ignored foo", actual); - assertTrue("stripPrefix is wrong", actual.isStripPrefix()); - assertEquals("retryable is wrong", Boolean.TRUE, actual.getRetryable()); - } - - @Test - public void testIgnoredRouteNonServiceIdPathRemains() { - // This is how you setup a route defined like zuul.proxy.route.foo=/** - ZuulRoute route = new ZuulRoute("/**", "foo"); - route.setId("foo"); - - this.properties.getRoutes().put("foo", route); - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.setIgnoredServices(Collections.singleton("*")); - given(this.discovery.getServices()).willReturn(Collections.singletonList("foo")); - LinkedHashMap routes = routeLocator.locateRoutes(); - ZuulRoute actual = routes.get("/**"); - assertNotNull("routes ignored foo", actual); - assertEquals("id is wrong", "foo", actual.getId()); - assertEquals("location is wrong", "foo", actual.getServiceId()); - assertEquals("path is wrong", "/**", actual.getPath()); - } - - @Test - public void testIgnoredRouteIncludedIfConfiguredAndNotDiscovered() { - this.properties.getRoutes().put("foo", - new ZuulRoute("/foo/**", "http://foo.com")); - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - this.properties.setIgnoredServices(Collections.singleton("*")); - given(this.discovery.getServices()).willReturn(Collections.singletonList("bar")); - List routesMap = routeLocator.getRoutes(); - assertNotNull("routes ignored foo", getRoute(routesMap, getMapping("foo"))); - } - - @Test - public void testAutoRoutes() { - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - given(this.discovery.getServices()) - .willReturn(Collections.singletonList(MYSERVICE)); - List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); - assertMapping(routesMap, MYSERVICE); - } - - @Test - public void testAutoRoutesCanBeOverridden() { - ZuulRoute route = new ZuulRoute("/" + MYSERVICE + "/**", - "http://example.com/" + MYSERVICE); - this.properties.getRoutes().put(MYSERVICE, route); - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - given(this.discovery.getServices()) - .willReturn(Collections.singletonList(MYSERVICE)); - List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); - assertMapping(routesMap, "http://example.com/" + MYSERVICE, MYSERVICE); - } - - @Test - public void testIgnoredLocalServiceByDefault() { - given(this.discovery.getServices()) - .willReturn(Collections.singletonList(MYSERVICE)); - Registration registration = new Registration() { - @Override - public String getServiceId() { - return MYSERVICE; - } - - @Override - public String getHost() { - return "localhost"; - } - - @Override - public int getPort() { - return 80; - } - - @Override - public boolean isSecure() { - return false; - } - - @Override - public URI getUri() { - return null; - } - - @Override - public Map getMetadata() { - return null; - } - }; - - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties, registration); - - LinkedHashMap routes = routeLocator.locateRoutes(); - ZuulRoute actual = routes.get("/**"); - assertNull("routes didn't ignore " + MYSERVICE, actual); - - List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertTrue("routesMap was empty", routesMap.isEmpty()); - } - - @Test - public void testIgnoredLocalServiceFalse() { - this.properties.setIgnoreLocalService(false); - - given(this.discovery.getServices()) - .willReturn(Collections.singletonList(MYSERVICE)); - - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties); - - List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); - assertMapping(routesMap, MYSERVICE); - } - - @Test - public void testLocalServiceExceptionIgnored() { - given(this.discovery.getServices()).willReturn(Collections.emptyList()); - - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties, (Registration)null); - - // if no exception is thrown in constructor, this is a success - routeLocator.locateRoutes(); - } - - @Test - public void testRegExServiceRouteMapperNoServiceIdMatches() { - given(this.discovery.getServices()) - .willReturn(Collections.singletonList(MYSERVICE)); - - PatternServiceRouteMapper regExServiceRouteMapper = new PatternServiceRouteMapper( - this.regexMapper.getServicePattern(), this.regexMapper.getRoutePattern()); - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties, regExServiceRouteMapper); - List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); - assertMapping(routesMap, MYSERVICE); - } - - @Test - public void testRegExServiceRouteMapperServiceIdMatches() { - given(this.discovery.getServices()) - .willReturn(Collections.singletonList("rest-service-v1")); - - PatternServiceRouteMapper regExServiceRouteMapper = new PatternServiceRouteMapper( - this.regexMapper.getServicePattern(), this.regexMapper.getRoutePattern()); - DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties, regExServiceRouteMapper); - List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); - assertMapping(routesMap, "rest-service-v1", "v1/rest-service"); - } - - protected void assertMapping(List routesMap, String serviceId) { - assertMapping(routesMap, serviceId, serviceId); - } - - protected void assertMapping(List routesMap, String expectedRoute, - String key) { - String mapping = getMapping(key); - Route route = getRoute(routesMap, mapping); - assertNotNull("Could not find route for " + key, route); - String location = route.getLocation(); - assertEquals("routesMap had wrong value for " + mapping, expectedRoute, location); - } - - private String getMapping(String serviceId) { - return "/" + serviceId + "/**"; - } - - protected void assertDefaultMapping(List routesMap, String expectedRoute) { - String mapping = "/**"; - String route = getRoute(routesMap, mapping).getLocation(); - assertEquals("routesMap had wrong value for " + mapping, expectedRoute, route); - } - - private Route getRoute(List routes, String path) { - for (Route route : routes) { - String pattern = route.getFullPath(); - if (path.equals(pattern)) { - return route; - } - } - return null; - } - - private void setTestRequestcontext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapperIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapperIntegrationTests.java deleted file mode 100644 index 309f0bc9..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapperIntegrationTests.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.springframework.cloud.netflix.zuul.filters.discovery; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.StaticServerList; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.cloud.netflix.zuul.RoutesEndpoint; -import org.springframework.context.annotation.Bean; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.zuul.context.RequestContext; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author Stéphane Leroy - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT, - properties = { "spring.application.name=regex-test-application", "spring.jmx.enabled=false", - "eureka.client.enabled=false" }) -@DirtiesContext -public class PatternServiceRouteMapperIntegrationTests { - - protected static final String SERVICE_ID = "domain-service-v1"; - - @LocalServerPort - private int port; - - @Autowired - private DiscoveryClientRouteLocator routes; - - @Autowired - private RoutesEndpoint endpoint; - - @Before - public void setTestRequestcontext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void getRegexMappedService() { - this.endpoint.reset(); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/v1/domain/service/get/1", - HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Get 1", result.getBody()); - } - - @Test - public void getStaticRoute() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port); - this.endpoint.reset(); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/self/get/1", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Get 1", result.getBody()); - } - - @SpringBootConfiguration - @EnableAutoConfiguration - @RestController - @EnableZuulProxy - @RibbonClient(value = SERVICE_ID, configuration = SimpleRibbonClientConfiguration.class) - protected static class SampleCustomZuulProxyApplication { - - @Bean - public DiscoveryClient discoveryClient() { - DiscoveryClient discoveryClient = mock(DiscoveryClient.class); - List services = new ArrayList<>(); - services.add(SERVICE_ID); - when(discoveryClient.getServices()).thenReturn(services); - return discoveryClient; - } - - @RequestMapping(value = "/get/{id}", method = RequestMethod.GET) - public String get(@PathVariable String id) { - return "Get " + id; - } - - @Bean - public PatternServiceRouteMapper serviceRouteMapper() { - return new PatternServiceRouteMapper( - "(?^.+)-(?.+)-(?v.+$)", - "${version}/${domain}/${name}"); - } - - } - - protected static class SimpleRibbonClientConfiguration { - - @LocalServerPort - private int port = 0; - - @Bean - public ServerList ribbonServerList() { - return new StaticServerList<>(new Server("localhost", this.port)); - } - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapperTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapperTests.java deleted file mode 100644 index afca60b9..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapperTests.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.springframework.cloud.netflix.zuul.filters.discovery; - -import com.netflix.zuul.context.RequestContext; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * @author Stéphane Leroy - */ -public class PatternServiceRouteMapperTests { - - /** - * Service pattern that follow convention {domain}-{name}-{version}. The name is - * optional - */ - public static final String SERVICE_PATTERN = "(?^\\w+)(-(?\\w+)-|-)(?v\\d+$)"; - public static final String ROUTE_PATTERN = "${version}/${domain}/${name}"; - - @Before - public void setTestRequestcontext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void test_return_mapped_route_if_serviceid_matches() { - PatternServiceRouteMapper toTest = new PatternServiceRouteMapper(SERVICE_PATTERN, - ROUTE_PATTERN); - - assertEquals("service version convention", "v1/rest/service", - toTest.apply("rest-service-v1")); - } - - @Test - public void test_return_serviceid_if_no_matches() { - PatternServiceRouteMapper toTest = new PatternServiceRouteMapper(SERVICE_PATTERN, - ROUTE_PATTERN); - - // No version here - assertEquals("No matches for this service id", "rest-service", - toTest.apply("rest-service")); - } - - @Test - public void test_route_should_be_cleaned_before_returned() { - // Messy patterns - PatternServiceRouteMapper toTest = new PatternServiceRouteMapper( - SERVICE_PATTERN + "(?.)?", - "/${version}/${nevermatch}/${domain}/${name}/"); - assertEquals("No matches for this service id", "v1/domain/service", - toTest.apply("domain-service-v1")); - assertEquals("No matches for this service id", "v1/domain", - toTest.apply("domain-v1")); - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilterIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilterIntegrationTests.java deleted file mode 100644 index d5d29b24..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilterIntegrationTests.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.post; - -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.zuul.context.RequestContext; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.StaticServerList; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.context.annotation.Bean; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.bind.annotation.RequestMapping; - -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Biju Kunjummen - */ - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { - "zuul.routes.aservice.path:/service/**", "zuul.routes.aservice.strip-prefix:true", - "eureka.client.enabled:false" }) -@DirtiesContext -public class LocationRewriteFilterIntegrationTests { - - @LocalServerPort - private int port; - - @Before - public void before() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @Test - public void testWithRedirectPrefixStripped() { - String url = "http://localhost:" + port + "/service/redirectingUri"; - ResponseEntity response = new TestRestTemplate().getForEntity(url, - String.class); - List locationHeaders = response.getHeaders().get("Location"); - - assertThat(locationHeaders).hasSize(1); - String locationHeader = locationHeaders.get(0); - assertThat(locationHeader).withFailMessage("Location should have prefix") - .isEqualTo( - String.format("http://localhost:%d/service/redirectedUri", port)); - - } - - @SpringBootConfiguration - @EnableAutoConfiguration - @EnableZuulProxy - @Controller - @RibbonClient(name = "aservice", configuration = RibbonConfig.class) - protected static class Config { - - @RequestMapping("/redirectingUri") - public String redirect1() { - return "redirect:/redirectedUri"; - } - - @Bean - public LocationRewriteFilter locationRewriteFilter() { - return new LocationRewriteFilter(); - } - - } - - public static class RibbonConfig { - @LocalServerPort - private int port; - - @Bean - public ServerList ribbonServerList() { - return new StaticServerList<>(new Server("localhost", this.port)); - } - - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilterTests.java deleted file mode 100644 index adf9f314..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilterTests.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.post; - -import com.netflix.util.Pair; -import com.netflix.zuul.context.RequestContext; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.cloud.netflix.zuul.filters.Route; -import org.springframework.cloud.netflix.zuul.filters.RouteLocator; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; - -import java.util.Collections; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * @author Biju Kunjummen - */ - -public class LocationRewriteFilterTests { - - private final String ZUUL_HOST = "myzuul.com"; - private final String ZUUL_SCHEME = "https"; - private final int ZUUL_PORT = 8443; - private final String ZUUL_BASE_URL = String.format("%s://%s:%d", ZUUL_SCHEME, - ZUUL_HOST, ZUUL_PORT); - - private final String SERVER_HOST = "someserver.com"; - private final String SERVER_SCHEME = "http"; - private final int SERVER_PORT = 8564; - private final String SERVER_BASE_URL = String.format("%s://%s:%d", SERVER_SCHEME, - SERVER_HOST, SERVER_PORT); - - @Before - public void before() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - - @After - public void reset() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void shouldRewriteLocationHeadersWithRoutePrefix() { - RequestContext context = RequestContext.getCurrentContext(); - ZuulProperties zuulProperties = new ZuulProperties(); - LocationRewriteFilter filter = setFilterUpWith(context, zuulProperties, - new Route("service1", "/redirectingUri", "service1", "prefix", false, - Collections.EMPTY_SET, true), - "/prefix/redirectingUri", "/redirectedUri;someparam?param1=abc"); - filter.run(); - assertThat(getLocationHeader(context).second()).isEqualTo(String - .format("%s/prefix/redirectedUri;someparam?param1=abc", ZUUL_BASE_URL)); - } - - @Test - public void shouldBeUntouchedIfNoRoutesFound() { - RequestContext context = RequestContext.getCurrentContext(); - ZuulProperties zuulProperties = new ZuulProperties(); - LocationRewriteFilter filter = setFilterUpWith(context, zuulProperties, null, - "/prefix/redirectingUri", "/redirectedUri;someparam?param1=abc"); - filter.run(); - assertThat(getLocationHeader(context).second()).isEqualTo( - String.format("%s/redirectedUri;someparam?param1=abc", SERVER_BASE_URL)); - } - - @Test - public void shouldRewriteLocationHeadersIfPrefixIsNotStripped() { - RequestContext context = RequestContext.getCurrentContext(); - ZuulProperties zuulProperties = new ZuulProperties(); - LocationRewriteFilter filter = setFilterUpWith(context, zuulProperties, - new Route("service1", "/something/redirectingUri", "service1", "prefix", - false, Collections.EMPTY_SET, false), - "/prefix/redirectingUri", - "/something/redirectedUri;someparam?param1=abc"); - filter.run(); - assertThat(getLocationHeader(context).second()).isEqualTo(String.format( - "%s/something/redirectedUri;someparam?param1=abc", ZUUL_BASE_URL)); - } - - @Test - public void shouldRewriteLocationHeadersIfPrefixIsEmpty() { - RequestContext context = RequestContext.getCurrentContext(); - ZuulProperties zuulProperties = new ZuulProperties(); - LocationRewriteFilter filter = setFilterUpWith(context, zuulProperties, - new Route("service1", "/something/redirectingUri", "service1", "", false, - Collections.EMPTY_SET, true), - "/redirectingUri", "/something/redirectedUri;someparam?param1=abc"); - filter.run(); - assertThat(getLocationHeader(context).second()).isEqualTo(String.format( - "%s/something/redirectedUri;someparam?param1=abc", ZUUL_BASE_URL)); - } - - @Test - public void shouldAddBackGlobalPrefixIfPresent() { - RequestContext context = RequestContext.getCurrentContext(); - ZuulProperties zuulProperties = new ZuulProperties(); - zuulProperties.setPrefix("global"); - zuulProperties.setStripPrefix(true); - LocationRewriteFilter filter = setFilterUpWith(context, zuulProperties, - new Route("service1", "/something/redirectingUri", "service1", "prefix", - false, Collections.EMPTY_SET, true), - "/global/prefix/redirectingUri", - "/something/redirectedUri;someparam?param1=abc"); - filter.run(); - assertThat(getLocationHeader(context).second()).isEqualTo(String.format( - "%s/global/prefix/something/redirectedUri;someparam?param1=abc", - ZUUL_BASE_URL)); - } - - @Test - public void shouldNotAddBackGlobalPrefixIfNotStripped() { - RequestContext context = RequestContext.getCurrentContext(); - ZuulProperties zuulProperties = new ZuulProperties(); - zuulProperties.setPrefix("global"); - zuulProperties.setStripPrefix(false); - LocationRewriteFilter filter = setFilterUpWith(context, zuulProperties, - new Route("service1", "/something/redirectingUri", "service1", "prefix", - false, Collections.EMPTY_SET, true), - "/global/prefix/redirectingUri", - "/global/something/redirectedUri;someparam?param1=abc"); - filter.run(); - assertThat(getLocationHeader(context).second()).isEqualTo(String.format( - "%s/global/prefix/something/redirectedUri;someparam?param1=abc", - ZUUL_BASE_URL)); - } - - private LocationRewriteFilter setFilterUpWith(RequestContext context, - ZuulProperties zuulProperties, Route route, String toZuulRequestUri, - String redirectedUri) { - MockHttpServletRequest httpServletRequest = new MockHttpServletRequest(); - httpServletRequest.setRequestURI(toZuulRequestUri); - httpServletRequest.setServerName(ZUUL_HOST); - httpServletRequest.setScheme(ZUUL_SCHEME); - httpServletRequest.setServerPort(ZUUL_PORT); - context.setRequest(httpServletRequest); - - MockHttpServletResponse httpServletResponse = new MockHttpServletResponse(); - context.getZuulResponseHeaders().add(new Pair<>("Location", - String.format("%s%s", SERVER_BASE_URL, redirectedUri))); - context.setResponse(httpServletResponse); - - RouteLocator routeLocator = mock(RouteLocator.class); - when(routeLocator.getMatchingRoute(toZuulRequestUri)).thenReturn(route); - LocationRewriteFilter filter = new LocationRewriteFilter(zuulProperties, - routeLocator); - - return filter; - } - - private Pair getLocationHeader(RequestContext ctx) { - if (ctx.getZuulResponseHeaders() != null) { - for (Pair pair : ctx.getZuulResponseHeaders()) { - if (pair.first().equals("Location")) { - return pair; - } - } - } - return null; - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterIntegrationTests.java deleted file mode 100644 index b8ac6d9c..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterIntegrationTests.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.post; - -import javax.servlet.http.HttpServletRequest; - -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.StaticServerList; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.context.annotation.Bean; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ROUTE_TYPE; - -/** - * @author Spencer Gibb - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SendErrorFilterIntegrationTests.Config.class, properties = "zuul.routes.filtertest:/filtertest/**", webEnvironment = RANDOM_PORT) -@DirtiesContext -public class SendErrorFilterIntegrationTests { - - @LocalServerPort - private int port; - - @Before - public void setTestRequestcontext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void testPreFails() { - String url = "http://localhost:" + port + "/filtertest/get?failpre=true"; - ResponseEntity response = new TestRestTemplate().getForEntity(url, - String.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - } - - @Test - public void testRouteFails() { - String url = "http://localhost:" + port + "/filtertest/get?failroute=true"; - ResponseEntity response = new TestRestTemplate().getForEntity(url, - String.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - } - - @Test - public void testPostFails() { - String url = "http://localhost:" + port + "/filtertest/get?failpost=true"; - ResponseEntity response = new TestRestTemplate().getForEntity(url, - String.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - } - - @SpringBootConfiguration - @EnableAutoConfiguration - @EnableZuulProxy - @RestController - @RibbonClient(name = "filtertest", configuration = RibbonConfig.class) - protected static class Config { - - @RequestMapping("/get") - public String get() { - return "Hello"; - } - - @Bean - public ZuulFilter testPreFilter() { - return new FailureFilter() { - @Override - public String filterType() { - return PRE_TYPE; - } - }; - } - - @Bean - public ZuulFilter testRouteFilter() { - return new FailureFilter() { - @Override - public String filterType() { - return ROUTE_TYPE; - } - }; - } - - @Bean - public ZuulFilter testPostFilter() { - return new FailureFilter() { - @Override - public String filterType() { - return POST_TYPE; - } - }; - } - } - - public static class RibbonConfig { - @LocalServerPort - private int port; - - @Bean - public ServerList ribbonServerList() { - return new StaticServerList<>(new Server("localhost", this.port)); - } - - } - - private abstract static class FailureFilter extends ZuulFilter { - @Override - public int filterOrder() { - return Integer.MIN_VALUE; - } - - @Override - public boolean shouldFilter() { - HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); - return request.getParameter("fail" + filterType()) != null; - } - - @Override - public Object run() { - HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); - if (request.getParameter("fail" + filterType()) != null) { - throw new RuntimeException("failing on purpose in " + filterType()); - } - return null; - } - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterTests.java deleted file mode 100644 index bd3daa56..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterTests.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.post; - -import javax.servlet.http.HttpServletRequest; - -import com.netflix.zuul.exception.ZuulException; -import com.netflix.zuul.monitoring.MonitoringHelper; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.http.HttpStatus; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; - -import com.netflix.zuul.context.RequestContext; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; - -/** - * @author Spencer Gibb - */ -public class SendErrorFilterTests { - - @Before - public void setTestRequestcontext() { - MonitoringHelper.initMocks(); - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @After - public void reset() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void runsNormally() { - SendErrorFilter filter = createSendErrorFilter(new MockHttpServletRequest()); - assertTrue("shouldFilter returned false", filter.shouldFilter()); - filter.run(); - } - - private SendErrorFilter createSendErrorFilter(HttpServletRequest request) { - RequestContext context = new RequestContext(); - context.setRequest(request); - context.setResponse(new MockHttpServletResponse()); - context.setThrowable(new ZuulException(new RuntimeException(), HttpStatus.NOT_FOUND.value(), null)); - RequestContext.testSetCurrentContext(context); - SendErrorFilter filter = new SendErrorFilter(); - filter.setErrorPath("/error"); - return filter; - } - - @Test - public void noRequestDispatcher() { - SendErrorFilter filter = createSendErrorFilter(mock(HttpServletRequest.class)); - assertTrue("shouldFilter returned false", filter.shouldFilter()); - filter.run(); - } - - @Test - public void doesNotRunTwice() { - SendErrorFilter filter = createSendErrorFilter(new MockHttpServletRequest()); - assertTrue("shouldFilter returned false", filter.shouldFilter()); - filter.run(); - assertFalse("shouldFilter returned true", filter.shouldFilter()); - } - - @Test - public void setResponseCode() { - SendErrorFilter filter = createSendErrorFilter(new MockHttpServletRequest()); - filter.run(); - - RequestContext ctx = RequestContext.getCurrentContext(); - int resCode = ctx.getResponse().getStatus(); - int ctxCode = ctx.getResponseStatusCode(); - - assertEquals("invalid response code: " + resCode, HttpStatus.NOT_FOUND.value(), resCode); - assertEquals("invalid response code in RequestContext: " + ctxCode, resCode, ctxCode); - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendResponseFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendResponseFilterTests.java deleted file mode 100644 index 5e133c50..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendResponseFilterTests.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.post; - -import java.io.ByteArrayInputStream; -import java.io.Closeable; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.UndeclaredThrowableException; - -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.web.util.WebUtils; - -import com.netflix.zuul.context.Debug; -import com.netflix.zuul.context.RequestContext; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.X_ZUUL_DEBUG_HEADER; - -/** - * @author Spencer Gibb - */ -public class SendResponseFilterTests { - - @Before - public void setTestRequestcontext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @After - public void reset() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void runsNormally() throws Exception { - String characterEncoding = null; - String content = "hello"; - runFilter(characterEncoding, content, false); - } - - @Test - public void useServlet31Works() { - assertThat(new SendResponseFilter().isUseServlet31()).isTrue(); - } - - @Test - public void characterEncodingNotOverridden() throws Exception { - String characterEncoding = "UTF-16"; - String content = "\u00a5"; - runFilter(characterEncoding, content, true); - } - - @Test - public void runWithDebugHeader() throws Exception { - ZuulProperties properties = new ZuulProperties(); - properties.setIncludeDebugHeader(true); - - SendResponseFilter filter = createFilter(properties, "hello", null, new MockHttpServletResponse(), false); - Debug.addRoutingDebug("test"); - filter.run(); - - String debugHeader = RequestContext.getCurrentContext().getResponse() - .getHeader(X_ZUUL_DEBUG_HEADER); - assertThat("wrong debug header", debugHeader, equalTo("[[[test]]]")); - } - - @Test - public void runWithOriginContentLength() throws Exception { - ZuulProperties properties = new ZuulProperties(); - properties.setSetContentLength(true); - - SendResponseFilter filter = createFilter(properties, "hello", null, new MockHttpServletResponse(), false); - RequestContext.getCurrentContext().setOriginContentLength(6L); // for test - RequestContext.getCurrentContext().setResponseGZipped(false); - filter.run(); - - String contentLength = RequestContext.getCurrentContext().getResponse() - .getHeader("Content-Length"); - assertThat("wrong origin content length", contentLength, equalTo("6")); - } - - @Test - public void closeResponseOutputStreamError() throws Exception { - HttpServletResponse response = mock(HttpServletResponse.class); - InputStream mockStream = spy(new ByteArrayInputStream("Hello\n".getBytes("UTF-8"))); - - RequestContext context = new RequestContext(); - context.setRequest(new MockHttpServletRequest()); - context.setResponse(response); - context.setResponseDataStream(mockStream); - Closeable zuulResponse = mock(Closeable.class); - context.set("zuulResponse", zuulResponse); - RequestContext.testSetCurrentContext(context); - - SendResponseFilter filter = new SendResponseFilter(); - - ServletOutputStream zuuloutputstream = mock(ServletOutputStream.class); - doThrow(new IOException("Response to client closed")).when(zuuloutputstream).write(isA(byte[].class), anyInt(), anyInt()); - - when(response.getOutputStream()).thenReturn(zuuloutputstream); - - try { - filter.run(); - } catch (UndeclaredThrowableException ex) { - assertThat(ex.getUndeclaredThrowable().getMessage(), is("Response to client closed")); - } - - verify(zuulResponse).close(); - verify(mockStream).close(); - } - - @Test - public void testCloseResponseDataStream() throws Exception { - HttpServletResponse response = mock(HttpServletResponse.class); - InputStream mockStream = spy(new ByteArrayInputStream("Hello\n".getBytes("UTF-8"))); - - RequestContext context = new RequestContext(); - context.setRequest(new MockHttpServletRequest()); - context.setResponse(response); - context.setResponseDataStream(mockStream); - Closeable zuulResponse = mock(Closeable.class); - context.set("zuulResponse", zuulResponse); - RequestContext.testSetCurrentContext(context); - - when(response.getOutputStream()).thenReturn(mock(ServletOutputStream.class)); - - SendResponseFilter filter = new SendResponseFilter(); - - filter.run(); - - verify(mockStream).close(); - } - - private void runFilter(String characterEncoding, String content, boolean streamContent) throws Exception { - MockHttpServletResponse response = new MockHttpServletResponse(); - SendResponseFilter filter = createFilter(content, characterEncoding, response, streamContent); - assertTrue("shouldFilter returned false", filter.shouldFilter()); - filter.run(); - String encoding = RequestContext.getCurrentContext().getResponse().getCharacterEncoding(); - String expectedEncoding = characterEncoding != null ? characterEncoding : WebUtils.DEFAULT_CHARACTER_ENCODING; - assertThat("wrong character encoding", encoding, equalTo(expectedEncoding)); - assertThat("wrong content", response.getContentAsString(), equalTo(content)); - } - - private SendResponseFilter createFilter(String content, String characterEncoding, MockHttpServletResponse response, boolean streamContent) throws Exception { - return createFilter(new ZuulProperties(), content, characterEncoding, response, streamContent); - } - - private SendResponseFilter createFilter(ZuulProperties properties, String content, String characterEncoding, MockHttpServletResponse response, boolean streamContent) throws Exception { - HttpServletRequest request = new MockHttpServletRequest(); - RequestContext context = new RequestContext(); - context.setRequest(request); - context.setResponse(response); - - if (characterEncoding != null) { - response.setCharacterEncoding(characterEncoding); - } - - if (streamContent) { - context.setResponseDataStream(new ByteArrayInputStream(content.getBytes(characterEncoding))); - } else { - context.setResponseBody(content); - } - - context.addZuulResponseHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(content.length())); - - context.set("error.status_code", HttpStatus.NOT_FOUND.value()); - RequestContext.testSetCurrentContext(context); - SendResponseFilter filter = new SendResponseFilter(properties); - return filter; - } - -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/pre/FormBodyWrapperFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/pre/FormBodyWrapperFilterTests.java deleted file mode 100644 index 10ef5b4e..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/pre/FormBodyWrapperFilterTests.java +++ /dev/null @@ -1,188 +0,0 @@ -package org.springframework.cloud.netflix.zuul.filters.pre; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.Part; - -import org.apache.commons.io.IOUtils; -import org.junit.Before; -import org.junit.Test; -import org.springframework.mock.web.MockMultipartHttpServletRequest; - -import com.netflix.zuul.context.RequestContext; - -/** - * @author Michael Hartle - */ -public class FormBodyWrapperFilterTests { - - private FormBodyWrapperFilter filter; - - private MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); - - @Before - public void init() { - this.filter = new FormBodyWrapperFilter(); - RequestContext ctx = RequestContext.getCurrentContext(); - ctx.clear(); - ctx.setRequest(this.request); - } - - @Test - public void multiplePartNamesWithMultipleParts() throws IOException, ServletException { - this.request.setRequestURI("/api/foo/1"); - this.request.setRemoteAddr("5.6.7.8"); - - final Map> firstPartHeaders = new HashMap<>(); - final byte[] firstPartBody = "{ \"u\" : 1 }".getBytes(); - final Part firstPart = new MockPart("a", "application/json", null, firstPartHeaders, firstPartBody); - this.request.addPart(firstPart); - - final Map> secondPartHeaders = new HashMap<>(); - final byte[] secondPartBody = "%PDF...1".getBytes(); - final Part secondPart = new MockPart("b", "application/pdf", "document.pdf", secondPartHeaders, secondPartBody); - this.request.addPart(secondPart); - - final Map> thirdPartHeaders = new HashMap<>(); - final byte[] thirdPartBody = "%PDF...2".getBytes(); - final Part thirdPart = new MockPart("c", "application/pdf", "attachment1.pdf", thirdPartHeaders, thirdPartBody); - this.request.addPart(thirdPart); - - final Map> fourthPartHeaders = new HashMap<>(); - final byte[] fourthPartBody = "%PDF...3".getBytes(); - final Part fourthPart = new MockPart("c", "application/pdf", "attachment2.pdf", fourthPartHeaders, fourthPartBody); - this.request.addPart(fourthPart); - - final Map> fifthPartHeaders = new HashMap<>(); - final byte[] fifthPartBody = "%PDF...4".getBytes(); - final Part fifthPart = new MockPart("c", "application/pdf", "attachment3.pdf", fifthPartHeaders, fifthPartBody); - this.request.addPart(fifthPart); - - this.filter.run(); - - final RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/api/foo/1", ctx.getRequest().getRequestURI()); - assertEquals("5.6.7.8", ctx.getRequest().getRemoteAddr()); - assertEquals(5, ctx.getRequest().getParts().size()); - - final Part[] parts = ctx.getRequest().getParts().toArray(new Part[0]); - assertEquals("a", parts[0].getName()); - assertEquals(null, parts[0].getSubmittedFileName()); - assertEquals("application/json", parts[0].getContentType()); - assertArrayEquals(firstPartBody, IOUtils.toByteArray(parts[0].getInputStream())); - - assertEquals("b", parts[1].getName()); - assertEquals("document.pdf", parts[1].getSubmittedFileName()); - assertEquals("application/pdf", parts[1].getContentType()); - assertArrayEquals(secondPartBody, IOUtils.toByteArray(parts[1].getInputStream())); - - assertEquals("c", parts[2].getName()); - assertEquals("attachment1.pdf", parts[2].getSubmittedFileName()); - assertEquals("application/pdf", parts[2].getContentType()); - assertArrayEquals(thirdPartBody, IOUtils.toByteArray(parts[2].getInputStream())); - - assertEquals("c", parts[3].getName()); - assertEquals("attachment2.pdf", parts[3].getSubmittedFileName()); - assertEquals("application/pdf", parts[3].getContentType()); - assertArrayEquals(fourthPartBody, IOUtils.toByteArray(parts[3].getInputStream())); - - assertEquals("c", parts[4].getName()); - assertEquals("attachment3.pdf", parts[4].getSubmittedFileName()); - assertEquals("application/pdf", parts[4].getContentType()); - assertArrayEquals(fifthPartBody, IOUtils.toByteArray(parts[4].getInputStream())); - } - - private class MockPart implements Part { - private final String name; - private final String contentType; - private final String submittedFileName; - private final Map> headers; - private final byte[] body; - - public MockPart(final String name, final String contentType, final String submittedFileName, final Map> headers, final byte[] body) { - this.name = name; - this.contentType = contentType; - this.submittedFileName = submittedFileName; - this.headers = headers; - this.body = body; - } - - @Override - public InputStream getInputStream() throws IOException { - return new ByteArrayInputStream(this.body); - } - - @Override - public String getContentType() { - return this.contentType; - } - - @Override - public String getName() { - return this.name; - } - - @Override - public String getSubmittedFileName() { - return this.submittedFileName; - } - - @Override - public long getSize() { - return this.body != null ? this.body.length : 0; - } - - @Override - public void write(String fileName) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public void delete() throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public String getHeader(String name) { - if (this.headers == null) { - return null; - } - - final List values = this.headers.get(name); - - if (values == null || values.size() == 0) { - return null; - } - - return values.get(0); - } - - @Override - public Collection getHeaders(String name) { - if (this.headers == null) { - return null; - } - - return this.headers.get(name); - } - - @Override - public Collection getHeaderNames() { - if (this.headers == null) { - return null; - } - - return this.headers.keySet(); - } - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/pre/PreDecorationFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/pre/PreDecorationFilterTests.java deleted file mode 100644 index 5969435f..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/pre/PreDecorationFilterTests.java +++ /dev/null @@ -1,635 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.pre; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import com.netflix.util.Pair; -import com.netflix.zuul.context.RequestContext; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; - -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelper; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute; -import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; -import org.springframework.mock.web.MockHttpServletRequest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.MockitoAnnotations.initMocks; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORWARD_TO_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.REQUEST_URI_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVICE_ID_KEY; - -/** - * @author Dave Syer - */ -public class PreDecorationFilterTests { - - private PreDecorationFilter filter; - - @Mock - private DiscoveryClient discovery; - - private ZuulProperties properties = new ZuulProperties(); - - private DiscoveryClientRouteLocator routeLocator; - - private MockHttpServletRequest request = new MockHttpServletRequest(); - - private ProxyRequestHelper proxyRequestHelper = new ProxyRequestHelper(); - - @Before - public void init() { - initMocks(this); - this.properties = new ZuulProperties(); - this.routeLocator = new DiscoveryClientRouteLocator("/", this.discovery, - this.properties); - this.filter = new PreDecorationFilter(this.routeLocator, "/", this.properties, - this.proxyRequestHelper); - RequestContext ctx = RequestContext.getCurrentContext(); - ctx.clear(); - ctx.setRequest(this.request); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void basicProperties() throws Exception { - assertEquals(5, this.filter.filterOrder()); - assertEquals(true, this.filter.shouldFilter()); - assertEquals(PRE_TYPE, this.filter.filterType()); - } - - @Test - public void skippedIfServiceIdSet() throws Exception { - RequestContext.getCurrentContext().set(SERVICE_ID_KEY, "myservice"); - assertEquals(false, this.filter.shouldFilter()); - } - - @Test - public void skippedIfForwardToSet() throws Exception { - RequestContext.getCurrentContext().set(FORWARD_TO_KEY, "myconteext"); - assertEquals(false, this.filter.shouldFilter()); - } - - @Test - public void xForwardedHostHasPort() throws Exception { - this.properties.setPrefix("/api"); - this.request.setRequestURI("/api/foo/1"); - this.request.setRemoteAddr("5.6.7.8"); - this.request.setServerPort(8080); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("localhost:8080", - ctx.getZuulRequestHeaders().get("x-forwarded-host")); - } - - @Test - public void xForwardedHostAndProtoAppend() throws Exception { - this.properties.setPrefix("/api"); - this.request.setRequestURI("/api/foo/1"); - this.request.setRemoteAddr("5.6.7.8"); - this.request.setServerPort(8080); - this.request.addHeader("X-Forwarded-Host", "example.com"); - this.request.addHeader("X-Forwarded-Proto", "https"); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("example.com,localhost:8080", - ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("443,8080", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("https,http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - } - - @Test - public void xForwardedHostOnlyAppends() throws Exception { - this.properties.setPrefix("/api"); - this.request.setRequestURI("/api/foo/1"); - this.request.setRemoteAddr("5.6.7.8"); - this.request.setServerPort(8080); - this.request.addHeader("X-Forwarded-Host", "example.com"); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("example.com,localhost:8080", - ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("8080", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - } - - @Test - public void xForwardedProtoOnlyAppends() throws Exception { - this.properties.setPrefix("/api"); - this.request.setRequestURI("/api/foo/1"); - this.request.setRemoteAddr("5.6.7.8"); - this.request.setServerPort(8080); - this.request.addHeader("X-Forwarded-Proto", "https"); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("localhost:8080", - ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("443,8080", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("https,http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - } - - @Test - public void xForwardedProtoHttpOnlyAppends() throws Exception { - this.properties.setPrefix("/api"); - this.request.setRequestURI("/api/foo/1"); - this.request.setRemoteAddr("5.6.7.8"); - this.request.setServerPort(8080); - this.request.addHeader("X-Forwarded-Proto", "http"); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("localhost:8080", - ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("80,8080", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http,http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - } - - @Test - public void xForwardedPortOnlyAppends() throws Exception { - this.properties.setPrefix("/api"); - this.request.setRequestURI("/api/foo/1"); - this.request.setRemoteAddr("5.6.7.8"); - this.request.setServerPort(8080); - this.request.addHeader("X-Forwarded-Port", "456"); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("localhost:8080", - ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("456,8080", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - } - - @Test - public void xForwardedPortAndProtoAppends() throws Exception { - this.properties.setPrefix("/api"); - this.request.setRequestURI("/api/foo/1"); - this.request.setRemoteAddr("5.6.7.8"); - this.request.setServerPort(8080); - this.request.addHeader("X-Forwarded-Proto", "https"); - this.request.addHeader("X-Forwarded-Port", "456"); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("localhost:8080", - ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("456,8080", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("https,http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - } - - @Test - public void hostHeaderSet() throws Exception { - this.properties.setPrefix("/api"); - this.properties.setAddHostHeader(true); - this.request.setRequestURI("/api/foo/1"); - this.request.setRemoteAddr("5.6.7.8"); - this.request.setServerPort(8080); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("localhost:8080", - ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("localhost:8080", ctx.getZuulRequestHeaders().get("host")); - } - - @Test - public void prefixRouteAddsHeader() throws Exception { - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.request.setRequestURI("/api/foo/1"); - this.request.setRemoteAddr("5.6.7.8"); - this.request.addHeader("X-Forwarded-For", "1.2.3.4"); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/foo/1", ctx.get(REQUEST_URI_KEY)); - assertEquals("localhost", ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("80", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - assertEquals("/api", ctx.getZuulRequestHeaders().get("x-forwarded-prefix")); - assertEquals("1.2.3.4, 5.6.7.8", - ctx.getZuulRequestHeaders().get("x-forwarded-for")); - assertEquals("foo", - getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")); - } - - @Test - public void prefixRouteWithPrefixHeaderConcatsHeader() throws Exception { - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.request.setRequestURI("/api/foo/1"); - this.request.setRemoteAddr("5.6.7.8"); - this.request.addHeader("X-Forwarded-For", "1.2.3.4"); - this.request.addHeader("X-Forwarded-Prefix", "/prefix"); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/foo/1", ctx.get(REQUEST_URI_KEY)); - assertEquals("localhost", ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("80", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - assertEquals("/prefix/api", - ctx.getZuulRequestHeaders().get("x-forwarded-prefix")); - assertEquals("1.2.3.4, 5.6.7.8", - ctx.getZuulRequestHeaders().get("x-forwarded-for")); - assertEquals("foo", - getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")); - } - - @Test - public void routeWithContextPath() { - this.properties.setStripPrefix(false); - this.request.setRequestURI("/api/foo/1"); - this.request.setContextPath("/context-path"); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/api/foo/**", "foo", null, false, null, null)); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/api/foo/1", ctx.get(REQUEST_URI_KEY)); - assertEquals("localhost", ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("80", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - assertEquals("/context-path", - ctx.getZuulRequestHeaders().get("x-forwarded-prefix")); - assertEquals("foo", - getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")); - } - - @Test - public void prefixRouteWithContextPath() { - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.request.setRequestURI("/api/foo/1"); - this.request.setContextPath("/context-path"); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/foo/1", ctx.get(REQUEST_URI_KEY)); - assertEquals("localhost", ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("80", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - assertEquals("/context-path/api", - ctx.getZuulRequestHeaders().get("x-forwarded-prefix")); - assertEquals("foo", - getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")); - } - - @Test - public void routeIgnoreContextPathIfPrefixHeader() { - this.properties.setStripPrefix(false); - this.request.setRequestURI("/api/foo/1"); - this.request.setContextPath("/context-path"); - this.request.addHeader("X-Forwarded-Prefix", "/prefix"); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/api/foo/**", "foo", null, false, null, null)); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/api/foo/1", ctx.get(REQUEST_URI_KEY)); - assertEquals("localhost", ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("80", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - assertEquals("/prefix", ctx.getZuulRequestHeaders().get("x-forwarded-prefix")); - assertEquals("foo", - getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")); - } - - @Test - public void prefixRouteIgnoreContextPathIfPrefixHeader() { - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.request.setRequestURI("/api/foo/1"); - this.request.setContextPath("/context-path"); - this.request.addHeader("X-Forwarded-Prefix", "/prefix"); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/foo/1", ctx.get(REQUEST_URI_KEY)); - assertEquals("localhost", ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("80", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - assertEquals("/prefix/api", - ctx.getZuulRequestHeaders().get("x-forwarded-prefix")); - assertEquals("foo", - getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")); - } - - @Test - public void forwardRouteAddsLocation() throws Exception { - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.request.setRequestURI("/api/foo/1"); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", null, "forward:/foo", true, null, null)); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/foo/1", ctx.get(FORWARD_TO_KEY)); - } - - @Test - public void forwardWithoutStripPrefixAppendsPath() throws Exception { - this.request.setRequestURI("/foo/1"); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", null, "forward:/bar", false, null, null)); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/bar/foo/1", ctx.get(FORWARD_TO_KEY)); - } - - @Test - public void prefixRouteWithRouteStrippingAddsHeader() throws Exception { - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.request.setRequestURI("/api/foo/1"); - this.routeLocator.addRoute("/foo/**", "foo"); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/1", ctx.get(REQUEST_URI_KEY)); - assertEquals("localhost", ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - assertEquals("/api/foo", ctx.getZuulRequestHeaders().get("x-forwarded-prefix")); - assertEquals("foo", - getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")); - } - - @Test - public void routeNotFound() throws Exception { - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", null, "forward:/foo", true, null, null)); - - this.request.setRequestURI("/api/bar/1"); - - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/api/bar/1", ctx.get(FORWARD_TO_KEY)); - } - - @Test - public void routeNotFoundDispatcherServletSpecialPath() throws Exception { - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.properties.setAddProxyHeaders(true); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", null, "forward:/foo", true, null, null)); - - this.filter = new PreDecorationFilter(this.routeLocator, "/special", - this.properties, this.proxyRequestHelper); - - this.request.setRequestURI("/api/bar/1"); - - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/special/api/bar/1", ctx.get(FORWARD_TO_KEY)); - } - - @Test - public void routeNotFoundZuulRequest() throws Exception { - setTestRequestContext(); - RequestContext ctx = RequestContext.getCurrentContext(); - RequestContext.getCurrentContext().setZuulEngineRan(); - this.request.setRequestURI("/zuul/api/bar/1"); - ctx.setRequest(this.request); - - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.properties.setServletPath("/zuul"); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", null, "forward:/foo", true, null, null)); - - this.filter.run(); - - assertEquals("/api/bar/1", ctx.get(FORWARD_TO_KEY)); - } - - @Test - public void routeNotFoundZuulRequestDispatcherServletSpecialPath() throws Exception { - setTestRequestContext(); - RequestContext ctx = RequestContext.getCurrentContext(); - RequestContext.getCurrentContext().setZuulEngineRan(); - this.request.setRequestURI("/zuul/api/bar/1"); - ctx.setRequest(this.request); - - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.properties.setServletPath("/zuul"); - this.properties.setAddProxyHeaders(true); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", null, "forward:/foo", true, null, null)); - this.filter = new PreDecorationFilter(this.routeLocator, "/special", - this.properties, this.proxyRequestHelper); - - this.filter.run(); - - assertEquals("/special/api/bar/1", ctx.get(FORWARD_TO_KEY)); - } - - @Test - public void routeNotFoundZuulRequestZuulHomeMapping() throws Exception { - setTestRequestContext(); - RequestContext ctx = RequestContext.getCurrentContext(); - RequestContext.getCurrentContext().setZuulEngineRan(); - this.request.setRequestURI("/api/bar/1"); - ctx.setRequest(this.request); - - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.properties.setServletPath("/"); - this.properties.setAddProxyHeaders(true); - this.routeLocator.addRoute( - new ZuulRoute("foo", "/foo/**", null, "forward:/foo", true, null, null)); - - this.filter = new PreDecorationFilter(this.routeLocator, "/special", - this.properties, this.proxyRequestHelper); - - this.filter.run(); - - assertEquals("/special/api/bar/1", ctx.get(FORWARD_TO_KEY)); - } - - @Test - public void sensitiveHeadersOverride() throws Exception { - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.properties.setSensitiveHeaders(Collections.singleton("x-bar")); - this.request.setRequestURI("/api/foo/1"); - ZuulRoute route = new ZuulRoute("/foo/**", "foo"); - route.setSensitiveHeaders(Collections.singleton("x-foo")); - this.routeLocator.addRoute(route); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - @SuppressWarnings("unchecked") - Set sensitiveHeaders = (Set) ctx - .get(ProxyRequestHelper.IGNORED_HEADERS); - assertTrue("sensitiveHeaders is wrong: " + sensitiveHeaders, - sensitiveHeaders.containsAll(Collections.singletonList("x-foo"))); - assertFalse("sensitiveHeaders is wrong: " + sensitiveHeaders, - sensitiveHeaders.contains("Cookie")); - } - - @Test - public void sensitiveHeadersOverrideEmpty() throws Exception { - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.properties.setSensitiveHeaders(Collections.singleton("x-bar")); - this.request.setRequestURI("/api/foo/1"); - ZuulRoute route = new ZuulRoute("/foo/**", "foo"); - route.setSensitiveHeaders(Collections.emptySet()); - this.routeLocator.addRoute(route); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - @SuppressWarnings("unchecked") - Set sensitiveHeaders = (Set) ctx - .get(ProxyRequestHelper.IGNORED_HEADERS); - assertTrue("sensitiveHeaders is wrong: " + sensitiveHeaders, - sensitiveHeaders.isEmpty()); - } - - @Test - public void sensitiveHeadersDefaults() throws Exception { - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.properties.setSensitiveHeaders(Collections.singleton("x-bar")); - this.request.setRequestURI("/api/foo/1"); - this.routeLocator.addRoute("/foo/**", "foo"); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - @SuppressWarnings("unchecked") - Set sensitiveHeaders = (Set) ctx - .get(ProxyRequestHelper.IGNORED_HEADERS); - assertTrue("sensitiveHeaders is wrong: " + sensitiveHeaders, - sensitiveHeaders.containsAll(Collections.singletonList("x-bar"))); - assertFalse("sensitiveHeaders is wrong", sensitiveHeaders.contains("Cookie")); - } - - @Test - public void sensitiveHeadersCaseInsensitive() throws Exception { - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.properties.setSensitiveHeaders(Collections.singleton("X-bAr")); - this.request.setRequestURI("/api/foo/1"); - this.routeLocator.addRoute("/foo/**", "foo"); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - @SuppressWarnings("unchecked") - Set sensitiveHeaders = (Set) ctx - .get(ProxyRequestHelper.IGNORED_HEADERS); - assertTrue("sensitiveHeaders is wrong: " + sensitiveHeaders, - sensitiveHeaders.containsAll(Collections.singletonList("x-bar"))); - } - - @Test - public void sensitiveHeadersOverrideCaseInsensitive() throws Exception { - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.properties.setSensitiveHeaders(Collections.singleton("X-bAr")); - this.request.setRequestURI("/api/foo/1"); - ZuulRoute route = new ZuulRoute("/foo/**", "foo"); - route.setSensitiveHeaders(Collections.singleton("X-Foo")); - this.routeLocator.addRoute(route); - this.filter.run(); - RequestContext ctx = RequestContext.getCurrentContext(); - @SuppressWarnings("unchecked") - Set sensitiveHeaders = (Set) ctx - .get(ProxyRequestHelper.IGNORED_HEADERS); - assertTrue("sensitiveHeaders is wrong: " + sensitiveHeaders, - sensitiveHeaders.containsAll(Collections.singletonList("x-foo"))); - } - - @Test - public void ignoredHeadersAlreadySetInRequestContextDontGetOverridden() - throws Exception { - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.properties.setSensitiveHeaders(Collections.singleton("x-bar")); - this.request.setRequestURI("/api/foo/1"); - this.routeLocator.addRoute("/foo/**", "foo"); - RequestContext ctx = RequestContext.getCurrentContext(); - ctx.set(ProxyRequestHelper.IGNORED_HEADERS, - new HashSet<>(Arrays.asList("x-foo"))); - this.filter.run(); - @SuppressWarnings("unchecked") - Set sensitiveHeaders = (Set) ctx - .get(ProxyRequestHelper.IGNORED_HEADERS); - assertTrue("sensitiveHeaders is wrong: " + sensitiveHeaders, - sensitiveHeaders.containsAll(Arrays.asList("x-bar", "x-foo"))); - } - - @Test - public void urlProperlyDecodedWhenCharacterEncodingIsSet() throws Exception { - this.request.setCharacterEncoding("UTF-8"); - this.properties.setPrefix("/api"); - this.properties.setStripPrefix(true); - this.request.setRequestURI("/api/foo/ol%C3%A9%D7%93%D7%A8%D7%A2%D7%A7"); - this.routeLocator.addRoute("/foo/**", "foo"); - RequestContext ctx = RequestContext.getCurrentContext(); - this.filter.run(); - String decodedRequestURI = (String) ctx.get(REQUEST_URI_KEY); - assertTrue(decodedRequestURI.equals("/oléדרעק")); - } - - private Object getHeader(List> headers, String key) { - String value = null; - for (Pair pair : headers) { - if (pair.first().toLowerCase().equals(key.toLowerCase())) { - value = pair.second(); - break; - } - } - return value; - } - - private void setTestRequestContext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - - } - -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/EagerLoadOfZuulConfigurationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/EagerLoadOfZuulConfigurationTests.java deleted file mode 100644 index 56f5b894..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/EagerLoadOfZuulConfigurationTests.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package org.springframework.cloud.netflix.zuul.filters.route; - -import com.netflix.zuul.context.RequestContext; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.concurrent.atomic.AtomicInteger; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringRunner.class) -@SpringBootTest(properties = { "zuul.routes.eagerroute.service-id=eager", - "zuul.ribbon.eager-load.enabled=true" }) -@DirtiesContext -public class EagerLoadOfZuulConfigurationTests { - - @Before - public void setTestRequestContext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - @Test - public void testEagerLoading() { - // Child context FooConfig should have been eagerly instantiated.. - assertThat(Foo.getInstanceCount()).isEqualTo(1); - } - - @EnableAutoConfiguration - @Configuration - @EnableZuulProxy - @RibbonClients(@RibbonClient(name = "eager", configuration = FooConfig.class)) - static class TestConfig { - - } - - static class Foo { - private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger(); - - public Foo() { - INSTANCE_COUNT.incrementAndGet(); - } - - public static int getInstanceCount() { - return INSTANCE_COUNT.get(); - } - } - - static class FooConfig { - - @Bean - public Foo foo() { - return new Foo(); - } - - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/LazyLoadOfZuulConfigurationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/LazyLoadOfZuulConfigurationTests.java deleted file mode 100644 index a39be7bb..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/LazyLoadOfZuulConfigurationTests.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.route; - -import java.util.concurrent.atomic.AtomicInteger; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.cloud.netflix.ribbon.StaticServerList; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.zuul.context.RequestContext; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT, properties = { - "zuul.routes.lazyroute.service-id=lazy", "zuul.routes.lazyroute.path=/lazy/**", - "zuul.ribbon.eager-load.enabled=false"}) -@DirtiesContext -public class LazyLoadOfZuulConfigurationTests { - - @LocalServerPort - protected int port; - - @Before - public void setTestRequestContext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void testLazyLoading() { - // Child context FooConfig should be lazily created.. - assertThat(Foo.getInstanceCount()).isEqualTo(0); - - String uri = String.format("http://localhost:%d/lazy/sample", this.port); - - ResponseEntity result = new TestRestTemplate().getForEntity(uri, - String.class); - - // the instance should be available now.. - assertThat(Foo.getInstanceCount()).isEqualTo(1); - - assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(result.getBody()).isEqualTo("sample"); - } - - @EnableAutoConfiguration - @Configuration - @EnableZuulProxy - @RibbonClients(@RibbonClient(name = "lazy", configuration = FooConfig.class)) - static class TestConfig { - - } - - static class Foo { - private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger(); - - public Foo() { - INSTANCE_COUNT.incrementAndGet(); - } - - public static int getInstanceCount() { - return INSTANCE_COUNT.get(); - } - } - - static class FooConfig { - - @Bean - public Foo foo() { - return new Foo(); - } - - @LocalServerPort - private int port; - - @Bean - public ServerList ribbonServerList() { - return new StaticServerList<>(new Server("localhost", this.port)); - } - - } - - @Configuration - @RestController - static class SampleWebConfig { - - @RequestMapping("/sample") - public String sampleEndpoint() { - return "sample"; - } - - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommandTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommandTests.java deleted file mode 100644 index 1f5cd8b9..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommandTests.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.startsWith; -import static org.hamcrest.core.IsNull.nullValue; -import static org.junit.Assert.assertThat; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.net.URI; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Collections; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.StreamUtils; - -import com.netflix.client.http.HttpRequest; -import com.netflix.client.http.HttpRequest.Verb; - -/** - * @author Spencer Gibb - */ -public class RestClientRibbonCommandTests { - - private ZuulProperties zuulProperties; - - @Before - public void setUp() { - zuulProperties = new ZuulProperties(); - } - - /** - * Tests old constructors kept for backwards compatibility with Spring Cloud Sleuth 1.x versions - */ - @Test - @Deprecated - public void testNullEntityWithOldConstruct() throws Exception { - String uri = "http://example.com"; - LinkedMultiValueMap headers = new LinkedMultiValueMap<>(); - headers.add("my-header", "my-value"); - LinkedMultiValueMap params = new LinkedMultiValueMap<>(); - params.add("myparam", "myparamval"); - RestClientRibbonCommand command = - new RestClientRibbonCommand("cmd", null,Verb.GET ,uri, false, headers, params, null); - - HttpRequest request = command.createRequest(); - - assertThat("uri is wrong", request.getUri().toString(), startsWith(uri)); - assertThat("my-header is wrong", request.getHttpHeaders().getFirstValue("my-header"), is(equalTo("my-value"))); - assertThat("myparam is missing", request.getQueryParams().get("myparam").iterator().next(), is(equalTo("myparamval"))); - - command = - new RestClientRibbonCommand("cmd", null, - new RibbonCommandContext("example", "GET", uri, false, headers, params, null), - zuulProperties); - - request = command.createRequest(); - - assertThat("uri is wrong", request.getUri().toString(), startsWith(uri)); - assertThat("my-header is wrong", request.getHttpHeaders().getFirstValue("my-header"), is(equalTo("my-value"))); - assertThat("myparam is missing", request.getQueryParams().get("myparam").iterator().next(), is(equalTo("myparamval"))); - } - - @Test - public void testNullEntity() throws Exception { - String uri = "http://example.com"; - LinkedMultiValueMap headers = new LinkedMultiValueMap<>(); - headers.add("my-header", "my-value"); - LinkedMultiValueMap params = new LinkedMultiValueMap<>(); - params.add("myparam", "myparamval"); - RestClientRibbonCommand command = - new RestClientRibbonCommand("cmd", null, - new RibbonCommandContext("example", "GET", uri, false, headers, params, null, new ArrayList()), - zuulProperties); - - HttpRequest request = command.createRequest(); - - assertThat("uri is wrong", request.getUri().toString(), startsWith(uri)); - assertThat("my-header is wrong", request.getHttpHeaders().getFirstValue("my-header"), is(equalTo("my-value"))); - assertThat("myparam is missing", request.getQueryParams().get("myparam").iterator().next(), is(equalTo("myparamval"))); - } - - @Test - // this situation happens, see https://github.com/spring-cloud/spring-cloud-netflix/issues/1042#issuecomment-227723877 - public void testEmptyEntityGet() throws Exception { - String entityValue = ""; - testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), false, "GET"); - } - - @Test - public void testNonEmptyEntityPost() throws Exception { - String entityValue = "abcd"; - testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), true, "POST"); - } - - @Test - public void testNonEmptyEntityDelete() throws Exception { - String entityValue = "abcd"; - testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), true, "DELETE"); - } - - void testEntity(String entityValue, ByteArrayInputStream requestEntity, boolean addContentLengthHeader, String method) throws Exception { - String lengthString = String.valueOf(entityValue.length()); - Long length = null; - URI uri = URI.create("http://example.com"); - LinkedMultiValueMap headers = new LinkedMultiValueMap<>(); - if (addContentLengthHeader) { - headers.add("Content-Length", lengthString); - length = (long) entityValue.length(); - } - - RibbonRequestCustomizer requestCustomizer = new RibbonRequestCustomizer() { - @Override - public boolean accepts(Class builderClass) { - return builderClass == HttpRequest.Builder.class; - } - - @Override - public void customize(HttpRequest.Builder builder) { - builder.header("from-customizer", "foo"); - } - }; - RibbonCommandContext context = new RibbonCommandContext("example", method, - uri.toString(), false, headers, new LinkedMultiValueMap(), - requestEntity, Collections.singletonList(requestCustomizer)); - context.setContentLength(length); - RestClientRibbonCommand command = new RestClientRibbonCommand("cmd", null, context, zuulProperties); - - HttpRequest request = command.createRequest(); - - assertThat("uri is wrong", request.getUri().toString(), startsWith(uri.toString())); - if (addContentLengthHeader) { - assertThat("Content-Length is wrong", request.getHttpHeaders().getFirstValue("Content-Length"), - is(equalTo(lengthString))); - } - assertThat("from-customizer is wrong", request.getHttpHeaders().getFirstValue("from-customizer"), - is(equalTo("foo"))); - - - if (method.equalsIgnoreCase("DELETE")) { - assertThat("entity is was non-null", request.getEntity(), is(nullValue())); - } else { - assertThat("entity is missing", request.getEntity(), is(notNullValue())); - assertThat("entity is wrong type", InputStream.class.isAssignableFrom(request.getEntity().getClass()), is(true)); - InputStream entity = (InputStream) request.getEntity(); - String string = StreamUtils.copyToString(entity, Charset.forName("UTF-8")); - assertThat("content is wrong", string, is(equalTo(entityValue))); - } - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilterLoadBalancerKeyIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilterLoadBalancerKeyIntegrationTests.java deleted file mode 100644 index 6acd0506..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilterLoadBalancerKeyIntegrationTests.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.route; - -import com.netflix.loadbalancer.AvailabilityFilteringRule; -import com.netflix.loadbalancer.IRule; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.StaticServerList; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.*; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; - -import static org.junit.Assert.assertEquals; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.LOAD_BALANCER_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; - -/** - * @author Yongsung Yoon - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = CanaryTestZuulProxyApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - value = { "zuul.routes.simple.path: /simple/**" }) -@DirtiesContext -public class RibbonRoutingFilterLoadBalancerKeyIntegrationTests { - - @Autowired - private TestRestTemplate testRestTemplate; - - @Before - public void setTestRequestContext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - @Test - public void invokeWithUserDefinedCanaryHeader() { - HttpHeaders headers = new HttpHeaders(); - headers.set("X-Canary-Test", "true"); - - ResponseEntity result = testRestTemplate.exchange("/simple/hello", HttpMethod.GET, - new HttpEntity<>(headers), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("canary", result.getBody()); - } - - @Test - public void invokeWithoutUserDefinedCanaryHeader() { - HttpHeaders headers = new HttpHeaders(); - ResponseEntity result = testRestTemplate.exchange("/simple/hello", HttpMethod.GET, - new HttpEntity<>(headers), String.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); - } -} - -@Configuration -@EnableAutoConfiguration -@RestController -@EnableZuulProxy -@RibbonClient(name = "simple", configuration = CanaryTestRibbonClientConfiguration.class) -class CanaryTestZuulProxyApplication { - - @RequestMapping(value = "/hello", method = RequestMethod.GET) - public String hello() { - return "canary"; - } - - @Bean - public ZuulFilter testCanarySupportPreFilter() { - return new ZuulFilter() { - @Override - public Object run() { - RequestContext context = RequestContext.getCurrentContext(); - if (checkIfCanaryRequest(context)) { - context.set(LOAD_BALANCER_KEY, "canary"); // set loadBalancerKey for IRule - } - return null; - } - - private boolean checkIfCanaryRequest(RequestContext context) { - HttpServletRequest request = context.getRequest(); - String canaryHeader = request.getHeader("X-Canary-Test"); // user defined header - - if ((canaryHeader != null) && (canaryHeader.equalsIgnoreCase("true"))) { - return true; - } - return false; - } - - @Override - public boolean shouldFilter() { - return true; - } - - @Override - public String filterType() { - return PRE_TYPE; - } - - @Override - public int filterOrder() { - return 0; - } - }; - } -} - -@Configuration -class CanaryTestRibbonClientConfiguration { - - @LocalServerPort - private int port; - - private static Server testCanaryInstance; - - @Bean - public ServerList ribbonServerList() { - return new StaticServerList<>(new Server("normal-routing-notexist-localhost", this.port)); - } - - @Bean - public IRule canaryTestRule() { - if (testCanaryInstance == null) { - testCanaryInstance = new Server("localhost", port); // use test server as a canary instance - } - return new TestCanaryRule(); - } - - public static class TestCanaryRule extends AvailabilityFilteringRule { - @Override - public Server choose(Object key) { - if ((key != null) && (key.equals("canary"))) { - return testCanaryInstance; // choose test canary server instead of normal servers. - } - return super.choose(key); // normal routing - } - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilterTests.java deleted file mode 100644 index 7a783d30..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilterTests.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collections; - -import com.netflix.zuul.context.RequestContext; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer; -import org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelper; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; - -import javax.servlet.http.HttpServletResponse; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.LOAD_BALANCER_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVICE_ID_KEY; - -/** - * @author Spencer Gibb - * @author Yongsung Yoon - * @author Gang Li - */ -public class RibbonRoutingFilterTests { - - private RequestContext requestContext; - private RibbonRoutingFilter filter; - - @Before - public void setUp() throws Exception { - setUpRequestContext(); - setupRibbonRoutingFilter(); - } - - @After - public void tearDown() throws Exception { - requestContext.unset(); - } - - @Test - public void useServlet31Works() { - assertThat(filter.isUseServlet31()).isTrue(); - } - - @Test - public void testLoadBalancerKeyToRibbonCommandContext() throws Exception { - final String testKey = "testLoadBalancerKey"; - requestContext.set(LOAD_BALANCER_KEY, testKey); - RibbonCommandContext commandContext = filter.buildCommandContext(requestContext); - - assertThat(commandContext.getLoadBalancerKey()).isEqualTo(testKey); - } - - @Test - public void testNullLoadBalancerKeyToRibbonCommandContext() throws Exception { - requestContext.set(LOAD_BALANCER_KEY, null); - RibbonCommandContext commandContext = filter.buildCommandContext(requestContext); - - assertThat(commandContext.getLoadBalancerKey()).isNull(); - } - - @Test - public void testSetResponseWithNonHttpStatusCode() throws Exception { - ClientHttpResponse response = this.createClientHttpResponseWithNonStatus(); - this.filter.setResponse(response); - assertThat(517).isEqualTo(this.requestContext.get("responseStatusCode")); - } - - @Test - public void testSetResponseWithHttpStatusCode() throws Exception { - ClientHttpResponse response = this.createClientHttpResponse(); - this.filter.setResponse(response); - assertThat(200).isEqualTo(this.requestContext.get("responseStatusCode")); - } - - private void setUpRequestContext() { - requestContext = RequestContext.getCurrentContext(); - MockHttpServletRequest mockRequest = new MockHttpServletRequest(); - HttpServletResponse httpServletResponse = new MockHttpServletResponse(); - mockRequest.setMethod("GET"); - mockRequest.setRequestURI("/foo/bar"); - requestContext.setRequest(mockRequest); - requestContext.setRequestQueryParams(Collections.EMPTY_MAP); - requestContext.set(SERVICE_ID_KEY, "testServiceId"); - requestContext.set("response", httpServletResponse); - } - - private void setupRibbonRoutingFilter() { - RibbonCommandFactory factory = mock(RibbonCommandFactory.class); - filter = new RibbonRoutingFilter(new ProxyRequestHelper(), factory, Collections.emptyList()); - } - - private ClientHttpResponse createClientHttpResponseWithNonStatus() { - return new ClientHttpResponse() { - @Override - public HttpStatus getStatusCode() throws IOException { - return null; - } - - @Override - public int getRawStatusCode() throws IOException { - return 517; - } - - @Override - public String getStatusText() throws IOException { - return "Fail"; - } - - @Override - public void close() { - - } - - @Override - public InputStream getBody() throws IOException { - return new ByteArrayInputStream("Fail".getBytes()); - } - - @Override - public HttpHeaders getHeaders() { - HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON); - return httpHeaders; - } - }; - } - - private ClientHttpResponse createClientHttpResponse() { - return new ClientHttpResponse() { - @Override - public HttpStatus getStatusCode() throws IOException { - return HttpStatus.OK; - } - - @Override - public int getRawStatusCode() throws IOException { - return 200; - } - - @Override - public String getStatusText() throws IOException { - return "OK"; - } - - @Override - public void close() { - - } - - @Override - public InputStream getBody() throws IOException { - return new ByteArrayInputStream("OK".getBytes()); - } - - @Override - public HttpHeaders getHeaders() { - HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON); - return httpHeaders; - } - }; - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SendForwardFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SendForwardFilterTests.java deleted file mode 100644 index f25c953d..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SendForwardFilterTests.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.route; - -import javax.servlet.http.HttpServletRequest; - -import com.netflix.zuul.context.RequestContext; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORWARD_TO_KEY; - -/** - * @author Dave Syer - */ -public class SendForwardFilterTests { - - @After - public void reset() { - RequestContext.getCurrentContext().clear(); - } - - @Before - public void setTestRequestcontext() { - RequestContext context = new RequestContext(); - RequestContext.testSetCurrentContext(context); - } - - @Test - public void runsNormally() { - SendForwardFilter filter = createSendForwardFilter(new MockHttpServletRequest()); - assertTrue("shouldFilter returned false", filter.shouldFilter()); - filter.run(); - } - - private SendForwardFilter createSendForwardFilter(HttpServletRequest request) { - RequestContext context = new RequestContext(); - context.setRequest(request); - context.setResponse(new MockHttpServletResponse()); - context.set(FORWARD_TO_KEY, "/foo"); - RequestContext.testSetCurrentContext(context); - SendForwardFilter filter = new SendForwardFilter(); - return filter; - } - - @Test - public void doesNotRunTwice() { - SendForwardFilter filter = createSendForwardFilter(new MockHttpServletRequest()); - assertTrue("shouldFilter returned false", filter.shouldFilter()); - filter.run(); - assertFalse("shouldFilter returned true", filter.shouldFilter()); - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilterTests.java deleted file mode 100644 index 339c622a..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilterTests.java +++ /dev/null @@ -1,395 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Field; -import java.net.URL; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.Collections; -import java.util.concurrent.TimeUnit; -import java.util.zip.GZIPOutputStream; - -import javax.servlet.http.HttpServletResponse; - -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.monitoring.CounterFactory; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.Configurable; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.entity.InputStreamEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.assertj.core.api.Assertions; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory; -import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory; -import org.springframework.cloud.commons.httpclient.DefaultApacheHttpClientConnectionManagerFactory; -import org.springframework.cloud.commons.httpclient.DefaultApacheHttpClientFactory; -import org.springframework.cloud.context.environment.EnvironmentChangeEvent; -import org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelper; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.metrics.EmptyCounterFactory; -import org.springframework.cloud.netflix.zuul.util.ZuulRuntimeException; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.ReflectionUtils; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; -import static org.springframework.boot.test.util.EnvironmentTestUtils.addEnvironment; -import static org.springframework.util.StreamUtils.copyToByteArray; -import static org.springframework.util.StreamUtils.copyToString; - -/** - * @author Andreas Kluth - * @author Spencer Gibb - * @author Gang Li - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SampleApplication.class, - webEnvironment = RANDOM_PORT, - properties = {"server.servlet.contextPath: /app"}) -@DirtiesContext -public class SimpleHostRoutingFilterTests { - - private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - - @LocalServerPort - private int port; - - @Before - public void setup() { - CounterFactory.initialize(new EmptyCounterFactory()); - } - - @After - public void clear() { - if (this.context != null) { - this.context.close(); - } - CounterFactory.initialize(null); - } - - @Test - public void timeoutPropertiesAreApplied() { - addEnvironment(this.context, "zuul.host.socket-timeout-millis=11000", - "zuul.host.connect-timeout-millis=2100"); - setupContext(); - CloseableHttpClient httpClient = getFilter().newClient(); - Assertions.assertThat(httpClient).isInstanceOf(Configurable.class); - RequestConfig config = ((Configurable) httpClient).getConfig(); - assertEquals(11000, config.getSocketTimeout()); - assertEquals(2100, config.getConnectTimeout()); - } - - @Test - public void connectionPropertiesAreApplied() { - addEnvironment(this.context, "zuul.host.maxTotalConnections=100", - "zuul.host.maxPerRouteConnections=10", "zuul.host.timeToLive=5", - "zuul.host.timeUnit=SECONDS"); - setupContext(); - PoolingHttpClientConnectionManager connMgr = (PoolingHttpClientConnectionManager)getFilter().getConnectionManager(); - assertEquals(100, connMgr.getMaxTotal()); - assertEquals(10, connMgr.getDefaultMaxPerRoute()); - Object pool = getField(connMgr, "pool"); - Long timeToLive = getField(pool, "timeToLive"); - TimeUnit timeUnit = getField(pool, "tunit"); - assertEquals(new Long(5), timeToLive); - assertEquals(TimeUnit.SECONDS, timeUnit); - } - - protected T getField(Object target, String name) { - Field field = ReflectionUtils.findField(target.getClass(), name); - ReflectionUtils.makeAccessible(field); - Object value = ReflectionUtils.getField(field, target); - return (T)value; - } - - @Test - public void validateSslHostnamesByDefault() { - setupContext(); - assertTrue("Hostname verification should be enabled by default", - getFilter().isSslHostnameValidationEnabled()); - } - - @Test - public void validationOfSslHostnamesCanBeDisabledViaProperty() { - addEnvironment(this.context, "zuul.sslHostnameValidationEnabled=false"); - setupContext(); - assertFalse("Hostname verification should be disabled via property", - getFilter().isSslHostnameValidationEnabled()); - } - - @Test - public void defaultPropertiesAreApplied() { - setupContext(); - PoolingHttpClientConnectionManager connMgr = (PoolingHttpClientConnectionManager)getFilter().getConnectionManager(); - - assertEquals(200, connMgr.getMaxTotal()); - assertEquals(20, connMgr.getDefaultMaxPerRoute()); - } - - @Test - public void deleteRequestBuiltWithBody() { - setupContext(); - InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(new byte[]{1})); - HttpRequest httpRequest = getFilter().buildHttpRequest("DELETE", "uri", inputStreamEntity, - new LinkedMultiValueMap(), new LinkedMultiValueMap(), new MockHttpServletRequest()); - - assertTrue(httpRequest instanceof HttpEntityEnclosingRequest); - HttpEntityEnclosingRequest httpEntityEnclosingRequest = (HttpEntityEnclosingRequest) httpRequest; - assertTrue(httpEntityEnclosingRequest.getEntity() != null); - } - - @Test - public void httpClientDoesNotDecompressEncodedData() throws Exception { - setupContext(); - InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(new byte[]{1})); - HttpRequest httpRequest = getFilter().buildHttpRequest("GET", "/app/compressed/get/1", inputStreamEntity, - new LinkedMultiValueMap(), new LinkedMultiValueMap(), new MockHttpServletRequest()); - - CloseableHttpResponse response = getFilter().newClient().execute(new HttpHost("localhost", this.port), httpRequest); - assertEquals(200, response.getStatusLine().getStatusCode()); - byte[] responseBytes = copyToByteArray(response.getEntity().getContent()); - assertTrue(Arrays.equals(GZIPCompression.compress("Get 1"), responseBytes)); - } - - @Test - public void httpClientPreservesUnencodedData() throws Exception { - setupContext(); - InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(new byte[]{1})); - HttpRequest httpRequest = getFilter().buildHttpRequest("GET", "/app/get/1", inputStreamEntity, - new LinkedMultiValueMap(), new LinkedMultiValueMap(), new MockHttpServletRequest()); - - CloseableHttpResponse response = getFilter().newClient().execute(new HttpHost("localhost", this.port), httpRequest); - assertEquals(200, response.getStatusLine().getStatusCode()); - String responseString = copyToString(response.getEntity().getContent(), Charset.forName("UTF-8")); - assertTrue("Get 1".equals(responseString)); - } - - - @Test - public void redirectTest() throws Exception { - setupContext(); - InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(new byte[]{})); - HttpRequest httpRequest = getFilter().buildHttpRequest("GET", "/app/redirect", inputStreamEntity, - new LinkedMultiValueMap(), new LinkedMultiValueMap(), new MockHttpServletRequest()); - - CloseableHttpResponse response = getFilter().newClient().execute(new HttpHost("localhost", this.port), httpRequest); - assertEquals(302, response.getStatusLine().getStatusCode()); - String responseString = copyToString(response.getEntity().getContent(), Charset.forName("UTF-8")); - assertTrue(response.getLastHeader("Location").getValue().contains("/app/get/5")); - } - - @Test - public void zuulHostKeysUpdateHttpClient() { - setupContext(); - SimpleHostRoutingFilter filter = getFilter(); - CloseableHttpClient httpClient = (CloseableHttpClient) ReflectionTestUtils.getField(filter, "httpClient"); - EnvironmentChangeEvent event = new EnvironmentChangeEvent(Collections.singleton("zuul.host.mykey")); - filter.onPropertyChange(event); - CloseableHttpClient newhttpClient = (CloseableHttpClient) ReflectionTestUtils.getField(filter, "httpClient"); - Assertions.assertThat(httpClient).isNotEqualTo(newhttpClient); - } - - @Test - public void getRequestBody() throws Exception { - setupContext(); - MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); - request.setContent("{1}".getBytes()); - request.addHeader("singleName", "singleValue"); - request.addHeader("multiName", "multiValue1"); - request.addHeader("multiName", "multiValue2"); - RequestContext.getCurrentContext().setRequest(request); - InputStream inputStream = getFilter().getRequestBody(request); - assertTrue(Arrays.equals("{1}".getBytes(), copyToByteArray(inputStream))); - } - - @Test - public void putRequestBuiltWithBody() throws Exception { - setupContext(); - InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(new byte[]{1})); - HttpRequest httpRequest = getFilter().buildHttpRequest("PUT", "uri", inputStreamEntity, - new LinkedMultiValueMap(), new LinkedMultiValueMap(), new MockHttpServletRequest()); - - assertTrue(httpRequest instanceof HttpEntityEnclosingRequest); - HttpEntityEnclosingRequest httpEntityEnclosingRequest = (HttpEntityEnclosingRequest) httpRequest; - assertTrue(httpEntityEnclosingRequest.getEntity() != null); - } - - @Test - public void postRequestBuiltWithBody() throws Exception { - setupContext(); - InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(new byte[]{1})); - HttpRequest httpRequest = getFilter().buildHttpRequest("POST", "uri", inputStreamEntity, - new LinkedMultiValueMap(), new LinkedMultiValueMap(), new MockHttpServletRequest()); - - assertTrue(httpRequest instanceof HttpEntityEnclosingRequest); - HttpEntityEnclosingRequest httpEntityEnclosingRequest = (HttpEntityEnclosingRequest) httpRequest; - assertTrue(httpEntityEnclosingRequest.getEntity() != null); - } - - @Test - public void pathRequestBuiltWithBody() throws Exception { - setupContext(); - InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(new byte[]{1})); - HttpRequest httpRequest = getFilter().buildHttpRequest("PATCH", "uri", inputStreamEntity, - new LinkedMultiValueMap(), new LinkedMultiValueMap(), new MockHttpServletRequest()); - - HttpPatch basicHttpRequest = (HttpPatch) httpRequest; - assertTrue(basicHttpRequest.getEntity() != null); - } - - @Test - public void shouldFilterFalse() throws Exception { - setupContext(); - assertEquals(false, getFilter().shouldFilter()); - } - - @Test - public void shouldFilterTrue() throws Exception { - setupContext(); - RequestContext.getCurrentContext().set("routeHost", new URL("http://localhost:8080")); - RequestContext.getCurrentContext().set("sendZuulResponse", true); - assertEquals(true, getFilter().shouldFilter()); - } - - @Test - public void filterOrder() throws Exception { - setupContext(); - assertEquals(100, getFilter().filterOrder()); - } - - @Test(expected = ZuulRuntimeException.class) - public void run() throws Exception { - setupContext(); - MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); - request.setContent("{1}".getBytes()); - request.addHeader("singleName", "singleValue"); - request.addHeader("multiName", "multiValue1"); - request.addHeader("multiName", "multiValue2"); - RequestContext.getCurrentContext().setRequest(request); - URL url = new URL("http://localhost:8080"); - RequestContext.getCurrentContext().set("routeHost", url); - getFilter().run(); - } - - private void setupContext() { - this.context.register(PropertyPlaceholderAutoConfiguration.class, - TestConfiguration.class); - this.context.refresh(); - } - - private SimpleHostRoutingFilter getFilter() { - return this.context.getBean(SimpleHostRoutingFilter.class); - } - - @Configuration - @EnableConfigurationProperties - protected static class TestConfiguration { - @Bean - ZuulProperties zuulProperties() { - return new ZuulProperties(); - } - - @Bean - ApacheHttpClientFactory clientFactory() {return new DefaultApacheHttpClientFactory(HttpClientBuilder.create()); } - - @Bean - ApacheHttpClientConnectionManagerFactory connectionManagerFactory() { return new DefaultApacheHttpClientConnectionManagerFactory(); } - - @Bean - SimpleHostRoutingFilter simpleHostRoutingFilter(ZuulProperties zuulProperties, - ApacheHttpClientConnectionManagerFactory connectionManagerFactory, - ApacheHttpClientFactory clientFactory) { - return new SimpleHostRoutingFilter(new ProxyRequestHelper(), zuulProperties, connectionManagerFactory, clientFactory); - } - } -} - -@Configuration -@EnableAutoConfiguration -@RestController -class SampleApplication { - - public static void main(String[] args) { - SpringApplication.run(SampleApplication.class, args); - } - - @RequestMapping(value = "/compressed/get/{id}", method = RequestMethod.GET) - public byte[] getCompressed(@PathVariable String id, HttpServletResponse response) throws IOException { - response.setHeader("content-encoding", "gzip"); - return GZIPCompression.compress("Get " + id); - } - - @RequestMapping(value = "/get/{id}", method = RequestMethod.GET) - public String getString(@PathVariable String id, HttpServletResponse response) throws IOException { - return "Get " + id; - } - - @RequestMapping(value = "/redirect", method = RequestMethod.GET) - public String redirect(HttpServletResponse response) throws IOException { - response.sendRedirect("/app/get/5"); - return null; - } -} - -class GZIPCompression { - - public static byte[] compress(final String str) throws IOException { - if ((str == null) || (str.length() == 0)) { - return null; - } - ByteArrayOutputStream obj = new ByteArrayOutputStream(); - GZIPOutputStream gzip = new GZIPOutputStream(obj); - gzip.write(str.getBytes("UTF-8")); - gzip.close(); - return obj.toByteArray(); - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFactoryTest.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFactoryTest.java deleted file mode 100644 index e37616b3..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFactoryTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.springframework.cloud.netflix.zuul.filters.route.apache; - -import java.util.HashSet; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; - -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; -import com.netflix.client.config.IClientConfigKey; -import com.netflix.config.ConfigurationManager; -import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -/** - * @author Ryan Baxter - */ -public class HttpClientRibbonCommandFactoryTest { - - SpringClientFactory springClientFactory; - ZuulProperties zuulProperties; - HttpClientRibbonCommandFactory ribbonCommandFactory; - - @Before - public void setup(){ - this.springClientFactory = mock(SpringClientFactory.class); - this.zuulProperties = new ZuulProperties(); - RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock(RibbonLoadBalancingHttpClient.class); - IClientConfig clientConfig = new DefaultClientConfigImpl(); - doReturn(loadBalancingHttpClient).when(this.springClientFactory).getClient(anyString(), - eq(RibbonLoadBalancingHttpClient.class)); - doReturn(clientConfig).when(this.springClientFactory).getClientConfig(anyString()); - this.ribbonCommandFactory = new HttpClientRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); - } - - @After - public void after() { - ConfigurationManager.getConfigInstance().clear(); - HystrixPropertiesFactory.reset(); - } - - @Test - public void testHystrixTimeoutValue() throws Exception { - RibbonCommandContext context = mock(RibbonCommandContext.class); - doReturn("service").when(context).getServiceId(); - HttpClientRibbonCommand ribbonCommand = this.ribbonCommandFactory.create(context); - assertEquals(2000, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); - } - - @Test - public void testHystrixTimeoutValueSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", 50); - RibbonCommandContext context = mock(RibbonCommandContext.class); - doReturn("service").when(context).getServiceId(); - HttpClientRibbonCommand ribbonCommand = this.ribbonCommandFactory.create(context); - assertEquals(50, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); - } - - @Test - public void testHystrixTimeoutValueCommandSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.service.execution.isolation.thread.timeoutInMilliseconds", 50); - RibbonCommandContext context = mock(RibbonCommandContext.class); - doReturn("service").when(context).getServiceId(); - HttpClientRibbonCommand ribbonCommand = this.ribbonCommandFactory.create(context); - assertEquals(50, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); - } - - @Test - public void testHystrixTimeoutValueCommandAndDefaultSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", 30); - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.service.execution.isolation.thread.timeoutInMilliseconds", 50); - RibbonCommandContext context = mock(RibbonCommandContext.class); - doReturn("service").when(context).getServiceId(); - HttpClientRibbonCommand ribbonCommand = this.ribbonCommandFactory.create(context); - assertEquals(50, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); - } - - @Test - public void testHystrixTimeoutValueRibbonTimeouts() throws Exception { - SpringClientFactory springClientFactory = mock(SpringClientFactory.class); - ZuulProperties zuulProperties = new ZuulProperties(); - RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock(RibbonLoadBalancingHttpClient.class); - IClientConfig clientConfig = new DefaultClientConfigImpl(); - clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); - clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); - doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(RibbonLoadBalancingHttpClient.class)); - doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); - RibbonCommandContext context = mock(RibbonCommandContext.class); - doReturn("service").when(context).getServiceId(); - HttpClientRibbonCommand ribbonCommand = ribbonCommandFactory.create(context); - assertEquals(600, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); - } - -} \ No newline at end of file diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFallbackTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFallbackTests.java deleted file mode 100644 index bfc1f86d..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFallbackTests.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.apache; - -import com.netflix.zuul.context.RequestContext; - -import org.junit.Before; -import org.junit.runner.RunWith; - -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.zuul.filters.route.support.RibbonCommandFallbackTests; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author Ryan Baxter - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = RibbonCommandFallbackTests.TestConfig.class, webEnvironment = RANDOM_PORT, properties = { - "zuul.routes.simple: /simple/**", "zuul.routes.another: /another/twolevel/**", - "ribbon.ReadTimeout: 1" }) -@DirtiesContext -public class HttpClientRibbonCommandFallbackTests extends RibbonCommandFallbackTests { - - @Before - public void init() { - RequestContext.getCurrentContext().clear(); - } - -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandIntegrationTests.java deleted file mode 100644 index 3a31a6bc..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandIntegrationTests.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.apache; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.springframework.http.HttpHeaders.SET_COOKIE; - -import java.util.Collections; -import java.util.Set; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.servlet.error.ErrorAttributes; -import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.ribbon.StaticServerList; -import org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; -import org.springframework.cloud.netflix.zuul.filters.route.RibbonCommandFactory; -import org.springframework.cloud.netflix.zuul.filters.route.support.ZuulProxyTestBase; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.util.WebUtils; - -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; - -/** - * @author Spencer Gibb - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = HttpClientRibbonCommandIntegrationTests.TestConfig.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { - "zuul.routes.other: /test/**=http://localhost:7777/local", - "zuul.routes.another: /another/twolevel/**", "zuul.routes.simple: /simple/**", - "zuul.routes.singleton.id: singleton", - "zuul.routes.singleton.path: /singleton/**", - "zuul.routes.singleton.sensitiveHeaders: " }) -@DirtiesContext -public class HttpClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { - - @Before - public void init() { - super.setTestRequestcontext(); - } - - @Test - public void patchOnSelfViaRibbonRoutingFilter() { - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/simple/local/1", HttpMethod.PATCH, - new HttpEntity<>("TestPatch"), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Patched 1!", result.getBody()); - } - - @Test - public void postOnSelfViaRibbonRoutingFilter() { - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/simple/local/1", HttpMethod.POST, - new HttpEntity<>("TestPost"), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted 1!", result.getBody()); - } - - @Test - public void deleteOnSelfViaRibbonRoutingFilter() { - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/simple/local/1", HttpMethod.DELETE, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Deleted 1!", result.getBody()); - } - - @Test - public void ribbonLoadBalancingHttpClientCookiePolicy() { - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/simple/downstream_cookie", - HttpMethod.POST, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Cookie 434354454!", result.getBody()); - assertNull(result.getHeaders().getFirst(SET_COOKIE)); - - // if new instance of RibbonLoadBalancingHttpClient is getting created every time - // and HttpClient is not reused then there are no concerns for the shared cookie - // storage - // but since https://github.com/spring-cloud/spring-cloud-netflix/issues/1150 is - // on the way a - result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/singleton/downstream_cookie", - HttpMethod.POST, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Cookie 434354454!", result.getBody()); - assertEquals("jsessionid=434354454", result.getHeaders().getFirst(SET_COOKIE)); - - result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/singleton/downstream_cookie", - HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Cookie null!", result.getBody()); - } - - @Test - public void ribbonCommandFactoryOverridden() { - assertTrue("ribbonCommandFactory not a HttpClientRibbonCommandFactory", - this.ribbonCommandFactory instanceof HttpClientRibbonCommandFactory); - } - - // Don't use @SpringBootApplication because we don't want to component scan - @Configuration - @EnableAutoConfiguration - @RestController - @EnableZuulProxy - @RibbonClients({ - @RibbonClient(name = "simple", configuration = ZuulProxyTestBase.SimpleRibbonClientConfiguration.class), - @RibbonClient(name = "another", configuration = ZuulProxyTestBase.AnotherRibbonClientConfiguration.class), - @RibbonClient(name = "singleton", configuration = SingletonRibbonClientConfiguration.class) }) - static class TestConfig extends ZuulProxyTestBase.AbstractZuulProxyApplication { - - @Autowired(required = false) - private Set zuulFallbackProviders = Collections.emptySet(); - - @RequestMapping(value = "/local/{id}", method = RequestMethod.PATCH) - public String patch(@PathVariable final String id, - @RequestBody final String body) { - return "Patched " + id + "!"; - } - - @RequestMapping(value = "/downstream_cookie", method = RequestMethod.POST) - public String setDownstreamCookie(HttpServletResponse response) { - response.addCookie(new Cookie("jsessionid", "434354454")); - return "Cookie 434354454!"; - } - - @RequestMapping(value = "/downstream_cookie", method = RequestMethod.GET) - public String readDownstreamCookie(HttpServletRequest request) { - final Cookie cookie = WebUtils.getCookie(request, "jsessionid"); - return "Cookie " + cookie + "!"; - } - - @Bean - public RibbonCommandFactory ribbonCommandFactory( - final SpringClientFactory clientFactory) { - return new HttpClientRibbonCommandFactory(clientFactory, new ZuulProperties(), - zuulFallbackProviders); - } - - @Bean - public ZuulProxyTestBase.MyErrorController myErrorController( - ErrorAttributes errorAttributes) { - return new ZuulProxyTestBase.MyErrorController(errorAttributes); - } - } - - // Load balancer with fixed server list and defined ribbon rest client - @Configuration - public static class SingletonRibbonClientConfiguration { - - @Value("${local.server.port}") - private int port; - - @Bean - public ServerList ribbonServerList() { - return new StaticServerList<>(new Server("localhost", this.port)); - } - - @Bean - public RibbonLoadBalancingHttpClient ribbonClient(IClientConfig config, - ILoadBalancer loadBalancer, RetryHandler retryHandler) { - final RibbonLoadBalancingHttpClient client = new RibbonLoadBalancingHttpClient(config, - new DefaultServerIntrospector()); - client.setLoadBalancer(loadBalancer); - client.setRetryHandler(retryHandler); - return client; - } - - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonRetryIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonRetryIntegrationTests.java deleted file mode 100644 index d7d737b3..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonRetryIntegrationTests.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.apache; - -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.zuul.filters.route.support.RibbonRetryIntegrationTestBase; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author Ryan Baxter - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = RibbonRetryIntegrationTestBase.RetryableTestConfig.class, - webEnvironment = RANDOM_PORT, - properties = { - "zuul.retryable: false", /* Disable retry by default, have each route enable it */ - "hystrix.command.default.execution.timeout.enabled: false", /* Disable hystrix so its timeout doesnt get in the way */ - "ribbon.ReadTimeout: 1000", /* Make sure ribbon will timeout before the thread is done sleeping */ - "zuul.routes.retryable.id: retryable", - "zuul.routes.retryable.path: /retryable/**", - "zuul.routes.retryable.retryable: true", - "retryable.ribbon.OkToRetryOnAllOperations: true", - "retryable.ribbon.MaxAutoRetries: 1", - "retryable.ribbon.MaxAutoRetriesNextServer: 1", - "zuul.routes.getretryable.id: getretryable", - "zuul.routes.getretryable.path: /getretryable/**", - "zuul.routes.getretryable.retryable: true", - "getretryable.ribbon.MaxAutoRetries: 1", - "getretryable.ribbon.MaxAutoRetriesNextServer: 1", - "zuul.routes.disableretry.id: disableretry", - "zuul.routes.disableretry.path: /disableretry/**", - "zuul.routes.disableretry.retryable: false", /* This will override the global */ - "disableretry.ribbon.MaxAutoRetries: 1", - "disableretry.ribbon.MaxAutoRetriesNextServer: 1", - "zuul.routes.globalretrydisabled: /globalretrydisabled/**", - "globalretrydisabled.ribbon.MaxAutoRetries: 1", - "globalretrydisabled.ribbon.MaxAutoRetriesNextServer: 1", - "retryable.ribbon.retryableStatusCodes: 404,403" -}) -@DirtiesContext -public class HttpClientRibbonRetryIntegrationTests extends RibbonRetryIntegrationTestBase { -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFactoryTest.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFactoryTest.java deleted file mode 100644 index 82536644..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFactoryTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.springframework.cloud.netflix.zuul.filters.route.okhttp; - -import java.util.HashSet; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpLoadBalancingClient; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; - -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; -import com.netflix.client.config.IClientConfigKey; -import com.netflix.config.ConfigurationManager; -import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -/** - * @author Ryan Baxter - */ -public class OkHttpRibbonCommandFactoryTest { - - SpringClientFactory springClientFactory; - ZuulProperties zuulProperties; - OkHttpRibbonCommandFactory commandFactory; - - @Before - public void setup() { - this.springClientFactory = mock(SpringClientFactory.class); - this.zuulProperties = new ZuulProperties(); - OkHttpLoadBalancingClient loadBalancingHttpClient = mock(OkHttpLoadBalancingClient.class); - IClientConfig clientConfig = new DefaultClientConfigImpl(); - doReturn(loadBalancingHttpClient).when(this.springClientFactory).getClient(anyString(), - eq(OkHttpLoadBalancingClient.class)); - doReturn(clientConfig).when(this.springClientFactory).getClientConfig(anyString()); - commandFactory = new OkHttpRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); - } - - @After - public void after() { - ConfigurationManager.getConfigInstance().clear(); - HystrixPropertiesFactory.reset(); - } - - @Test - public void testHystrixTimeoutValue() throws Exception { - RibbonCommandContext context = mock(RibbonCommandContext.class); - doReturn("service").when(context).getServiceId(); - OkHttpRibbonCommand ribbonCommand = this.commandFactory.create(context); - assertEquals(2000, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); - } - - @Test - public void testHystrixTimeoutValueSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", 50); - RibbonCommandContext context = mock(RibbonCommandContext.class); - doReturn("service").when(context).getServiceId(); - OkHttpRibbonCommand ribbonCommand = this.commandFactory.create(context); - assertEquals(50, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); - } - - @Test - public void testHystrixTimeoutValueCommandSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.service.execution.isolation.thread.timeoutInMilliseconds", 50); - RibbonCommandContext context = mock(RibbonCommandContext.class); - doReturn("service").when(context).getServiceId(); - OkHttpRibbonCommand ribbonCommand = this.commandFactory.create(context); - assertEquals(50, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); - } - - @Test - public void testHystrixTimeoutValueCommandAndDefaultSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", 30); - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.service.execution.isolation.thread.timeoutInMilliseconds", 50); - RibbonCommandContext context = mock(RibbonCommandContext.class); - doReturn("service").when(context).getServiceId(); - OkHttpRibbonCommand ribbonCommand = this.commandFactory.create(context); - assertEquals(50, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); - } - - @Test - public void testHystrixTimeoutValueRibbonTimeouts() throws Exception { - SpringClientFactory springClientFactory = mock(SpringClientFactory.class); - ZuulProperties zuulProperties = new ZuulProperties(); - OkHttpLoadBalancingClient loadBalancingHttpClient = mock(OkHttpLoadBalancingClient.class); - IClientConfig clientConfig = new DefaultClientConfigImpl(); - clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); - clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); - doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(OkHttpLoadBalancingClient.class)); - doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); - RibbonCommandContext context = mock(RibbonCommandContext.class); - doReturn("service").when(context).getServiceId(); - OkHttpRibbonCommand ribbonCommand = commandFactory.create(context); - assertEquals(600, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); - } - -} \ No newline at end of file diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFallbackTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFallbackTests.java deleted file mode 100644 index 00a4713c..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFallbackTests.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.okhttp; - -import com.netflix.zuul.context.RequestContext; - -import org.junit.Before; -import org.junit.runner.RunWith; - -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.zuul.filters.route.support.RibbonCommandFallbackTests; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * @author Ryan Baxter - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = RibbonCommandFallbackTests.TestConfig.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, value = { - "zuul.routes.simple: /simple/**", "zuul.routes.another: /another/twolevel/**", - "ribbon.ReadTimeout: 1" }) -@DirtiesContext -public class OkHttpRibbonCommandFallbackTests extends RibbonCommandFallbackTests { - @Before - public void init() { - RequestContext.getCurrentContext().clear(); - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandIntegrationTests.java deleted file mode 100644 index ea531470..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandIntegrationTests.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.okhttp; - -import java.util.Collections; -import java.util.Set; - -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.servlet.error.ErrorAttributes; -import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpLoadBalancingClient; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; -import org.springframework.cloud.netflix.zuul.filters.route.RibbonCommandFactory; -import org.springframework.cloud.netflix.zuul.filters.route.support.ZuulProxyTestBase; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.bind.annotation.RestController; -import com.netflix.client.DefaultLoadBalancerRetryHandler; -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = OkHttpRibbonCommandIntegrationTests.TestConfig.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { - "zuul.routes.other: /test/**=http://localhost:7777/local", - "zuul.routes.another: /another/twolevel/**", "zuul.routes.simple: /simple/**" }) -@DirtiesContext -public class OkHttpRibbonCommandIntegrationTests extends ZuulProxyTestBase { - - @Before - public void init() { - super.setTestRequestcontext(); - } - - @Test - public void patchOnSelfViaRibbonRoutingFilter() { - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/simple/local/1", HttpMethod.PATCH, - new HttpEntity<>("TestPatch"), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Patched 1!", result.getBody()); - } - - @Test - public void postOnSelfViaRibbonRoutingFilter() { - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/simple/local/1", HttpMethod.POST, - new HttpEntity<>("TestPost"), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted 1!", result.getBody()); - } - - @Test - public void deleteOnSelfViaRibbonRoutingFilter() { - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/simple/local/1", HttpMethod.DELETE, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Deleted 1!", result.getBody()); - } - - @Test - public void ribbonCommandFactoryOverridden() { - assertTrue("ribbonCommandFactory not a OkHttpRibbonCommandFactory", - this.ribbonCommandFactory instanceof OkHttpRibbonCommandFactory); - } - - // Don't use @SpringBootApplication because we don't want to component scan - @Configuration - @EnableAutoConfiguration - @RestController - @EnableZuulProxy - @RibbonClients({ - @RibbonClient(name = "simple", configuration = SimpleRibbonClientConfiguration.class), - @RibbonClient(name = "another", configuration = AnotherRibbonClientConfiguration.class) }) - static class TestConfig extends ZuulProxyTestBase.AbstractZuulProxyApplication { - - @Autowired(required = false) - private Set zuulFallbackProviders = Collections.emptySet(); - - @Bean - public RibbonCommandFactory ribbonCommandFactory( - final SpringClientFactory clientFactory) { - return new OkHttpRibbonCommandFactory(clientFactory, new ZuulProperties(), - zuulFallbackProviders); - } - - @Bean - public MyErrorController myErrorController(ErrorAttributes errorAttributes) { - return new MyErrorController(errorAttributes); - } - - @Bean - public IClientConfig config() { - return new DefaultClientConfigImpl(); - } - - @Bean - public OkHttpLoadBalancingClient okClient(IClientConfig config) { - final OkHttpLoadBalancingClient client = new OkHttpLoadBalancingClient(config, - new DefaultServerIntrospector()); - client.setLoadBalancer(new TestLoadBalancer<>()); - client.setRetryHandler(new DefaultLoadBalancerRetryHandler()); - return client; - } - } - - static class TestLoadBalancer extends ZoneAwareLoadBalancer { - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonRetryIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonRetryIntegrationTests.java deleted file mode 100644 index f56830f4..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonRetryIntegrationTests.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.okhttp; - -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.zuul.filters.route.support.RibbonRetryIntegrationTestBase; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * @author Ryan Baxter - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = RibbonRetryIntegrationTestBase.RetryableTestConfig.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, value = { - "zuul.retryable: false", /* Disable retry by default, have each route enable it */ - "ribbon.okhttp.enabled: true", - "hystrix.command.default.execution.timeout.enabled: false", /* Disable hystrix so its timeout doesnt get in the way */ - "ribbon.ReadTimeout: 1000", /* Make sure ribbon will timeout before the thread is done sleeping */ - "zuul.routes.retryable.id: retryable", - "zuul.routes.retryable.path: /retryable/**", - "zuul.routes.retryable.retryable: true", - "retryable.ribbon.OkToRetryOnAllOperations: true", - "retryable.ribbon.retryableStatusCodes: 404", - "retryable.ribbon.MaxAutoRetries: 1", - "retryable.ribbon.MaxAutoRetriesNextServer: 1", - "zuul.routes.getretryable.id: getretryable", - "zuul.routes.getretryable.path: /getretryable/**", - "zuul.routes.getretryable.retryable: true", - "getretryable.ribbon.MaxAutoRetries: 1", - "getretryable.ribbon.MaxAutoRetriesNextServer: 1", - "zuul.routes.disableretry.path: /disableretry/**", - "zuul.routes.disableretry.path: /disableretry/**", - "zuul.routes.disableretry.retryable: false", /* This will override the global */ - "disableretry.ribbon.MaxAutoRetries: 1", - "disableretry.ribbon.MaxAutoRetriesNextServer: 1", - "zuul.routes.globalretrydisabled: /globalretrydisabled/**", - "globalretrydisabled.ribbon.MaxAutoRetries: 1", - "globalretrydisabled.ribbon.MaxAutoRetriesNextServer: 1" -}) -@DirtiesContext -public class OkHttpRibbonRetryIntegrationTests extends RibbonRetryIntegrationTestBase { -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/restclient/RestClientRibbonCommandFallbackTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/restclient/RestClientRibbonCommandFallbackTests.java deleted file mode 100644 index ff7d3cd7..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/restclient/RestClientRibbonCommandFallbackTests.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.restclient; - -import com.netflix.zuul.context.RequestContext; - -import org.junit.Before; -import org.junit.runner.RunWith; - -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.zuul.filters.route.support.RibbonCommandFallbackTests; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * @author Ryan Baxter - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = RibbonCommandFallbackTests.TestConfig.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, value = { - "zuul.routes.simple: /simple/**", "zuul.routes.another: /another/twolevel/**", - "ribbon.ReadTimeout: 1" }) -@DirtiesContext -public class RestClientRibbonCommandFallbackTests extends RibbonCommandFallbackTests { - @Before - public void init() { - RequestContext.getCurrentContext().clear(); - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/restclient/RestClientRibbonCommandIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/restclient/RestClientRibbonCommandIntegrationTests.java deleted file mode 100644 index 320fc3d2..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/restclient/RestClientRibbonCommandIntegrationTests.java +++ /dev/null @@ -1,422 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.restclient; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.UUID; - -import javax.servlet.http.HttpServletRequest; - -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.servlet.error.ErrorAttributes; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.ribbon.StaticServerList; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; -import org.springframework.cloud.netflix.zuul.filters.route.RestClientRibbonCommand; -import org.springframework.cloud.netflix.zuul.filters.route.RestClientRibbonCommandFactory; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.zuul.filters.route.RibbonCommandFactory; -import org.springframework.cloud.netflix.zuul.filters.route.support.NoEncodingFormHttpMessageConverter; -import org.springframework.cloud.netflix.zuul.filters.route.support.ZuulProxyTestBase; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.StringHttpMessageConverter; -import org.springframework.mock.http.client.MockClientHttpResponse; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.bind.annotation.MatrixVariable; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import com.netflix.client.ClientException; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.niws.client.http.RestClient; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = RestClientRibbonCommandIntegrationTests.TestConfig.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { - "zuul.routes.other: /test/**=http://localhost:7777/local", - "zuul.routes.another: /another/twolevel/**", "zuul.routes.simple: /simple/**", - "zuul.routes.badhost: /badhost/**", "zuul.ignored-headers: X-Header", - "zuul.routes.rnd: /rnd/**", "rnd.ribbon.listOfServers: ${random.value}", - "zuul.remove-semicolon-content: false", "ribbon.restclient.enabled=true"}) -@DirtiesContext -public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { - - @Autowired - DiscoveryClientRouteLocator routeLocator; - - @Override - protected boolean supportsPatch() { - return false; - } - - @Override - protected boolean supportsDeleteWithBody() { - return false; - } - - @Test - public void simpleHostRouteWithTrailingSlash() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/"); - this.endpoint.reset(); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/self/trailing-slash", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("/trailing-slash", result.getBody()); - assertFalse(this.myErrorController.wasControllerUsed()); - } - - @Test - public void simpleHostRouteWithNonExistentUrl() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/"); - this.endpoint.reset(); - String uri = "/self/nonExistentUrl"; - this.myErrorController.setUriToMatch(uri); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + uri, HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode()); - assertFalse(this.myErrorController.wasControllerUsed()); - } - - @Test - public void simpleHostRouteIgnoredHeader() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/"); - this.endpoint.reset(); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/self/add-header", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertNull(result.getHeaders().get("X-Header")); - } - - @Test - @Ignore //FIXME: does spring 5.0 no longer send the X-Application-Context header? - public void simpleHostRouteDefaultIgnoredHeader() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/"); - this.endpoint.reset(); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/self/add-header", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - List headers = result.getHeaders().get("X-Application-Context"); - assertNotNull("header was null", headers); - assertEquals("[testclient:0]", headers.toString()); - } - - @Test - public void simpleHostRouteWithQuery() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/"); - this.endpoint.reset(); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/self/query?foo=bar", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("/query?foo=bar", result.getBody()); - } - - @Test - public void simpleHostRouteWithMatrix() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/"); - this.endpoint.reset(); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/self/matrix/my;q=2;p=1/more;x=2", - HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("my=1-2;more=2", result.getBody()); - } - - @Test - public void simpleHostRouteWithEncodedQuery() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/"); - this.endpoint.reset(); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/self/query?foo={foo}", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class, "weird#chars"); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("/query?foo=weird#chars", result.getBody()); - } - - @Test - public void simpleHostRouteWithColonParamNames() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/"); - this.endpoint.reset(); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/self/colonquery?foo:bar={foobar0}&foobar={foobar1}", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class, "baz", "bam"); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("/colonquery?foo:bar=baz&foobar=bam", result.getBody()); - } - - @Test - public void simpleHostRouteWithContentType() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/"); - this.endpoint.reset(); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/self/content-type", HttpMethod.POST, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("", result.getBody()); - } - - @Test - public void ribbonCommandForbidden() { - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/simple/throwexception/403", - HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode()); - } - - @Test - public void ribbonCommandServiceUnavailable() { - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/simple/throwexception/503", - HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.SERVICE_UNAVAILABLE, result.getStatusCode()); - } - - @Test - public void ribbonCommandBadHost() { - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/badhost/1", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); - // JSON response - assertThat(result.getBody(), containsString("\"status\":500")); - } - - @Test - public void ribbonCommandRandomHostFromConfig() { - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/rnd/1", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); - // JSON response - assertThat(result.getBody(), containsString("\"status\":500")); - } - - @Test - public void ribbonCommandFactoryOverridden() { - assertTrue("ribbonCommandFactory not a MyRibbonCommandFactory", - this.ribbonCommandFactory instanceof TestConfig.MyRibbonCommandFactory); - } - - @Override - @SuppressWarnings("deprecation") - @Test - public void javascriptEncodedFormParams() { - TestRestTemplate testRestTemplate = new TestRestTemplate(); - ArrayList> converters = new ArrayList<>(); - converters.addAll(Arrays.asList(new StringHttpMessageConverter(), - new NoEncodingFormHttpMessageConverter())); - testRestTemplate.getRestTemplate().setMessageConverters(converters); - - MultiValueMap map = new LinkedMultiValueMap<>(); - map.add("foo", "(bar)"); - ResponseEntity result = testRestTemplate.postForEntity( - "http://localhost:" + this.port + "/simple/local", map, String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted [(bar)] and Content-Length was: -1!", result.getBody()); - } - - @Test - public void routeLocatorOverridden() { - assertTrue("routeLocator not a MyRouteLocator", - this.routeLocator instanceof TestConfig.MyRouteLocator); - } - - // Don't use @SpringBootApplication because we don't want to component scan - @Configuration - @EnableAutoConfiguration - @RestController - @EnableZuulProxy - @RibbonClients({ - @RibbonClient(name = "badhost", configuration = TestConfig.BadHostRibbonClientConfiguration.class), - @RibbonClient(name = "simple", configuration = ZuulProxyTestBase.SimpleRibbonClientConfiguration.class), - @RibbonClient(name = "another", configuration = ZuulProxyTestBase.AnotherRibbonClientConfiguration.class) }) - static class TestConfig extends ZuulProxyTestBase.AbstractZuulProxyApplication { - - @Autowired(required = false) - private Set fallbackProviders = Collections.emptySet(); - - @RequestMapping("/trailing-slash") - public String trailingSlash(HttpServletRequest request) { - return request.getRequestURI(); - } - - @RequestMapping("/content-type") - public String contentType(HttpServletRequest request) { - String header = request.getHeader("Content-Type"); - return header == null ? "" : header; - } - - @RequestMapping("/add-header") - public ResponseEntity addHeader(HttpServletRequest request) { - HttpHeaders headers = new HttpHeaders(); - headers.set("X-Header", "FOO"); - ResponseEntity result = new ResponseEntity<>( - request.getRequestURI(), headers, HttpStatus.OK); - return result; - } - - @RequestMapping("/query") - public String query(HttpServletRequest request, @RequestParam String foo) { - return request.getRequestURI() + "?foo=" + foo; - } - - @RequestMapping("/colonquery") - public String colonQuery(HttpServletRequest request, @RequestParam(name = "foo:bar") String foobar0, @RequestParam(name = "foobar") String foobar1) { - return request.getRequestURI() + "?foo:bar=" + foobar0 + "&foobar=" + foobar1; - } - - @RequestMapping("/matrix/{name}/{another}") - public String matrix(@PathVariable("name") String name, - @MatrixVariable(value = "p", pathVar = "name") int p, - @MatrixVariable(value = "q", pathVar = "name") int q, - @PathVariable("another") String another, - @MatrixVariable(value = "x", pathVar = "another") int x) { - return name + "=" + p + "-" + q + ";" + another + "=" + x; - } - - @Bean - public RibbonCommandFactory ribbonCommandFactory( - SpringClientFactory clientFactory) { - return new MyRibbonCommandFactory(clientFactory, fallbackProviders); - } - - @Bean - public DiscoveryClientRouteLocator discoveryRouteLocator( - DiscoveryClient discoveryClient, - ZuulProperties zuulProperties) { - return new MyRouteLocator("/", discoveryClient, zuulProperties); - } - - @Bean - public MyErrorController myErrorController(ErrorAttributes errorAttributes) { - return new MyErrorController(errorAttributes); - } - - public static void main(String[] args) { - SpringApplication.run(TestConfig.class, args); - } - - public static class MyRibbonCommandFactory - extends RestClientRibbonCommandFactory { - - private SpringClientFactory clientFactory; - - public MyRibbonCommandFactory(SpringClientFactory clientFactory, - Set fallbackProviders) { - super(clientFactory, new ZuulProperties(), fallbackProviders); - this.clientFactory = clientFactory; - } - - @Override - @SuppressWarnings("deprecation") - public RestClientRibbonCommand create(RibbonCommandContext context) { - String uri = context.getUri(); - if (uri.startsWith("/throwexception/")) { - String code = uri.replace("/throwexception/", ""); - RestClient restClient = clientFactory - .getClient(context.getServiceId(), RestClient.class); - return new MyCommand(Integer.parseInt(code), context.getServiceId(), - restClient, context); - } - return super.create(context); - } - } - - static class MyCommand extends RestClientRibbonCommand { - - private int errorCode; - - public MyCommand(int errorCode, String commandKey, RestClient restClient, - RibbonCommandContext context) { - super(commandKey, restClient, context, new ZuulProperties()); - this.errorCode = errorCode; - } - - @Override - protected ClientHttpResponse run() throws Exception { - if (this.errorCode == 503) { - throw new ClientException(ClientException.ErrorType.SERVER_THROTTLED); - } - return new MockClientHttpResponse(new byte[0], - HttpStatus.valueOf(this.errorCode)); - } - } - - // Load balancer with fixed server list for "simple" pointing to bad host - @Configuration - static class BadHostRibbonClientConfiguration { - @Bean - public ServerList ribbonServerList() { - return new StaticServerList<>( - new Server(UUID.randomUUID().toString(), 4322)); - } - - } - - static class MyRouteLocator extends DiscoveryClientRouteLocator { - - public MyRouteLocator(String servletPath, DiscoveryClient discovery, - ZuulProperties properties) { - super(servletPath, discovery, properties); - } - } - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/NoEncodingFormHttpMessageConverter.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/NoEncodingFormHttpMessageConverter.java deleted file mode 100644 index 3f54c909..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/NoEncodingFormHttpMessageConverter.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2013-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.support; - -import java.io.IOException; -import java.util.Iterator; - -import org.springframework.http.HttpOutputMessage; -import org.springframework.http.MediaType; -import org.springframework.http.converter.FormHttpMessageConverter; -import org.springframework.http.converter.HttpMessageNotWritableException; -import org.springframework.util.MultiValueMap; -import org.springframework.util.StreamUtils; - -/** - * @author Jacques-Etienne Beaudet - */ -public class NoEncodingFormHttpMessageConverter extends FormHttpMessageConverter { - - @SuppressWarnings("unchecked") - @Override - public void write(MultiValueMap map, MediaType contentType, HttpOutputMessage outputMessage) - throws IOException, HttpMessageNotWritableException { - - MultiValueMap form = (MultiValueMap) map; - StringBuilder builder = new StringBuilder(); - for (Iterator nameIterator = form.keySet().iterator(); nameIterator.hasNext();) { - String name = nameIterator.next(); - for (Iterator valueIterator = form.get(name).iterator(); valueIterator.hasNext();) { - String value = valueIterator.next(); - builder.append(name); - if (value != null) { - builder.append('='); - builder.append(value); - if (valueIterator.hasNext()) { - builder.append('&'); - } - } - } - if (nameIterator.hasNext()) { - builder.append('&'); - } - } - final byte[] bytes = builder.toString().getBytes(FormHttpMessageConverter.DEFAULT_CHARSET); - outputMessage.getHeaders().setContentLength(bytes.length); - outputMessage.getHeaders().setContentType(MediaType.APPLICATION_FORM_URLENCODED); - - StreamUtils.copy(bytes, outputMessage.getBody()); - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandCauseFallbackPropagationTest.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandCauseFallbackPropagationTest.java deleted file mode 100644 index c4b2162f..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandCauseFallbackPropagationTest.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.support; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.UUID; - -import com.netflix.client.AbstractLoadBalancerAwareClient; -import com.netflix.client.ClientException; -import com.netflix.client.ClientRequest; -import com.netflix.client.IResponse; -import com.netflix.client.RequestSpecificRetryHandler; -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; -import com.netflix.client.http.HttpResponse; -import com.netflix.hystrix.HystrixCommandProperties; -import com.netflix.hystrix.exception.HystrixTimeoutException; - -import org.junit.Before; -import org.junit.Test; - -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.client.ClientHttpResponse; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -/** - * @author Dominik Mostek - */ -public class RibbonCommandCauseFallbackPropagationTest { - - private RibbonCommandContext context; - - @Before - public void setup() { - context = mock(RibbonCommandContext.class); - doReturn("fooRoute").when(context).getServiceId(); - } - - @Test - public void providerIsCalledInCaseOfException() throws Exception { - FallbackProvider provider = new TestFallbackProvider(getClientHttpResponse( - HttpStatus.INTERNAL_SERVER_ERROR)); - RuntimeException exception = new RuntimeException("Failed!"); - TestRibbonCommand testCommand = new TestRibbonCommand(new TestClient(exception), - provider, context); - - ClientHttpResponse response = testCommand.execute(); - - assertThat(response).isNotNull(); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - } - - @Test - public void causeIsProvidedForNewInterface() throws Exception { - TestFallbackProvider provider = TestFallbackProvider - .withResponse(HttpStatus.NOT_FOUND); - RuntimeException exception = new RuntimeException("Failed!"); - TestRibbonCommand testCommand = new TestRibbonCommand(new TestClient(exception), - provider, context); - - ClientHttpResponse response = testCommand.execute(); - - assertThat(response).isNotNull(); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - Throwable cause = provider.getCause(); - assertThat(cause.getClass()).isEqualTo(exception.getClass()); - assertThat(cause.getMessage()).isEqualTo(exception.getMessage()); - } - - @Test - public void executionExceptionIsUsedInsteadWhenFailedExceptionIsNull() - throws Exception { - TestFallbackProvider provider = TestFallbackProvider - .withResponse(HttpStatus.BAD_GATEWAY); - final RuntimeException exception = new RuntimeException("Failed!"); - TestRibbonCommand testCommand = new TestRibbonCommand(new TestClient(exception), - provider, context) { - @Override - public Throwable getFailedExecutionException() { - return null; - } - - @Override - public Throwable getExecutionException() { - return exception; - } - }; - - ClientHttpResponse response = testCommand.execute(); - - assertThat(response).isNotNull(); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_GATEWAY); - } - - @Test - public void timeoutExceptionIsPropagated() throws Exception { - TestFallbackProvider provider = TestFallbackProvider - .withResponse(HttpStatus.CONFLICT); - RuntimeException exception = new RuntimeException("Failed!"); - TestRibbonCommand testCommand = new TestRibbonCommand(new TestClient(exception), - provider, 1, context) { - @Override - protected ClientRequest createRequest() throws Exception { - Thread.sleep(5); - return super.createRequest(); - } - }; - - ClientHttpResponse response = testCommand.execute(); - - assertThat(response).isNotNull(); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); - assertThat(provider.getCause()).isNotNull(); - assertThat(provider.getCause().getClass()) - .isEqualTo(HystrixTimeoutException.class); - } - - public static class TestRibbonCommand extends - AbstractRibbonCommand, ClientRequest, HttpResponse> { - - public TestRibbonCommand( - AbstractLoadBalancerAwareClient client, - FallbackProvider fallbackProvider, RibbonCommandContext context) { - this(client, new ZuulProperties(), fallbackProvider, context); - } - - public TestRibbonCommand( - AbstractLoadBalancerAwareClient client, - ZuulProperties zuulProperties, FallbackProvider fallbackProvider, RibbonCommandContext context) { - super("testCommand" + UUID.randomUUID(), client, context, zuulProperties, - fallbackProvider); - } - - public TestRibbonCommand( - AbstractLoadBalancerAwareClient client, - FallbackProvider fallbackProvider, int timeout, RibbonCommandContext context) { - // different name is used because of properties caching - super(getSetter("testCommand" + UUID.randomUUID(), new ZuulProperties(), new DefaultClientConfigImpl()) - .andCommandPropertiesDefaults(defauts(timeout)), client, context, - fallbackProvider, null); - } - - private static HystrixCommandProperties.Setter defauts(final int timeout) { - return HystrixCommandProperties.Setter().withExecutionTimeoutEnabled(true) - .withExecutionIsolationStrategy( - HystrixCommandProperties.ExecutionIsolationStrategy.THREAD) - .withExecutionTimeoutInMilliseconds(timeout); - } - - @Override - protected ClientRequest createRequest() throws Exception { - return null; - } - } - - @SuppressWarnings("rawtypes") - public static class TestClient extends AbstractLoadBalancerAwareClient { - - private final RuntimeException exception; - - public TestClient(RuntimeException exception) { - super(null); - this.exception = exception; - } - - @Override - public IResponse executeWithLoadBalancer(final ClientRequest request, - final IClientConfig requestConfig) throws ClientException { - throw exception; - } - - @Override - public RequestSpecificRetryHandler getRequestSpecificRetryHandler( - final ClientRequest clientRequest, final IClientConfig iClientConfig) { - return null; - } - - @Override - public IResponse execute(final ClientRequest clientRequest, - final IClientConfig iClientConfig) throws Exception { - return null; - } - } - - public static class TestFallbackProvider implements FallbackProvider { - - private final ClientHttpResponse response; - private Throwable cause; - - public TestFallbackProvider(final ClientHttpResponse response) { - this.response = response; - } - - @Override - public ClientHttpResponse fallbackResponse(String route, final Throwable cause) { - this.cause = cause; - return response; - } - - @Override - public String getRoute() { - return "test-route"; - } - - public Throwable getCause() { - return cause; - } - - public static TestFallbackProvider withResponse(final HttpStatus status) { - return new TestFallbackProvider(getClientHttpResponse(status)); - } - } - - private static ClientHttpResponse getClientHttpResponse(final HttpStatus status) { - return new ClientHttpResponse() { - @Override - public HttpStatus getStatusCode() throws IOException { - return status; - } - - @Override - public int getRawStatusCode() throws IOException { - return getStatusCode().value(); - } - - @Override - public String getStatusText() throws IOException { - return getStatusCode().getReasonPhrase(); - } - - @Override - public void close() { - } - - @Override - public InputStream getBody() throws IOException { - return new ByteArrayInputStream("test".getBytes()); - } - - @Override - public HttpHeaders getHeaders() { - return new HttpHeaders(); - } - }; - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandFallbackTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandFallbackTests.java deleted file mode 100644 index be260a99..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandFallbackTests.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.support; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collections; -import java.util.Set; - -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.boot.web.servlet.error.ErrorAttributes; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; -import org.springframework.cloud.netflix.zuul.filters.route.RibbonCommandFactory; -import org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.web.bind.annotation.RestController; - -import static org.junit.Assert.assertEquals; - -/** - * @author Ryan Baxter - */ -public abstract class RibbonCommandFallbackTests { - - @LocalServerPort - protected int port; - - @Test - public void fallback() { - String uri = "/simple/slow"; - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + uri, HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("fallback", result.getBody()); - } - - @Test - public void defaultFallback() { - String uri = "/another/twolevel/slow"; - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + uri, HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("default fallback", result.getBody()); - } - - // Don't use @SpringBootApplication because we don't want to component scan - @Configuration - @EnableAutoConfiguration - @RestController - @EnableZuulProxy - @RibbonClients({ - @RibbonClient(name = "simple", configuration = ZuulProxyTestBase.SimpleRibbonClientConfiguration.class), - @RibbonClient(name = "another", configuration = ZuulProxyTestBase.AnotherRibbonClientConfiguration.class)}) - public static class TestConfig extends ZuulProxyTestBase.AbstractZuulProxyApplication { - - @Autowired(required = false) - private Set zuulFallbackProviders = Collections.emptySet(); - - - @Bean - public RibbonCommandFactory ribbonCommandFactory( - final SpringClientFactory clientFactory) { - return new HttpClientRibbonCommandFactory(clientFactory, new ZuulProperties(), - zuulFallbackProviders); - } - - @Bean - public ZuulProxyTestBase.MyErrorController myErrorController( - ErrorAttributes errorAttributes) { - return new ZuulProxyTestBase.MyErrorController(errorAttributes); - } - - @Bean - public FallbackProvider defaultFallbackProvider() { - return new DefaultFallbackProvider(); - } - } - - public static class DefaultFallbackProvider implements FallbackProvider { - - @Override - public String getRoute() { - return "*"; - } - - @Override - public ClientHttpResponse fallbackResponse(final String route, Throwable cause) { - return new ClientHttpResponse() { - @Override - public HttpStatus getStatusCode() throws IOException { - return HttpStatus.OK; - } - - @Override - public int getRawStatusCode() throws IOException { - if(route.equals("another")) { - return 200; - } - return 500; - } - - @Override - public String getStatusText() throws IOException { - return null; - } - - @Override - public void close() { - - } - - @Override - public InputStream getBody() throws IOException { - return new ByteArrayInputStream("default fallback".getBytes()); - } - - @Override - public HttpHeaders getHeaders() { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.TEXT_HTML); - return headers; - } - }; - } - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandHystrixThreadPoolKeyTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandHystrixThreadPoolKeyTests.java deleted file mode 100644 index 2003c5ae..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandHystrixThreadPoolKeyTests.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright 2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.filters.route.support; - -import com.netflix.client.AbstractLoadBalancerAwareClient; -import com.netflix.client.ClientRequest; -import com.netflix.client.http.HttpResponse; -import com.netflix.hystrix.HystrixCommandProperties; -import com.netflix.hystrix.strategy.HystrixPlugins; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Yongsung Yoon - */ -public class RibbonCommandHystrixThreadPoolKeyTests { - - private ZuulProperties zuulProperties; - - @Before - public void setUp() throws Exception { - zuulProperties = new ZuulProperties(); - } - - @After - public void tearDown() throws Exception { - HystrixPlugins.reset(); - } - - @Test - public void testDefaultHystrixThreadPoolKey() throws Exception { - zuulProperties.setRibbonIsolationStrategy( - HystrixCommandProperties.ExecutionIsolationStrategy.THREAD); - - TestRibbonCommand ribbonCommand1 = new TestRibbonCommand("testCommand1", - zuulProperties); - TestRibbonCommand ribbonCommand2 = new TestRibbonCommand("testCommand2", - zuulProperties); - - // CommandGroupKey should be used as ThreadPoolKey as default. - assertThat(ribbonCommand1.getThreadPoolKey().name()) - .isEqualTo(ribbonCommand1.getCommandGroup().name()); - assertThat(ribbonCommand2.getThreadPoolKey().name()) - .isEqualTo(ribbonCommand2.getCommandGroup().name()); - } - - @Test - public void testUseSeparateThreadPools() throws Exception { - zuulProperties.setRibbonIsolationStrategy( - HystrixCommandProperties.ExecutionIsolationStrategy.THREAD); - zuulProperties.getThreadPool().setUseSeparateThreadPools(true); - - TestRibbonCommand ribbonCommand1 = new TestRibbonCommand("testCommand1", - zuulProperties); - TestRibbonCommand ribbonCommand2 = new TestRibbonCommand("testCommand2", - zuulProperties); - - assertThat(ribbonCommand1.getThreadPoolKey().name()).isEqualTo("testCommand1"); - assertThat(ribbonCommand2.getThreadPoolKey().name()).isEqualTo("testCommand2"); - } - - @Test - public void testThreadPoolKeyPrefix() throws Exception { - final String prefix = "zuulgw-"; - - zuulProperties.setRibbonIsolationStrategy( - HystrixCommandProperties.ExecutionIsolationStrategy.THREAD); - zuulProperties.getThreadPool().setUseSeparateThreadPools(true); - zuulProperties.getThreadPool().setThreadPoolKeyPrefix(prefix); - - TestRibbonCommand ribbonCommand1 = new TestRibbonCommand("testCommand1", - zuulProperties); - TestRibbonCommand ribbonCommand2 = new TestRibbonCommand("testCommand2", - zuulProperties); - - assertThat(ribbonCommand1.getThreadPoolKey().name()) - .isEqualTo(prefix + "testCommand1"); - assertThat(ribbonCommand2.getThreadPoolKey().name()) - .isEqualTo(prefix + "testCommand2"); - } - - @Test - public void testNoSideEffectOnSemaphoreIsolation() throws Exception { - final String prefix = "zuulgw-"; - - zuulProperties.setRibbonIsolationStrategy( - HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE); - zuulProperties.getThreadPool().setUseSeparateThreadPools(true); - zuulProperties.getThreadPool().setThreadPoolKeyPrefix(prefix); - - TestRibbonCommand ribbonCommand1 = new TestRibbonCommand("testCommand1", - zuulProperties); - TestRibbonCommand ribbonCommand2 = new TestRibbonCommand("testCommand2", - zuulProperties); - - // There should be no side effect on semaphore isolation - assertThat(ribbonCommand1.getThreadPoolKey().name()) - .isEqualTo(ribbonCommand1.getCommandGroup().name()); - assertThat(ribbonCommand2.getThreadPoolKey().name()) - .isEqualTo(ribbonCommand2.getCommandGroup().name()); - } - - public static class TestRibbonCommand extends - AbstractRibbonCommand, ClientRequest, HttpResponse> { - public TestRibbonCommand(String commandKey, ZuulProperties zuulProperties) { - super(commandKey, null, null, zuulProperties); - } - - @Override - protected ClientRequest createRequest() throws Exception { - return null; - } - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonRetryIntegrationTestBase.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonRetryIntegrationTestBase.java deleted file mode 100644 index a0d1eea6..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonRetryIntegrationTestBase.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.support; - -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.zuul.context.RequestContext; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Before; -import org.junit.Test; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicyFactory; -import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser; -import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancedRetryPolicy; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancedRetryPolicyFactory; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerContext; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.ribbon.StaticServerList; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.bind.annotation.RestController; - -import static org.junit.Assert.assertEquals; - -/** - * @author Ryan Baxter - */ -public abstract class RibbonRetryIntegrationTestBase { - - private final Log LOG = LogFactory.getLog(RibbonRetryIntegrationTestBase.class); - - @Value("${local.server.port}") - protected int port; - - @Before - public void setup() { - RequestContext.getCurrentContext().clear(); - String uri = "/resetError"; - new TestRestTemplate().exchange("http://localhost:" + this.port + uri, - HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - } - - @Test - public void retryable() { - String uri = "/retryable/everyothererror"; - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + uri, HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - } - - @Test - public void retryableFourOFour() { - String uri = "/retryable/404everyothererror"; - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + uri, HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - } - - @Test - public void postRetryOK() { - String uri = "/retryable/posteveryothererror"; - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + uri, HttpMethod.POST, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - } - - @Test - public void getRetryable() { - String uri = "/getretryable/everyothererror"; - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + uri, HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - } - - @Test - public void postNotRetryable() { - String uri = "/getretryable/posteveryothererror"; - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + uri, HttpMethod.POST, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); - } - - @Test - public void disableRetry() { - String uri = "/disableretry/everyothererror"; - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + uri, HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - LOG.info("Response Body: " + result.getBody()); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); - } - - @Test - public void globalRetryDisabled() { - String uri = "/globalretrydisabled/everyothererror"; - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + uri, HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - LOG.info("Response Body: " + result.getBody()); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); - } - - // Don't use @SpringBootApplication because we don't want to component scan - @Configuration - @EnableAutoConfiguration - @RestController - @EnableZuulProxy - @RibbonClients({ - @RibbonClient(name = "retryable", configuration = RibbonClientConfiguration.class), - @RibbonClient(name = "disableretry", configuration = RibbonClientConfiguration.class), - @RibbonClient(name = "globalretrydisabled", configuration = RibbonClientConfiguration.class), - @RibbonClient(name = "getretryable", configuration = RibbonClientConfiguration.class) }) - public static class RetryableTestConfig { - - private final Log LOG = LogFactory.getLog(RetryableTestConfig.class); - - private boolean error = true; - - @RequestMapping("/resetError") - public void resetError() { - error = true; - } - - @RequestMapping("/everyothererror") - public ResponseEntity timeout() { - boolean shouldError = error; - error = !error; - try { - if (shouldError) { - Thread.sleep(80000); - } - } - catch (InterruptedException e) { - LOG.info(e); - Thread.currentThread().interrupt(); - } - - return new ResponseEntity("no error", HttpStatus.OK); - } - - @RequestMapping(path = "/posteveryothererror", method = RequestMethod.POST) - public ResponseEntity postTimeout() { - return timeout(); - } - - @RequestMapping("/404everyothererror") - @ResponseStatus(HttpStatus.NOT_FOUND) - public ResponseEntity fourOFourError() { - boolean shouldError = error; - error = !error; - if (shouldError) { - return new ResponseEntity("not found", HttpStatus.NOT_FOUND); - } - return new ResponseEntity("no error", HttpStatus.OK); - } - - } - - @Configuration - public static class RibbonClientConfiguration { - - @Value("${local.server.port}") - private int port; - - @Bean - public ServerList ribbonServerList() { - return new StaticServerList<>(new Server("localhost", this.port)); - } - } - - @Configuration - public static class FourOFourRetryableRibbonConfiguration - extends RibbonClientConfiguration { - - @Bean - public LoadBalancedRetryPolicyFactory loadBalancedRetryPolicyFactory( - SpringClientFactory factory) { - return new MyRibbonRetryPolicyFactory(factory); - } - - public static class MyRibbonRetryPolicyFactory - extends RibbonLoadBalancedRetryPolicyFactory { - - private SpringClientFactory factory; - - public MyRibbonRetryPolicyFactory(SpringClientFactory clientFactory) { - super(clientFactory); - this.factory = clientFactory; - } - - @Override - public LoadBalancedRetryPolicy create(String serviceId, - ServiceInstanceChooser loadBalanceChooser) { - RibbonLoadBalancerContext lbContext = this.factory - .getLoadBalancerContext(serviceId); - return new MyLoadBalancedRetryPolicy(serviceId, lbContext, - loadBalanceChooser); - } - - class MyLoadBalancedRetryPolicy extends RibbonLoadBalancedRetryPolicy { - - public MyLoadBalancedRetryPolicy(String serviceId, - RibbonLoadBalancerContext context, - ServiceInstanceChooser loadBalanceChooser) { - super(serviceId, context, loadBalanceChooser); - } - - @Override - public boolean retryableStatusCode(int statusCode) { - if (statusCode == HttpStatus.NOT_FOUND.value()) { - return true; - } - return super.retryableStatusCode(statusCode); - } - } - } - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/ZuulProxyTestBase.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/ZuulProxyTestBase.java deleted file mode 100644 index 96ae2988..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/ZuulProxyTestBase.java +++ /dev/null @@ -1,566 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.filters.route.support; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.web.ErrorProperties; -import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.servlet.error.ErrorAttributes; -import org.springframework.cloud.netflix.ribbon.StaticServerList; -import org.springframework.cloud.netflix.zuul.RoutesEndpoint; -import org.springframework.cloud.netflix.zuul.filters.Route; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; -import org.springframework.cloud.netflix.zuul.filters.route.RibbonCommandFactory; -import org.springframework.cloud.netflix.zuul.filters.route.support.RibbonRetryIntegrationTestBase.RetryableTestConfig; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.http.converter.FormHttpMessageConverter; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.StringHttpMessageConverter; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; - -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assume.assumeThat; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; - -/** - * @author Spencer Gibb - * @author Ryan Baxter - */ -public abstract class ZuulProxyTestBase { - - @Value("${local.server.port}") - protected int port; - - @Autowired - protected DiscoveryClientRouteLocator routes; - - @Autowired - protected RoutesEndpoint endpoint; - - @Autowired - protected RibbonCommandFactory ribbonCommandFactory; - - @Autowired - protected MyErrorController myErrorController; - - @Before - public void cleanup() { - this.myErrorController.clear(); - } - - @Before - public void setTestRequestcontext() { - RequestContext.testSetCurrentContext(null); - RequestContext.getCurrentContext().unset(); - } - - @After - public void clear() { - RequestContext.getCurrentContext().clear(); - } - - /** - * used to disable patch tests if client doesn't support it - */ - protected boolean supportsPatch() { - return true; - } - - /** - * used to switch delete tests with a boyd if client doesn't support it - */ - protected boolean supportsDeleteWithBody() { - return true; - } - - protected String getRoute(String path) { - for (Route route : this.routes.getRoutes()) { - if (path.equals(route.getFullPath())) { - return route.getLocation(); - } - } - return null; - } - - @Test - public void bindRouteUsingPhysicalRoute() { - assertEquals("http://localhost:7777/local", getRoute("/test/**")); - } - - @Test - public void bindRouteUsingOnlyPath() { - assertEquals("simple", getRoute("/simple/**")); - } - - @Test - public void getOnSelfViaRibbonRoutingFilter() { - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/simple/local/1", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Gotten 1!", result.getBody()); - } - - @Test - public void deleteOnSelfViaSimpleHostRoutingFilter() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/local"); - this.endpoint.reset(); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/self/1", HttpMethod.DELETE, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Deleted 1!", result.getBody()); - } - - @Test - public void stripPrefixFalseAppendsPath() { - this.routes.addRoute(new ZuulProperties.ZuulRoute("strip", "/strip/**", "strip", - "http://localhost:" + this.port + "/local", false, false, null)); - this.endpoint.reset(); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/strip", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - // Prefix not stripped to it goes to /local/strip - assertEquals("Gotten strip!", result.getBody()); - } - - @Test - public void testNotFoundFromApp() { - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/simple/local/notfound", - HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode()); - } - - @Test - public void testNotFoundOnProxy() { - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/myinvalidpath", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode()); - } - - @Test - public void getSecondLevel() { - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/another/twolevel/local/1", - HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Gotten 1!", result.getBody()); - } - - @Test - public void ribbonRouteWithSpace() { - String uri = "/simple/spa ce"; - this.myErrorController.setUriToMatch(uri); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + uri, HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Hello space", result.getBody()); - assertFalse(myErrorController.wasControllerUsed()); - } - - @Test - public void ribbonDeleteWithBody() { - this.endpoint.reset(); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/simple/deletewithbody", - HttpMethod.DELETE, new HttpEntity<>("deleterequestbody"), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - if (supportsDeleteWithBody()) { - assertEquals("Deleted deleterequestbody", result.getBody()); - } - else { - assertEquals("Deleted null", result.getBody()); - } - } - - @Test - public void ribbonRouteWithNonExistentUri() { - String uri = "/simple/nonExistent"; - this.myErrorController.setUriToMatch(uri); - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + uri, HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode()); - assertFalse(myErrorController.wasControllerUsed()); - } - - @Test - public void simpleHostRouteWithSpace() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port); - this.endpoint.reset(); - - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/self/spa ce", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Hello space", result.getBody()); - } - - @Test - public void simpleHostRouteWithOriginalQueryString() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port); - this.endpoint.reset(); - - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port - + "/self/qstring?original=value1&original=value2", - HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Received {original=[value1, value2]}", result.getBody()); - } - - @Test - public void simpleHostRouteWithOverriddenQString() { - this.routes.addRoute("/self/**", "http://localhost:" + this.port); - this.endpoint.reset(); - - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port - + "/self/qstring?override=true&different=key", - HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Received {key=[overridden]}", result.getBody()); - } - - @Test - public void patchOnSelfViaSimpleHostRoutingFilter() { - assumeThat(supportsPatch(), is(true)); - - this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/local"); - this.endpoint.reset(); - - ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/self/1", HttpMethod.PATCH, - new HttpEntity<>("TestPatch"), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Patched 1!", result.getBody()); - } - - @SuppressWarnings("deprecation") - @Test - public void javascriptEncodedFormParams() { - TestRestTemplate testRestTemplate = new TestRestTemplate(); - ArrayList> converters = new ArrayList<>(); - converters.addAll(Arrays.asList(new StringHttpMessageConverter(), - new NoEncodingFormHttpMessageConverter())); - testRestTemplate.getRestTemplate().setMessageConverters(converters); - - MultiValueMap map = new LinkedMultiValueMap<>(); - map.add("foo", "(bar)"); - ResponseEntity result = testRestTemplate.postForEntity( - "http://localhost:" + this.port + "/simple/local", map, String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted [(bar)] and Content-Length was: 13!", result.getBody()); - } - - public static abstract class AbstractZuulProxyApplication - extends DelegatingWebMvcConfiguration { - - private final Log LOG = LogFactory.getLog(RetryableTestConfig.class); - - @RequestMapping(value = "/local/{id}", method = RequestMethod.PATCH) - public String patch(@PathVariable final String id, - @RequestBody final String body) { - return "Patched " + id + "!"; - } - - @RequestMapping("/testing123") - public String testing123() { - throw new RuntimeException("myerror"); - } - - @RequestMapping("/local") - public String local() { - return "Hello local"; - } - - @RequestMapping(value = "/local", method = RequestMethod.POST) - public String postWithFormParam(HttpServletRequest request, - @RequestBody MultiValueMap body) { - return "Posted " + body.get("foo") + " and Content-Length was: " - + request.getContentLength() + "!"; - } - - @RequestMapping(value = "/deletewithbody", method = RequestMethod.DELETE) - public String deleteWithBody(@RequestBody(required = false) String body) { - return "Deleted " + body; - } - - @RequestMapping(value = "/local/{id}", method = RequestMethod.DELETE) - public String delete(@PathVariable String id) { - return "Deleted " + id + "!"; - } - - @RequestMapping(value = "/local/{id}", method = RequestMethod.GET) - public ResponseEntity get(@PathVariable String id) { - if ("notfound".equalsIgnoreCase(id)) { - return ResponseEntity.notFound().build(); - } - return ResponseEntity.ok("Gotten " + id + "!"); - } - - @RequestMapping(value = "/local/{id}", method = RequestMethod.POST) - public String post(@PathVariable String id, @RequestBody String body) { - return "Posted " + id + "!"; - } - - @RequestMapping(value = "/qstring") - public String qstring(@RequestParam MultiValueMap params) { - return "Received " + params.toString(); - } - - @RequestMapping("/") - public String home() { - return "Hello world"; - } - - @RequestMapping("/spa ce") - public String space() { - return "Hello space"; - } - - @RequestMapping("/slow") - public String slow() { - try { - Thread.sleep(80000); - } - catch (InterruptedException e) { - LOG.info(e); - Thread.currentThread().interrupt(); - } - return "slow"; - } - - @Bean - public FallbackProvider fallbackProvider() { - return new ZuulFallbackProvider(); - } - - @Bean - public ZuulFilter sampleFilter() { - return new ZuulFilter() { - @Override - public String filterType() { - return PRE_TYPE; - } - - @Override - public boolean shouldFilter() { - return true; - } - - @Override - public Object run() { - if (RequestContext.getCurrentContext().getRequest().getParameterMap() - .containsKey("override")) { - Map> overridden = new HashMap<>(); - overridden.put("key", Arrays.asList("overridden")); - RequestContext.getCurrentContext() - .setRequestQueryParams(overridden); - } - return null; - } - - @Override - public int filterOrder() { - return 0; - } - }; - - } - - @Override - public RequestMappingHandlerMapping requestMappingHandlerMapping() { - RequestMappingHandlerMapping mapping = super.requestMappingHandlerMapping(); - mapping.setRemoveSemicolonContent(false); - return mapping; - } - - } - - public static class ZuulFallbackProvider implements FallbackProvider { - - @Override - public String getRoute() { - return "simple"; - } - - @Override - public ClientHttpResponse fallbackResponse(String route, Throwable cause) { - return new ClientHttpResponse() { - @Override - public HttpStatus getStatusCode() throws IOException { - return HttpStatus.OK; - } - - @Override - public int getRawStatusCode() throws IOException { - return 200; - } - - @Override - public String getStatusText() throws IOException { - return null; - } - - @Override - public void close() { - - } - - @Override - public InputStream getBody() throws IOException { - return new ByteArrayInputStream("fallback".getBytes()); - } - - @Override - public HttpHeaders getHeaders() { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.TEXT_HTML); - return headers; - } - }; - } - } - - @Configuration - public class FormEncodedMessageConverterConfiguration - extends WebMvcConfigurerAdapter { - - @Override - public void configureMessageConverters(List> converters) { - FormHttpMessageConverter converter = new FormHttpMessageConverter(); - MediaType mediaType = new MediaType("application", "x-www-form-urlencoded", - Charset.forName("UTF-8")); - converter.setSupportedMediaTypes(Arrays.asList(mediaType)); - converters.add(converter); - super.configureMessageConverters(converters); - } - } - - // Load balancer with fixed server list for "simple" pointing to localhost - @Configuration - public static class SimpleRibbonClientConfiguration { - - @Value("${local.server.port}") - private int port; - - @Bean - public ServerList ribbonServerList() { - return new StaticServerList<>(new Server("localhost", this.port)); - } - - } - - @Configuration - public static class AnotherRibbonClientConfiguration { - - @Value("${local.server.port}") - private int port; - - @Bean - public ServerList ribbonServerList() { - return new StaticServerList<>(new Server("localhost", this.port)); - } - - } - - public static class MyErrorController extends BasicErrorController { - ThreadLocal uriToMatch = new ThreadLocal<>(); - - AtomicBoolean controllerUsed = new AtomicBoolean(); - - public MyErrorController(ErrorAttributes errorAttributes) { - super(errorAttributes, new ErrorProperties()); - } - - @Override - public ResponseEntity> error(HttpServletRequest request) { - String errorUri = (String) request - .getAttribute("javax.servlet.error.request_uri"); - - if (errorUri != null && errorUri.equals(this.uriToMatch.get())) { - controllerUsed.set(true); - } - this.uriToMatch.remove(); - return super.error(request); - } - - public void setUriToMatch(String uri) { - this.uriToMatch.set(uri); - } - - public boolean wasControllerUsed() { - return this.controllerUsed.get(); - } - - public void clear() { - this.controllerUsed.set(false); - } - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/DefaultCounterFactoryTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/DefaultCounterFactoryTests.java deleted file mode 100644 index 95e74f04..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/DefaultCounterFactoryTests.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2013-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.metrics; - - -import com.netflix.zuul.monitoring.CounterFactory; - -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.MeterRegistry; -import org.junit.Test; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class DefaultCounterFactoryTests { - - private static final String NAME = "my-super-metric-name"; - - @Test - public void shouldIncrement() throws Exception { - MeterRegistry meterRegistry = mock(MeterRegistry.class); - CounterFactory factory = new DefaultCounterFactory(meterRegistry); - - Counter counter = mock(Counter.class); - when(meterRegistry.counter(NAME)).thenReturn(counter); - - factory.increment(NAME); - - verify(counter).increment(); - } -} \ No newline at end of file diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/ZuulEmptyMetricsApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/ZuulEmptyMetricsApplicationTests.java deleted file mode 100644 index e8c9b9d1..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/ZuulEmptyMetricsApplicationTests.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.metrics; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.boot.autoconfigure.web.ServerProperties; -import org.springframework.cloud.netflix.zuul.ZuulServerAutoConfiguration; -import org.springframework.cloud.netflix.zuul.ZuulServerMarkerConfiguration; -import org.springframework.cloud.test.ClassPathExclusions; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.netflix.zuul.monitoring.CounterFactory; -import com.netflix.zuul.monitoring.TracerFactory; - -import static org.junit.Assert.assertEquals; - -@ClassPathExclusions({ "spring-boot-starter-actuator-*.jar", - "spring-boot-actuator-*.jar" }) -public class ZuulEmptyMetricsApplicationTests { - - private AnnotationConfigApplicationContext context; - - @Before - public void setUp() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - context.register(ZuulEmptyMetricsApplicationTestsConfiguration.class, - ZuulServerMarkerConfiguration.class, ZuulServerAutoConfiguration.class); - context.refresh(); - - this.context = context; - } - - @After - public void tearDown() throws Exception { - if (this.context != null) { - this.context.close(); - } - } - - @Test - public void shouldSetupDefaultCounterFactoryIfCounterServiceIsPresent() - throws Exception { - CounterFactory factory = this.context.getBean(CounterFactory.class); - - assertEquals(EmptyCounterFactory.class, factory.getClass()); - } - - @Test - public void shouldSetupEmptyTracerFactory() throws Exception { - TracerFactory factory = this.context.getBean(TracerFactory.class); - - assertEquals(EmptyTracerFactory.class, factory.getClass()); - } - - @Configuration - static class ZuulEmptyMetricsApplicationTestsConfiguration { - - @Bean - ServerProperties serverProperties() { - return new ServerProperties(); - } - - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/ZuulMetricsApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/ZuulMetricsApplicationTests.java deleted file mode 100644 index 4d178035..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/ZuulMetricsApplicationTests.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.metrics; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.zuul.EnableZuulServer; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; - -import com.netflix.zuul.exception.ZuulException; -import com.netflix.zuul.monitoring.CounterFactory; -import com.netflix.zuul.monitoring.TracerFactory; - -import static org.junit.Assert.assertEquals; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -import io.micrometer.core.instrument.MeterRegistry; -import io.micrometer.core.instrument.MockClock; -import io.micrometer.core.instrument.simple.SimpleConfig; -import io.micrometer.core.instrument.simple.SimpleMeterRegistry; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = { - ZuulMetricsApplicationTests.ZuulMetricsApplicationTestsConfiguration.class, - ZuulMetricsApplicationTests.ZuulConfig.class }, webEnvironment = RANDOM_PORT) -@DirtiesContext -public class ZuulMetricsApplicationTests { - - @Autowired - private CounterFactory counterFactory; - @Autowired - private TracerFactory tracerFactory; - @Autowired - private MeterRegistry meterRegistry; - - @Test - public void shouldSetupDefaultCounterFactoryIfCounterServiceIsPresent() - throws Exception { - assertEquals(DefaultCounterFactory.class, counterFactory.getClass()); - } - - @Test - public void shouldSetupEmptyTracerFactory() throws Exception { - assertEquals(EmptyTracerFactory.class, tracerFactory.getClass()); - } - - @Test - @SuppressWarnings("all") - public void shouldIncrementCounters() throws Exception { - new ZuulException("any", 500, "cause"); - new ZuulException("any", 500, "cause"); - - Double count = meterRegistry.counter("ZUUL::EXCEPTION:cause:500").count(); - assertEquals(count.longValue(), 2L); - - new ZuulException("any", 404, "cause2"); - new ZuulException("any", 404, "cause2"); - new ZuulException("any", 404, "cause2"); - - count = meterRegistry.counter("ZUUL::EXCEPTION:cause2:404").count(); - assertEquals(count.longValue(), 3L); - } - - // Don't use @SpringBootApplication because we don't want to component scan - @Configuration - @EnableAutoConfiguration - @EnableZuulServer - static class ZuulConfig { - - } - - @Configuration - static class ZuulMetricsApplicationTestsConfiguration { - - @Bean - public MeterRegistry meterRegistry() { - return new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock()); - } - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/AdhocTestSuite.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/AdhocTestSuite.java deleted file mode 100644 index 359b7863..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/AdhocTestSuite.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2012-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.test; - -import org.junit.Ignore; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -/** - * A test suite for probing weird ordering problems in the zuul tests. - * - * @author Spencer Gibb - */ -@RunWith(Suite.class) -@SuiteClasses({ - org.springframework.cloud.netflix.zuul.ZuulServerAutoConfigurationTests.class, - org.springframework.cloud.netflix.zuul.RoutesEndpointTests.class, - org.springframework.cloud.netflix.zuul.FormZuulServletProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.metrics.DefaultCounterFactoryTests.class, - org.springframework.cloud.netflix.zuul.metrics.ZuulEmptyMetricsApplicationTests.class, - org.springframework.cloud.netflix.zuul.metrics.ZuulMetricsApplicationTests.class, - org.springframework.cloud.netflix.zuul.web.ZuulHandlerMappingTests.class, - org.springframework.cloud.netflix.zuul.ZuulProxyAutoConfigurationTests.class, - org.springframework.cloud.netflix.zuul.RetryableZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.ServletPathZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.FormZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.filters.CompositeRouteLocatorTests.class, - org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFallbackTests.class, - org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFactoryTest.class, - org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonRetryIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.LazyLoadOfZuulConfigurationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.EagerLoadOfZuulConfigurationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.route.SendForwardFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.route.RestClientRibbonCommandTests.class, - org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilterLoadBalancerKeyIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommandFallbackTests.class, - org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonRetryIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommandIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommandFactoryTest.class, - org.springframework.cloud.netflix.zuul.filters.route.restclient.RestClientRibbonCommandIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.restclient.RestClientRibbonCommandFallbackTests.class, - org.springframework.cloud.netflix.zuul.filters.route.support.RibbonCommandCauseFallbackPropagationTest.class, - org.springframework.cloud.netflix.zuul.filters.route.support.RibbonCommandHystrixThreadPoolKeyTests.class, - org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelperTests.class, - org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocatorTests.class, - org.springframework.cloud.netflix.zuul.filters.ZuulPropertiesTests.class, - org.springframework.cloud.netflix.zuul.filters.CustomHostRoutingFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.discovery.PatternServiceRouteMapperIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.discovery.PatternServiceRouteMapperTests.class, - org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocatorTests.class, - org.springframework.cloud.netflix.zuul.filters.pre.PreDecorationFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.pre.FormBodyWrapperFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.post.LocationRewriteFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilterIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.post.LocationRewriteFilterIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilterTests.class, - org.springframework.cloud.netflix.zuul.RoutesEndpointDetailsTests.class, - org.springframework.cloud.netflix.zuul.ZuulProxyConfigurationTests.class, - org.springframework.cloud.netflix.zuul.ZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.SimpleZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.ZuulFilterInitializerTests.class, - org.springframework.cloud.netflix.zuul.RoutesEndpointIntegrationTests.class, - org.springframework.cloud.netflix.zuul.test.ZuulApacheHttpClientConfigurationTests.class, - org.springframework.cloud.netflix.zuul.test.ZuulOkHttpClientConfigurationTests.class, - org.springframework.cloud.netflix.zuul.ContextPathZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.SimpleZuulServerApplicationTests.class, - org.springframework.cloud.netflix.zuul.FiltersEndpointTests.class, - -}) -@Ignore -public class AdhocTestSuite { - -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/AdhocZuulTestSuite.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/AdhocZuulTestSuite.java deleted file mode 100644 index 76a38093..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/AdhocZuulTestSuite.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.test; - -import org.junit.Ignore; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -/** - * A test suite for probing weird ordering problems in the tests. - * - * @author Dave Syer - */ -@RunWith(Suite.class) -@SuiteClasses({ -org.springframework.cloud.netflix.zuul.ContextPathZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.filters.CompositeRouteLocatorTests.class, - org.springframework.cloud.netflix.zuul.filters.CustomHostRoutingFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocatorTests.class, - org.springframework.cloud.netflix.zuul.filters.discovery.PatternServiceRouteMapperIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.discovery.PatternServiceRouteMapperTests.class, - org.springframework.cloud.netflix.zuul.filters.post.LocationRewriteFilterIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.post.LocationRewriteFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilterIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.pre.FormBodyWrapperFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.pre.PreDecorationFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelperTests.class, - org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFactoryTest.class, - org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFallbackTests.class, - org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonRetryIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.EagerLoadOfZuulConfigurationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.LazyLoadOfZuulConfigurationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommandFactoryTest.class, - org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommandFallbackTests.class, - org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommandIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonRetryIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.restclient.RestClientRibbonCommandFallbackTests.class, - org.springframework.cloud.netflix.zuul.filters.route.restclient.RestClientRibbonCommandIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.RestClientRibbonCommandTests.class, - org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.route.SendForwardFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.route.support.RibbonCommandCauseFallbackPropagationTest.class, - org.springframework.cloud.netflix.zuul.filters.route.support.RibbonCommandHystrixThreadPoolKeyTests.class, - org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocatorTests.class, - org.springframework.cloud.netflix.zuul.filters.ZuulPropertiesTests.class, - org.springframework.cloud.netflix.zuul.FiltersEndpointTests.class, - org.springframework.cloud.netflix.zuul.FormZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.FormZuulServletProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.metrics.DefaultCounterFactoryTests.class, - org.springframework.cloud.netflix.zuul.metrics.ZuulEmptyMetricsApplicationTests.class, - org.springframework.cloud.netflix.zuul.metrics.ZuulMetricsApplicationTests.class, - org.springframework.cloud.netflix.zuul.RetryableZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.RoutesEndpointDetailsTests.class, - org.springframework.cloud.netflix.zuul.RoutesEndpointIntegrationTests.class, - org.springframework.cloud.netflix.zuul.RoutesEndpointTests.class, - org.springframework.cloud.netflix.zuul.ServletPathZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.SimpleZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.SimpleZuulServerApplicationTests.class, - org.springframework.cloud.netflix.zuul.test.ZuulApacheHttpClientConfigurationTests.class, - org.springframework.cloud.netflix.zuul.test.ZuulOkHttpClientConfigurationTests.class, - org.springframework.cloud.netflix.zuul.web.ZuulHandlerMappingTests.class, - org.springframework.cloud.netflix.zuul.ZuulFilterInitializerTests.class, - org.springframework.cloud.netflix.zuul.ZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.ZuulProxyAutoConfigurationTests.class, - org.springframework.cloud.netflix.zuul.ZuulProxyConfigurationTests.class, - org.springframework.cloud.netflix.zuul.ZuulServerAutoConfigurationTests.class, -}) -@Ignore -public class AdhocZuulTestSuite { - -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/TestAutoConfiguration.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/TestAutoConfiguration.java deleted file mode 100644 index a048e970..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/TestAutoConfiguration.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.test; - -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -import org.springframework.cloud.client.discovery.noop.NoopDiscoveryClientAutoConfiguration; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.core.Ordered; -import org.springframework.core.annotation.Order; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.web.firewall.StrictHttpFirewall; - -/** - * @author Spencer Gibb - */ -@Configuration -@Import({NoopDiscoveryClientAutoConfiguration.class}) -@AutoConfigureBefore(SecurityAutoConfiguration.class) -public class TestAutoConfiguration { - - @Configuration - @Order(Ordered.HIGHEST_PRECEDENCE) - protected static class TestSecurityConfiguration extends WebSecurityConfigurerAdapter { - - - TestSecurityConfiguration() { - super(true); - } - - @Override - public void configure(WebSecurity web) throws Exception { - StrictHttpFirewall httpFirewall = new StrictHttpFirewall(); - httpFirewall.setAllowSemicolon(true); - web.httpFirewall(httpFirewall); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - // super.configure(http); - http.antMatcher("/proxy-username") - .httpBasic() - .and() - .authorizeRequests().antMatchers("/**").permitAll(); - } - - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/ZuulApacheHttpClientConfigurationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/ZuulApacheHttpClientConfigurationTests.java deleted file mode 100644 index 9f477ebe..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/ZuulApacheHttpClientConfigurationTests.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.test; - -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.ArrayList; - -import org.apache.http.Header; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.message.BasicHeader; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.MockingDetails; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory; -import org.springframework.cloud.commons.httpclient.DefaultApacheHttpClientFactory; -import org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter; -import org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommand; -import org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.ReflectionUtils; - -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockingDetails; - -/** - * @author Ryan Baxter - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(properties = { - "ribbon.eureka.enabled = false"}) -@DirtiesContext -public class ZuulApacheHttpClientConfigurationTests { - - @Autowired - SimpleHostRoutingFilter simpleHostRoutingFilter; - - @Autowired - HttpClientRibbonCommandFactory httpClientRibbonCommandFactory; - - - @Test - public void testHttpClientSimpleHostRoutingFilter() { - CloseableHttpClient httpClient = getField(simpleHostRoutingFilter, "httpClient"); - MockingDetails httpClientDetails = mockingDetails(httpClient); - assertTrue(httpClientDetails.isMock()); - } - - @Test - public void testRibbonLoadBalancingHttpClient() { - RibbonCommandContext context = new RibbonCommandContext("foo"," GET", "http://localhost", - false, new LinkedMultiValueMap<>(), new LinkedMultiValueMap<>(), - null, new ArrayList<>(), 0l); - HttpClientRibbonCommand command = httpClientRibbonCommandFactory.create(context); - RibbonLoadBalancingHttpClient ribbonClient = command.getClient(); - CloseableHttpClient httpClient = getField(ribbonClient, "delegate"); - MockingDetails httpClientDetails = mockingDetails(httpClient); - assertTrue(httpClientDetails.isMock()); - } - - @SuppressWarnings("unchecked") - protected T getField(Object target, String name) { - Field field = ReflectionUtils.findField(target.getClass(), name); - ReflectionUtils.makeAccessible(field); - Object value = ReflectionUtils.getField(field, target); - return (T)value; - } - - @SpringBootConfiguration - @EnableAutoConfiguration - @EnableZuulProxy - static class TestConfig { - - static class MyApacheHttpClientFactory extends DefaultApacheHttpClientFactory { - public MyApacheHttpClientFactory(HttpClientBuilder builder) { - super(builder); - } - - @Override - public HttpClientBuilder createBuilder() { - CloseableHttpClient client = mock(CloseableHttpClient.class); - CloseableHttpResponse response = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); - doReturn(200).when(statusLine).getStatusCode(); - Mockito.doReturn(statusLine).when(response).getStatusLine(); - Header[] headers = new BasicHeader[0]; - doReturn(headers).when(response).getAllHeaders(); - try { - Mockito.doReturn(response).when(client).execute(any(HttpUriRequest.class)); - } catch (IOException e) { - e.printStackTrace(); - } - HttpClientBuilder builder = mock(HttpClientBuilder.class); - Mockito.doReturn(client).when(builder).build(); - return builder; - } - } - - @Bean - public ApacheHttpClientFactory apacheHttpClientFactory(HttpClientBuilder builder) { - return new MyApacheHttpClientFactory(builder); - } - } - -} - diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/ZuulOkHttpClientConfigurationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/ZuulOkHttpClientConfigurationTests.java deleted file mode 100644 index 0f973d50..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/ZuulOkHttpClientConfigurationTests.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.netflix.zuul.test; - -import java.lang.reflect.Field; -import java.util.ArrayList; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.MockingDetails; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory; -import org.springframework.cloud.commons.httpclient.OkHttpClientFactory; -import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpLoadBalancingClient; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommand; -import org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommandFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.ReflectionUtils; - -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockingDetails; - -import okhttp3.OkHttpClient; - -/** - * @author Ryan Baxter - */ -@RunWith(SpringRunner.class) -@SpringBootTest(properties = { - "spring.cloud.httpclientfactories.ok.enabled: true", - "ribbon.eureka.enabled = false", "ribbon.okhttp.enabled: true", - "ribbon.httpclient.enabled: false" }) -@DirtiesContext -public class ZuulOkHttpClientConfigurationTests { - - @Autowired - OkHttpClientFactory okHttpClientFactory; - - @Autowired - OkHttpClientConnectionPoolFactory connectionPoolFactory; - - @Autowired - OkHttpRibbonCommandFactory okHttpRibbonCommandFactory; - - @Test - public void testOkHttpLoadBalancingHttpClient() { - RibbonCommandContext context = new RibbonCommandContext("foo", " GET", - "http://localhost", false, new LinkedMultiValueMap<>(), - new LinkedMultiValueMap<>(), null, - new ArrayList<>(), 0l); - OkHttpRibbonCommand command = okHttpRibbonCommandFactory.create(context); - OkHttpLoadBalancingClient ribbonClient = command.getClient(); - OkHttpClient httpClient = getField(ribbonClient, "delegate"); - MockingDetails httpClientDetails = mockingDetails(httpClient); - assertTrue(httpClientDetails.isMock()); - } - - protected T getField(Object target, String name) { - Field field = ReflectionUtils.findField(target.getClass(), name); - ReflectionUtils.makeAccessible(field); - Object value = ReflectionUtils.getField(field, target); - return (T) value; - } - - @SpringBootConfiguration - @EnableAutoConfiguration - @EnableZuulProxy - static class TestConfig { - @Bean - public OkHttpClient client() { - return mock(OkHttpClient.class); - } - - } -} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/web/ZuulHandlerMappingTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/web/ZuulHandlerMappingTests.java deleted file mode 100644 index fc1a02c9..00000000 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/web/ZuulHandlerMappingTests.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 2013-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.springframework.cloud.netflix.zuul.web; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.springframework.boot.web.servlet.error.ErrorController; -import org.springframework.cloud.netflix.zuul.filters.Route; -import org.springframework.cloud.netflix.zuul.filters.RouteLocator; -import org.springframework.mock.web.MockHttpServletRequest; - -import com.netflix.zuul.context.RequestContext; - -/** - * @author Dave Syer - * @author Biju Kunjummen - */ -public class ZuulHandlerMappingTests { - - private ZuulHandlerMapping mapping; - - private RouteLocator locator = Mockito.mock(RouteLocator.class); - - private ErrorController errors = Mockito.mock(ErrorController.class); - - private MockHttpServletRequest request = new MockHttpServletRequest(); - - @Before - public void init() { - RequestContext.getCurrentContext().clear(); - this.mapping = new ZuulHandlerMapping(this.locator, new ZuulController()); - this.mapping.setErrorController(this.errors); - Mockito.when(this.errors.getErrorPath()).thenReturn("/error"); - } - - @Test - public void mappedPath() throws Exception { - Mockito.when(this.locator.getRoutes()).thenReturn(Collections - .singletonList(new Route("foo", "/foo/**", "foo", "", null, null))); - this.request.setServletPath("/foo/"); - this.mapping.setDirty(true); - assertThat(this.mapping.getHandler(this.request)).isNotNull(); - } - - @Test - public void defaultPath() throws Exception { - Mockito.when(this.locator.getRoutes()).thenReturn(Collections - .singletonList(new Route("default", "/**", "foo", "", null, null))); - ; - this.request.setServletPath("/"); - this.mapping.setDirty(true); - assertThat(this.mapping.getHandler(this.request)).isNotNull(); - } - - @Test - public void errorPath() throws Exception { - Mockito.when(this.locator.getRoutes()).thenReturn(Collections - .singletonList(new Route("default", "/**", "foo", "", null, null))); - this.request.setServletPath("/error"); - this.mapping.setDirty(true); - assertThat(this.mapping.getHandler(this.request)).isNull(); - } - - @Test - public void ignoredPathsShouldNotReturnAHandler() throws Exception { - assertThat(mappingWithIgnoredPathsAndRoutes(Arrays.asList("/p1/**"), - new Route("p1", "/p1/**", "p1", "", null, null)) - .getHandler(requestForAPath("/p1"))).isNull(); - - assertThat(mappingWithIgnoredPathsAndRoutes(Arrays.asList("/p1/**/p3/"), - new Route("p1", "/p1/**/p3", "p1", "", null, null)) - .getHandler(requestForAPath("/p1/p2/p3"))).isNull(); - - assertThat(mappingWithIgnoredPathsAndRoutes(Arrays.asList("/p1/**/p3/**"), - new Route("p1", "/p1/**/p3", "p1", "", null, null)) - .getHandler(requestForAPath("/p1/p2/p3"))).isNull(); - - assertThat(mappingWithIgnoredPathsAndRoutes(Arrays.asList("/p1/**/p4/"), - new Route("p1", "/p1/**/p4/", "p1", "", null, null)) - .getHandler(requestForAPath("/p1/p2/p3/p4"))).isNull(); - } - - private ZuulHandlerMapping mappingWithIgnoredPathsAndRoutes(List ignoredPaths, Route route) { - RouteLocator routeLocator = Mockito.mock(RouteLocator.class); - Mockito.when(routeLocator.getIgnoredPaths()) - .thenReturn(ignoredPaths); - Mockito.when(routeLocator.getRoutes()).thenReturn(Collections.singletonList(route)); - ZuulHandlerMapping zuulHandlerMapping = new ZuulHandlerMapping(routeLocator, new ZuulController()); - return zuulHandlerMapping; - } - - private MockHttpServletRequest requestForAPath(String path) { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setServletPath(path); - return request; - } - -} diff --git a/spring-cloud-netflix-zuul/src/test/resources/META-INF/spring.factories b/spring-cloud-netflix-zuul/src/test/resources/META-INF/spring.factories deleted file mode 100644 index 9819adfe..00000000 --- a/spring-cloud-netflix-zuul/src/test/resources/META-INF/spring.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -org.springframework.cloud.netflix.zuul.test.TestAutoConfiguration diff --git a/spring-cloud-netflix-zuul/src/test/resources/application.yml b/spring-cloud-netflix-zuul/src/test/resources/application.yml deleted file mode 100644 index de191f82..00000000 --- a/spring-cloud-netflix-zuul/src/test/resources/application.yml +++ /dev/null @@ -1,26 +0,0 @@ -server: - port: 9999 - compression: - enabled: true - min-response-size: 1024 - mime-types: application/xml,application/json -spring: - application: - name: testclient -#zuul: - #prefix: /api - #strip-prefix: true -# routes: -# test: -# serviceId: testclient -# path: /testing123/** -# stores: -# url: http://localhost:8081 -# path: /stores/** -hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000 -management: - context-path: /admin -endpoints.default.web.enabled: true -logging: - level: - org.springframework.cloud.netflix.zuul: DEBUG \ No newline at end of file diff --git a/spring-cloud-netflix-core/pom.xml b/spring-cloud-openfeign-core/pom.xml similarity index 96% rename from spring-cloud-netflix-core/pom.xml rename to spring-cloud-openfeign-core/pom.xml index f21c9f6d..13373977 100644 --- a/spring-cloud-netflix-core/pom.xml +++ b/spring-cloud-openfeign-core/pom.xml @@ -4,14 +4,14 @@ 4.0.0 org.springframework.cloud - spring-cloud-netflix + spring-cloud-openfeign 2.0.0.BUILD-SNAPSHOT .. - spring-cloud-netflix-core + spring-cloud-openfeign-core jar - Spring Cloud Netflix Core - Spring Cloud Netflix Core + Spring Cloud OpenFeign Core + Spring Cloud OpenFeign Core ${basedir}/.. diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/AnnotatedParameterProcessor.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/AnnotatedParameterProcessor.java similarity index 97% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/AnnotatedParameterProcessor.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/AnnotatedParameterProcessor.java index 7ec99d35..e8537fd4 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/AnnotatedParameterProcessor.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/AnnotatedParameterProcessor.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import java.lang.annotation.Annotation; import java.lang.reflect.Method; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/DefaultFeignLoggerFactory.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/DefaultFeignLoggerFactory.java similarity index 95% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/DefaultFeignLoggerFactory.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/DefaultFeignLoggerFactory.java index d7ca25d1..4950a1ab 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/DefaultFeignLoggerFactory.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/DefaultFeignLoggerFactory.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import feign.Logger; import feign.slf4j.Slf4jLogger; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/DefaultTargeter.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/DefaultTargeter.java similarity index 94% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/DefaultTargeter.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/DefaultTargeter.java index a51a0793..67666cec 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/DefaultTargeter.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/DefaultTargeter.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import feign.Feign; import feign.Target; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/EnableFeignClients.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/EnableFeignClients.java similarity index 98% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/EnableFeignClients.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/EnableFeignClients.java index 32029a73..ee81a204 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/EnableFeignClients.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/EnableFeignClients.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignAutoConfiguration.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignAutoConfiguration.java similarity index 98% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignAutoConfiguration.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignAutoConfiguration.java index 75cc6c57..1caeee00 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignAutoConfiguration.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignAutoConfiguration.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import java.util.ArrayList; import java.util.List; @@ -38,7 +38,7 @@ import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionMa import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory; import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory; import org.springframework.cloud.commons.httpclient.OkHttpClientFactory; -import org.springframework.cloud.netflix.feign.support.FeignHttpClientProperties; +import org.springframework.cloud.openfeign.support.FeignHttpClientProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClient.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClient.java similarity index 98% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClient.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClient.java index 0a40573c..59d58bb1 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClient.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClient.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClientFactoryBean.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientFactoryBean.java similarity index 98% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClientFactoryBean.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientFactoryBean.java index d2c5a947..feb6d816 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClientFactoryBean.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientFactoryBean.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import java.util.Map; import java.util.Objects; @@ -24,7 +24,7 @@ import org.springframework.beans.BeansException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient; +import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.util.Assert; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClientProperties.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientProperties.java similarity index 98% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClientProperties.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientProperties.java index 38a20af0..8a4687f2 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClientProperties.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientProperties.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import feign.Logger; import feign.RequestInterceptor; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClientSpecification.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientSpecification.java similarity index 97% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClientSpecification.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientSpecification.java index fdde09df..5e34f56d 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClientSpecification.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientSpecification.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import org.springframework.cloud.context.named.NamedContextFactory; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClientsConfiguration.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsConfiguration.java similarity index 91% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClientsConfiguration.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsConfiguration.java index a2feabdb..090bf3f4 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClientsConfiguration.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsConfiguration.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import java.util.ArrayList; import java.util.List; @@ -26,10 +26,10 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; -import org.springframework.cloud.netflix.feign.support.ResponseEntityDecoder; -import org.springframework.cloud.netflix.feign.support.SpringDecoder; -import org.springframework.cloud.netflix.feign.support.SpringEncoder; -import org.springframework.cloud.netflix.feign.support.SpringMvcContract; +import org.springframework.cloud.openfeign.support.ResponseEntityDecoder; +import org.springframework.cloud.openfeign.support.SpringDecoder; +import org.springframework.cloud.openfeign.support.SpringEncoder; +import org.springframework.cloud.openfeign.support.SpringMvcContract; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClientsRegistrar.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsRegistrar.java similarity index 99% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClientsRegistrar.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsRegistrar.java index 58cfd9a9..9427d431 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClientsRegistrar.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsRegistrar.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import java.io.IOException; import java.net.MalformedURLException; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignContext.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignContext.java similarity index 95% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignContext.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignContext.java index 1c9f0cd9..fd484e77 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignContext.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignContext.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import org.springframework.cloud.context.named.NamedContextFactory; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignFormatterRegistrar.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignFormatterRegistrar.java similarity index 95% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignFormatterRegistrar.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignFormatterRegistrar.java index 0a6f0e93..8408b778 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignFormatterRegistrar.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignFormatterRegistrar.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import org.springframework.format.FormatterRegistrar; import org.springframework.format.support.FormattingConversionService; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignLoggerFactory.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignLoggerFactory.java similarity index 95% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignLoggerFactory.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignLoggerFactory.java index 9440fdf0..93588134 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignLoggerFactory.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignLoggerFactory.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import feign.Logger; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/HystrixTargeter.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/HystrixTargeter.java similarity index 98% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/HystrixTargeter.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/HystrixTargeter.java index cfbe3659..d9925043 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/HystrixTargeter.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/HystrixTargeter.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import org.springframework.util.Assert; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/Targeter.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/Targeter.java similarity index 94% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/Targeter.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/Targeter.java index 3ebd9a86..fe74ebcc 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/Targeter.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/Targeter.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import feign.Feign; import feign.Target; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/annotation/PathVariableParameterProcessor.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/annotation/PathVariableParameterProcessor.java similarity index 94% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/annotation/PathVariableParameterProcessor.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/annotation/PathVariableParameterProcessor.java index c1dba1c9..edf6e985 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/annotation/PathVariableParameterProcessor.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/annotation/PathVariableParameterProcessor.java @@ -14,14 +14,14 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.annotation; +package org.springframework.cloud.openfeign.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Collection; import java.util.Map; -import org.springframework.cloud.netflix.feign.AnnotatedParameterProcessor; +import org.springframework.cloud.openfeign.AnnotatedParameterProcessor; import org.springframework.web.bind.annotation.PathVariable; import feign.MethodMetadata; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/annotation/RequestHeaderParameterProcessor.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/annotation/RequestHeaderParameterProcessor.java similarity index 94% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/annotation/RequestHeaderParameterProcessor.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/annotation/RequestHeaderParameterProcessor.java index 111bf00f..da8f0de9 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/annotation/RequestHeaderParameterProcessor.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/annotation/RequestHeaderParameterProcessor.java @@ -14,14 +14,14 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.annotation; +package org.springframework.cloud.openfeign.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Collection; import java.util.Map; -import org.springframework.cloud.netflix.feign.AnnotatedParameterProcessor; +import org.springframework.cloud.openfeign.AnnotatedParameterProcessor; import org.springframework.web.bind.annotation.RequestHeader; import feign.MethodMetadata; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/annotation/RequestParamParameterProcessor.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/annotation/RequestParamParameterProcessor.java similarity index 94% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/annotation/RequestParamParameterProcessor.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/annotation/RequestParamParameterProcessor.java index ba996ac2..2fbe6807 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/annotation/RequestParamParameterProcessor.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/annotation/RequestParamParameterProcessor.java @@ -14,14 +14,14 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.annotation; +package org.springframework.cloud.openfeign.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Collection; import java.util.Map; -import org.springframework.cloud.netflix.feign.AnnotatedParameterProcessor; +import org.springframework.cloud.openfeign.AnnotatedParameterProcessor; import org.springframework.web.bind.annotation.RequestParam; import static feign.Util.checkState; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/BaseRequestInterceptor.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/BaseRequestInterceptor.java similarity index 96% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/BaseRequestInterceptor.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/BaseRequestInterceptor.java index f7d49ff5..fefcc99b 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/BaseRequestInterceptor.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/BaseRequestInterceptor.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.encoding; +package org.springframework.cloud.openfeign.encoding; import feign.RequestInterceptor; import feign.RequestTemplate; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/FeignAcceptGzipEncodingAutoConfiguration.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/FeignAcceptGzipEncodingAutoConfiguration.java similarity index 93% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/FeignAcceptGzipEncodingAutoConfiguration.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/FeignAcceptGzipEncodingAutoConfiguration.java index 3f5388eb..1c581c59 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/FeignAcceptGzipEncodingAutoConfiguration.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/FeignAcceptGzipEncodingAutoConfiguration.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.encoding; +package org.springframework.cloud.openfeign.encoding; import feign.Feign; import feign.httpclient.ApacheHttpClient; @@ -24,7 +24,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.netflix.feign.FeignAutoConfiguration; +import org.springframework.cloud.openfeign.FeignAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/FeignAcceptGzipEncodingInterceptor.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/FeignAcceptGzipEncodingInterceptor.java similarity index 96% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/FeignAcceptGzipEncodingInterceptor.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/FeignAcceptGzipEncodingInterceptor.java index 868837a5..9753e76a 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/FeignAcceptGzipEncodingInterceptor.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/FeignAcceptGzipEncodingInterceptor.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.encoding; +package org.springframework.cloud.openfeign.encoding; import feign.RequestTemplate; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/FeignClientEncodingProperties.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/FeignClientEncodingProperties.java similarity index 97% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/FeignClientEncodingProperties.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/FeignClientEncodingProperties.java index 7d3733cc..d8307b9f 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/FeignClientEncodingProperties.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/FeignClientEncodingProperties.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.encoding; +package org.springframework.cloud.openfeign.encoding; import org.springframework.boot.context.properties.ConfigurationProperties; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/FeignContentGzipEncodingAutoConfiguration.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/FeignContentGzipEncodingAutoConfiguration.java similarity index 93% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/FeignContentGzipEncodingAutoConfiguration.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/FeignContentGzipEncodingAutoConfiguration.java index da778518..f0d973fd 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/FeignContentGzipEncodingAutoConfiguration.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/FeignContentGzipEncodingAutoConfiguration.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.encoding; +package org.springframework.cloud.openfeign.encoding; import feign.Feign; import feign.httpclient.ApacheHttpClient; @@ -24,7 +24,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.netflix.feign.FeignAutoConfiguration; +import org.springframework.cloud.openfeign.FeignAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/FeignContentGzipEncodingInterceptor.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/FeignContentGzipEncodingInterceptor.java similarity index 98% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/FeignContentGzipEncodingInterceptor.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/FeignContentGzipEncodingInterceptor.java index fae897b9..02ef1e45 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/FeignContentGzipEncodingInterceptor.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/FeignContentGzipEncodingInterceptor.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.encoding; +package org.springframework.cloud.openfeign.encoding; import feign.RequestTemplate; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/HttpEncoding.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/HttpEncoding.java similarity index 95% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/HttpEncoding.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/HttpEncoding.java index 378b50a7..58ec0a00 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/encoding/HttpEncoding.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/encoding/HttpEncoding.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.encoding; +package org.springframework.cloud.openfeign.encoding; /** * Lists all constants used by Feign encoders. diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/CachingSpringLoadBalancerFactory.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/CachingSpringLoadBalancerFactory.java similarity index 98% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/CachingSpringLoadBalancerFactory.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/CachingSpringLoadBalancerFactory.java index 3bb051ce..975c8718 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/CachingSpringLoadBalancerFactory.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/CachingSpringLoadBalancerFactory.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.ribbon; +package org.springframework.cloud.openfeign.ribbon; import java.util.Map; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/DefaultFeignLoadBalancedConfiguration.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/DefaultFeignLoadBalancedConfiguration.java similarity index 95% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/DefaultFeignLoadBalancedConfiguration.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/DefaultFeignLoadBalancedConfiguration.java index 1098ea0b..68b52485 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/DefaultFeignLoadBalancedConfiguration.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/DefaultFeignLoadBalancedConfiguration.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign.ribbon; +package org.springframework.cloud.openfeign.ribbon; import feign.Client; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/FeignLoadBalancer.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/FeignLoadBalancer.java similarity index 99% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/FeignLoadBalancer.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/FeignLoadBalancer.java index 4fab93f1..e8aa2286 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/FeignLoadBalancer.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/FeignLoadBalancer.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.ribbon; +package org.springframework.cloud.openfeign.ribbon; import feign.Client; import feign.Request; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/FeignRetryPolicy.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/FeignRetryPolicy.java similarity index 98% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/FeignRetryPolicy.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/FeignRetryPolicy.java index f78d52fa..56dfa7e9 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/FeignRetryPolicy.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/FeignRetryPolicy.java @@ -16,7 +16,7 @@ * */ -package org.springframework.cloud.netflix.feign.ribbon; +package org.springframework.cloud.openfeign.ribbon; import java.net.URI; import java.util.HashMap; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/FeignRibbonClientAutoConfiguration.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientAutoConfiguration.java similarity index 94% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/FeignRibbonClientAutoConfiguration.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientAutoConfiguration.java index d8981442..e1184ded 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/FeignRibbonClientAutoConfiguration.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientAutoConfiguration.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.ribbon; +package org.springframework.cloud.openfeign.ribbon; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -24,8 +24,8 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.cloud.client.loadbalancer.LoadBalancedBackOffPolicyFactory; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryListenerFactory; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicyFactory; -import org.springframework.cloud.netflix.feign.FeignAutoConfiguration; -import org.springframework.cloud.netflix.feign.support.FeignHttpClientProperties; +import org.springframework.cloud.openfeign.FeignAutoConfiguration; +import org.springframework.cloud.openfeign.support.FeignHttpClientProperties; import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/HttpClientFeignLoadBalancedConfiguration.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/HttpClientFeignLoadBalancedConfiguration.java similarity index 96% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/HttpClientFeignLoadBalancedConfiguration.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/HttpClientFeignLoadBalancedConfiguration.java index bdd226f4..db352aa2 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/HttpClientFeignLoadBalancedConfiguration.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/HttpClientFeignLoadBalancedConfiguration.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign.ribbon; +package org.springframework.cloud.openfeign.ribbon; import feign.Client; import feign.httpclient.ApacheHttpClient; @@ -34,7 +34,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory; import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory; -import org.springframework.cloud.netflix.feign.support.FeignHttpClientProperties; +import org.springframework.cloud.openfeign.support.FeignHttpClientProperties; import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/LoadBalancerFeignClient.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/LoadBalancerFeignClient.java similarity index 98% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/LoadBalancerFeignClient.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/LoadBalancerFeignClient.java index 37d7f662..ac18f7e1 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/LoadBalancerFeignClient.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/LoadBalancerFeignClient.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.ribbon; +package org.springframework.cloud.openfeign.ribbon; import java.io.IOException; import java.net.URI; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/OkHttpFeignLoadBalancedConfiguration.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/OkHttpFeignLoadBalancedConfiguration.java similarity index 96% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/OkHttpFeignLoadBalancedConfiguration.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/OkHttpFeignLoadBalancedConfiguration.java index c2502429..9d12641e 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/OkHttpFeignLoadBalancedConfiguration.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/OkHttpFeignLoadBalancedConfiguration.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign.ribbon; +package org.springframework.cloud.openfeign.ribbon; import feign.Client; import feign.okhttp.OkHttpClient; @@ -28,7 +28,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory; import org.springframework.cloud.commons.httpclient.OkHttpClientFactory; -import org.springframework.cloud.netflix.feign.support.FeignHttpClientProperties; +import org.springframework.cloud.openfeign.support.FeignHttpClientProperties; import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/RetryableFeignLoadBalancer.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/RetryableFeignLoadBalancer.java similarity index 99% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/RetryableFeignLoadBalancer.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/RetryableFeignLoadBalancer.java index cb5aea92..fee27f80 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/ribbon/RetryableFeignLoadBalancer.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/RetryableFeignLoadBalancer.java @@ -16,7 +16,7 @@ * */ -package org.springframework.cloud.netflix.feign.ribbon; +package org.springframework.cloud.openfeign.ribbon; import feign.Request; import feign.Response; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/FallbackCommand.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/FallbackCommand.java similarity index 96% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/FallbackCommand.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/FallbackCommand.java index 9bc03080..244cc740 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/FallbackCommand.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/FallbackCommand.java @@ -1,4 +1,4 @@ -package org.springframework.cloud.netflix.feign.support; +package org.springframework.cloud.openfeign.support; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/FeignHttpClientProperties.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/FeignHttpClientProperties.java similarity index 98% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/FeignHttpClientProperties.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/FeignHttpClientProperties.java index 501e3e7d..0449450a 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/FeignHttpClientProperties.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/FeignHttpClientProperties.java @@ -16,7 +16,7 @@ * */ -package org.springframework.cloud.netflix.feign.support; +package org.springframework.cloud.openfeign.support; import java.util.concurrent.TimeUnit; import org.springframework.boot.context.properties.ConfigurationProperties; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/FeignUtils.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/FeignUtils.java similarity index 96% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/FeignUtils.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/FeignUtils.java index bb0440fb..cd2f4745 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/FeignUtils.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/FeignUtils.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.support; +package org.springframework.cloud.openfeign.support; import java.util.ArrayList; import java.util.Collection; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/ResponseEntityDecoder.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/ResponseEntityDecoder.java similarity index 97% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/ResponseEntityDecoder.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/ResponseEntityDecoder.java index a9ccbc8c..8f421329 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/ResponseEntityDecoder.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/ResponseEntityDecoder.java @@ -1,4 +1,4 @@ -package org.springframework.cloud.netflix.feign.support; +package org.springframework.cloud.openfeign.support; import java.io.IOException; import java.lang.reflect.ParameterizedType; diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/SpringDecoder.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringDecoder.java similarity index 93% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/SpringDecoder.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringDecoder.java index 798ef5bd..4633b20c 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/SpringDecoder.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringDecoder.java @@ -15,9 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign.support; - -import static org.springframework.cloud.netflix.feign.support.FeignUtils.getHttpHeaders; +package org.springframework.cloud.openfeign.support; import java.io.IOException; import java.io.InputStream; @@ -103,7 +101,7 @@ public class SpringDecoder implements Decoder { @Override public HttpHeaders getHeaders() { - return getHttpHeaders(this.response.headers()); + return FeignUtils.getHttpHeaders(this.response.headers()); } } diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/SpringEncoder.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringEncoder.java similarity index 92% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/SpringEncoder.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringEncoder.java index 83c187d1..ce6eef48 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/SpringEncoder.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringEncoder.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign.support; +package org.springframework.cloud.openfeign.support; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -38,9 +38,6 @@ import feign.RequestTemplate; import feign.codec.EncodeException; import feign.codec.Encoder; -import static org.springframework.cloud.netflix.feign.support.FeignUtils.getHeaders; -import static org.springframework.cloud.netflix.feign.support.FeignUtils.getHttpHeaders; - /** * @author Spencer Gibb */ @@ -97,7 +94,7 @@ public class SpringEncoder implements Encoder { request.headers(null); // converters can modify headers, so update the request // with the modified headers - request.headers(getHeaders(outputMessage.getHeaders())); + request.headers(FeignUtils.getHeaders(outputMessage.getHeaders())); // do not use charset for binary data if (messageConverter instanceof ByteArrayHttpMessageConverter) { @@ -124,7 +121,7 @@ public class SpringEncoder implements Encoder { private final HttpHeaders httpHeaders; private FeignOutputMessage(RequestTemplate request) { - httpHeaders = getHttpHeaders(request.headers()); + httpHeaders = FeignUtils.getHttpHeaders(request.headers()); } @Override diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/SpringMvcContract.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringMvcContract.java similarity index 97% rename from spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/SpringMvcContract.java rename to spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringMvcContract.java index 21eae7ac..670b2372 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/support/SpringMvcContract.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringMvcContract.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.support; +package org.springframework.cloud.openfeign.support; import java.lang.annotation.Annotation; import java.lang.reflect.Method; @@ -28,10 +28,10 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.springframework.cloud.netflix.feign.AnnotatedParameterProcessor; -import org.springframework.cloud.netflix.feign.annotation.PathVariableParameterProcessor; -import org.springframework.cloud.netflix.feign.annotation.RequestHeaderParameterProcessor; -import org.springframework.cloud.netflix.feign.annotation.RequestParamParameterProcessor; +import org.springframework.cloud.openfeign.AnnotatedParameterProcessor; +import org.springframework.cloud.openfeign.annotation.PathVariableParameterProcessor; +import org.springframework.cloud.openfeign.annotation.RequestHeaderParameterProcessor; +import org.springframework.cloud.openfeign.annotation.RequestParamParameterProcessor; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ResourceLoaderAware; import org.springframework.core.DefaultParameterNameDiscoverer; diff --git a/spring-cloud-openfeign-core/src/main/resources/META-INF/spring.factories b/spring-cloud-openfeign-core/src/main/resources/META-INF/spring.factories new file mode 100644 index 00000000..51c962ab --- /dev/null +++ b/spring-cloud-openfeign-core/src/main/resources/META-INF/spring.factories @@ -0,0 +1,5 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +org.springframework.cloud.openfeign.ribbon.FeignRibbonClientAutoConfiguration,\ +org.springframework.cloud.openfeign.FeignAutoConfiguration,\ +org.springframework.cloud.openfeign.encoding.FeignAcceptGzipEncodingAutoConfiguration,\ +org.springframework.cloud.openfeign.encoding.FeignContentGzipEncodingAutoConfiguration diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/EnableFeignClientsTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/EnableFeignClientsTests.java similarity index 92% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/EnableFeignClientsTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/EnableFeignClientsTests.java index 73c24b38..75cfeee3 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/EnableFeignClientsTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/EnableFeignClientsTests.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import org.junit.Test; import org.junit.runner.RunWith; @@ -23,8 +23,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.cloud.netflix.feign.support.SpringEncoder; -import org.springframework.cloud.netflix.feign.support.SpringMvcContract; +import org.springframework.cloud.openfeign.support.SpringEncoder; +import org.springframework.cloud.openfeign.support.SpringMvcContract; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.test.annotation.DirtiesContext; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignClientFactoryTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientFactoryTests.java similarity index 97% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignClientFactoryTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientFactoryTests.java index e3587367..48ecbee9 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignClientFactoryTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientFactoryTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignClientOverrideDefaultsTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientOverrideDefaultsTests.java similarity index 97% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignClientOverrideDefaultsTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientOverrideDefaultsTests.java index bf07fddd..844bda57 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignClientOverrideDefaultsTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientOverrideDefaultsTests.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import org.junit.Test; import org.junit.runner.RunWith; @@ -23,8 +23,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.cloud.netflix.feign.support.SpringEncoder; -import org.springframework.cloud.netflix.feign.support.SpringMvcContract; +import org.springframework.cloud.openfeign.support.SpringEncoder; +import org.springframework.cloud.openfeign.support.SpringMvcContract; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignClientUsingPropertiesTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientUsingPropertiesTests.java similarity index 98% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignClientUsingPropertiesTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientUsingPropertiesTests.java index bc3ff336..7c799a19 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignClientUsingPropertiesTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientUsingPropertiesTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import feign.RequestInterceptor; import feign.RequestTemplate; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignClientsRegistrarTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientsRegistrarTests.java similarity index 98% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignClientsRegistrarTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientsRegistrarTests.java index e8280449..de6bf56d 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignClientsRegistrarTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientsRegistrarTests.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import java.util.Collections; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignCompressionTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignCompressionTests.java similarity index 89% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignCompressionTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignCompressionTests.java index 2a636fb2..afcf3269 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignCompressionTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignCompressionTests.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import java.util.Map; @@ -26,10 +26,10 @@ import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.cloud.netflix.feign.encoding.FeignAcceptGzipEncodingAutoConfiguration; -import org.springframework.cloud.netflix.feign.encoding.FeignAcceptGzipEncodingInterceptor; -import org.springframework.cloud.netflix.feign.encoding.FeignContentGzipEncodingAutoConfiguration; -import org.springframework.cloud.netflix.feign.encoding.FeignContentGzipEncodingInterceptor; +import org.springframework.cloud.openfeign.encoding.FeignAcceptGzipEncodingAutoConfiguration; +import org.springframework.cloud.openfeign.encoding.FeignAcceptGzipEncodingInterceptor; +import org.springframework.cloud.openfeign.encoding.FeignContentGzipEncodingAutoConfiguration; +import org.springframework.cloud.openfeign.encoding.FeignContentGzipEncodingInterceptor; import org.springframework.cloud.test.ClassPathExclusions; import org.springframework.cloud.test.ModifiedClassPathRunner; import org.springframework.context.annotation.Bean; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignHttpClientConfigurationTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignHttpClientConfigurationTests.java similarity index 98% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignHttpClientConfigurationTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignHttpClientConfigurationTests.java index 43f388a8..274c2b50 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignHttpClientConfigurationTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignHttpClientConfigurationTests.java @@ -14,7 +14,7 @@ * limitations under the License. * */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import java.lang.reflect.Field; import javax.net.ssl.SSLContextSpi; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignHttpClientUrlTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignHttpClientUrlTests.java similarity index 99% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignHttpClientUrlTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignHttpClientUrlTests.java index 38fcd89f..d5e074e1 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignHttpClientUrlTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignHttpClientUrlTests.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignLoggerFactoryTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignLoggerFactoryTests.java similarity index 98% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignLoggerFactoryTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignLoggerFactoryTests.java index c773ab4d..dba5c9ea 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignLoggerFactoryTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignLoggerFactoryTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignOkHttpConfigurationTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignOkHttpConfigurationTests.java similarity index 98% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignOkHttpConfigurationTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignOkHttpConfigurationTests.java index a55d758c..2f837db0 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/FeignOkHttpConfigurationTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignOkHttpConfigurationTests.java @@ -14,7 +14,7 @@ * limitations under the License. * */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import okhttp3.OkHttpClient; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/SpringDecoderTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/SpringDecoderTests.java similarity index 99% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/SpringDecoderTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/SpringDecoderTests.java index 5558eef0..74d53e72 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/SpringDecoderTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/SpringDecoderTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import java.util.ArrayList; import java.util.List; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/SpringRetryDisabledTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/SpringRetryDisabledTests.java similarity index 86% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/SpringRetryDisabledTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/SpringRetryDisabledTests.java index 11ca4d1b..b55723e0 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/SpringRetryDisabledTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/SpringRetryDisabledTests.java @@ -15,7 +15,7 @@ */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import java.util.Map; import org.junit.After; @@ -24,10 +24,10 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration; -import org.springframework.cloud.netflix.feign.ribbon.CachingSpringLoadBalancerFactory; -import org.springframework.cloud.netflix.feign.ribbon.FeignLoadBalancer; -import org.springframework.cloud.netflix.feign.ribbon.FeignRibbonClientAutoConfiguration; -import org.springframework.cloud.netflix.feign.ribbon.RetryableFeignLoadBalancer; +import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory; +import org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer; +import org.springframework.cloud.openfeign.ribbon.FeignRibbonClientAutoConfiguration; +import org.springframework.cloud.openfeign.ribbon.RetryableFeignLoadBalancer; import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; import org.springframework.cloud.test.ClassPathExclusions; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/SpringRetryEnabledTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/SpringRetryEnabledTests.java similarity index 86% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/SpringRetryEnabledTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/SpringRetryEnabledTests.java index 5a2eb512..9ab95543 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/SpringRetryEnabledTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/SpringRetryEnabledTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign; +package org.springframework.cloud.openfeign; import java.util.Map; import org.hamcrest.Matchers; @@ -23,10 +23,10 @@ import org.junit.runner.RunWith; import org.springframework.beans.BeansException; import org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration; import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; -import org.springframework.cloud.netflix.feign.ribbon.CachingSpringLoadBalancerFactory; -import org.springframework.cloud.netflix.feign.ribbon.FeignLoadBalancer; -import org.springframework.cloud.netflix.feign.ribbon.FeignRibbonClientAutoConfiguration; -import org.springframework.cloud.netflix.feign.ribbon.RetryableFeignLoadBalancer; +import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory; +import org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer; +import org.springframework.cloud.openfeign.ribbon.FeignRibbonClientAutoConfiguration; +import org.springframework.cloud.openfeign.ribbon.RetryableFeignLoadBalancer; import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; import org.springframework.context.ApplicationContext; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/beans/FeignClientTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/beans/FeignClientTests.java similarity index 91% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/beans/FeignClientTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/beans/FeignClientTests.java index 8e743217..a2f9180f 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/beans/FeignClientTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/beans/FeignClientTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.beans; +package org.springframework.cloud.openfeign.beans; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; @@ -29,8 +29,8 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.feign.FeignClient; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.FeignClient; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; @@ -48,7 +48,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = FeignClientTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { "spring.application.name=feignclienttest", - "logging.level.org.springframework.cloud.netflix.feign.valid=DEBUG", + "logging.level.org.springframework.cloud.openfeign.valid=DEBUG", "feign.httpclient.enabled=false", "feign.okhttp.enabled=false" }) @DirtiesContext public class FeignClientTests { @@ -64,7 +64,7 @@ public class FeignClientTests { @Qualifier("uniquequalifier") @Autowired - private org.springframework.cloud.netflix.feign.beans.extra.TestClient extraClient; + private org.springframework.cloud.openfeign.beans.extra.TestClient extraClient; @Configuration @EnableAutoConfiguration diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/beans/TestClient.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/beans/TestClient.java similarity index 82% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/beans/TestClient.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/beans/TestClient.java index 955a3caa..e00200e5 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/beans/TestClient.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/beans/TestClient.java @@ -14,10 +14,10 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.beans; +package org.springframework.cloud.openfeign.beans; -import org.springframework.cloud.netflix.feign.FeignClient; -import org.springframework.cloud.netflix.feign.beans.FeignClientTests.Hello; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.cloud.openfeign.beans.FeignClientTests.Hello; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/beans/extra/TestClient.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/beans/extra/TestClient.java similarity index 80% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/beans/extra/TestClient.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/beans/extra/TestClient.java index 42676f68..1ea2c6cd 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/beans/extra/TestClient.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/beans/extra/TestClient.java @@ -14,15 +14,15 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.beans.extra; +package org.springframework.cloud.openfeign.beans.extra; -import org.springframework.cloud.netflix.feign.FeignClient; -import org.springframework.cloud.netflix.feign.beans.FeignClientTests.Hello; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.cloud.openfeign.beans.FeignClientTests; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @FeignClient(value = "otherapp", qualifier = "uniquequalifier") public interface TestClient { @RequestMapping(method = RequestMethod.GET, value = "/hello") - Hello getHello(); + FeignClientTests.Hello getHello(); } diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/FeignAcceptEncodingTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/FeignAcceptEncodingTests.java similarity index 90% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/FeignAcceptEncodingTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/FeignAcceptEncodingTests.java index bd7f9956..ed01e9f9 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/FeignAcceptEncodingTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/FeignAcceptEncodingTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.encoding; +package org.springframework.cloud.openfeign.encoding; import java.util.Collections; import java.util.List; @@ -31,9 +31,9 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.feign.encoding.app.client.InvoiceClient; -import org.springframework.cloud.netflix.feign.encoding.app.domain.Invoice; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.encoding.app.client.InvoiceClient; +import org.springframework.cloud.openfeign.encoding.app.domain.Invoice; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -75,7 +75,7 @@ public class FeignAcceptEncodingTests { @EnableFeignClients(clients = InvoiceClient.class) @RibbonClient(name = "local", configuration = LocalRibbonClientConfiguration.class) - @SpringBootApplication(scanBasePackages = "org.springframework.cloud.netflix.feign.encoding.app") + @SpringBootApplication(scanBasePackages = "org.springframework.cloud.openfeign.encoding.app") public static class Application { } diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/FeignContentEncodingTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/FeignContentEncodingTests.java similarity index 90% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/FeignContentEncodingTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/FeignContentEncodingTests.java index 372c35c7..9b827c34 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/FeignContentEncodingTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/FeignContentEncodingTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.encoding; +package org.springframework.cloud.openfeign.encoding; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -29,9 +29,9 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.feign.encoding.app.client.InvoiceClient; -import org.springframework.cloud.netflix.feign.encoding.app.domain.Invoice; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.encoding.app.client.InvoiceClient; +import org.springframework.cloud.openfeign.encoding.app.domain.Invoice; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -78,7 +78,7 @@ public class FeignContentEncodingTests { @EnableFeignClients(clients = InvoiceClient.class) @RibbonClient(name = "local", configuration = LocalRibbonClientConfiguration.class) - @SpringBootApplication(scanBasePackages = "org.springframework.cloud.netflix.feign.encoding.app") + @SpringBootApplication(scanBasePackages = "org.springframework.cloud.openfeign.encoding.app") public static class Application { } diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/Invoices.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/Invoices.java similarity index 90% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/Invoices.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/Invoices.java index 1bcfa957..82b5f335 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/Invoices.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/Invoices.java @@ -14,9 +14,9 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.encoding; +package org.springframework.cloud.openfeign.encoding; -import org.springframework.cloud.netflix.feign.encoding.app.domain.Invoice; +import org.springframework.cloud.openfeign.encoding.app.domain.Invoice; import java.math.BigDecimal; import java.util.ArrayList; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/app/client/InvoiceClient.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/app/client/InvoiceClient.java similarity index 87% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/app/client/InvoiceClient.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/app/client/InvoiceClient.java index bc033976..466d2669 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/app/client/InvoiceClient.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/app/client/InvoiceClient.java @@ -14,12 +14,12 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.encoding.app.client; +package org.springframework.cloud.openfeign.encoding.app.client; import java.util.List; -import org.springframework.cloud.netflix.feign.FeignClient; -import org.springframework.cloud.netflix.feign.encoding.app.domain.Invoice; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.cloud.openfeign.encoding.app.domain.Invoice; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/app/domain/Invoice.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/app/domain/Invoice.java similarity index 93% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/app/domain/Invoice.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/app/domain/Invoice.java index 9bd28d8e..dc47351c 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/app/domain/Invoice.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/app/domain/Invoice.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.encoding.app.domain; +package org.springframework.cloud.openfeign.encoding.app.domain; import java.math.BigDecimal; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/app/resource/InvoiceResource.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/app/resource/InvoiceResource.java similarity index 93% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/app/resource/InvoiceResource.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/app/resource/InvoiceResource.java index 80933f58..d6030d9b 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/encoding/app/resource/InvoiceResource.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/app/resource/InvoiceResource.java @@ -14,9 +14,9 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.encoding.app.resource; +package org.springframework.cloud.openfeign.encoding.app.resource; -import org.springframework.cloud.netflix.feign.encoding.app.domain.Invoice; +import org.springframework.cloud.openfeign.encoding.app.domain.Invoice; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/invalid/FeignClientValidationTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/invalid/FeignClientValidationTests.java similarity index 96% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/invalid/FeignClientValidationTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/invalid/FeignClientValidationTests.java index db6ed80c..9d4ca565 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/invalid/FeignClientValidationTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/invalid/FeignClientValidationTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.invalid; +package org.springframework.cloud.openfeign.invalid; import feign.Feign; import feign.hystrix.FallbackFactory; @@ -23,9 +23,9 @@ import feign.hystrix.HystrixFeign; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.feign.FeignAutoConfiguration; -import org.springframework.cloud.netflix.feign.FeignClient; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.FeignAutoConfiguration; +import org.springframework.cloud.openfeign.FeignClient; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/CachingSpringLoadBalancerFactoryTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/CachingSpringLoadBalancerFactoryTests.java similarity index 98% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/CachingSpringLoadBalancerFactoryTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/CachingSpringLoadBalancerFactoryTests.java index d86ed087..8eb62d8b 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/CachingSpringLoadBalancerFactoryTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/CachingSpringLoadBalancerFactoryTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.ribbon; +package org.springframework.cloud.openfeign.ribbon; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/FeignLoadBalancerTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignLoadBalancerTests.java similarity index 92% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/FeignLoadBalancerTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignLoadBalancerTests.java index 4e468ca3..6d9f8dc0 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/FeignLoadBalancerTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignLoadBalancerTests.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign.ribbon; +package org.springframework.cloud.openfeign.ribbon; import java.net.URI; import java.util.Collection; @@ -28,8 +28,6 @@ import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.springframework.cloud.netflix.feign.ribbon.FeignLoadBalancer.RibbonRequest; -import org.springframework.cloud.netflix.feign.ribbon.FeignLoadBalancer.RibbonResponse; import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector; import org.springframework.cloud.netflix.ribbon.ServerIntrospector; @@ -95,7 +93,7 @@ public class FeignLoadBalancerTests { this.inspector); Request request = new RequestTemplate().method("GET").append("http://foo/") .request(); - RibbonRequest ribbonRequest = new RibbonRequest(this.delegate, request, + FeignLoadBalancer.RibbonRequest ribbonRequest = new FeignLoadBalancer.RibbonRequest(this.delegate, request, new URI(request.url())); Response response = Response.create(200, "Test", @@ -103,7 +101,7 @@ public class FeignLoadBalancerTests { when(this.delegate.execute(any(Request.class), any(Options.class))) .thenReturn(response); - RibbonResponse resp = this.feignLoadBalancer.execute(ribbonRequest, null); + FeignLoadBalancer.RibbonResponse resp = this.feignLoadBalancer.execute(ribbonRequest, null); assertThat(resp.getRequestedURI(), is(new URI("http://foo/"))); } @@ -160,7 +158,7 @@ public class FeignLoadBalancerTests { assertThat(request.url(),is(url)); - RibbonRequest ribbonRequest = new RibbonRequest(this.delegate,request,new URI(request.url())); + FeignLoadBalancer.RibbonRequest ribbonRequest = new FeignLoadBalancer.RibbonRequest(this.delegate,request,new URI(request.url())); Request cloneRequest = ribbonRequest.toRequest(); diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/FeignRibbonClientPathTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientPathTests.java similarity index 96% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/FeignRibbonClientPathTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientPathTests.java index 3946c256..6f973da4 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/FeignRibbonClientPathTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientPathTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.ribbon; +package org.springframework.cloud.openfeign.ribbon; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -26,8 +26,8 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.feign.FeignClient; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.cloud.netflix.ribbon.StaticServerList; import org.springframework.context.annotation.Bean; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/FeignRibbonClientRetryTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientRetryTests.java similarity index 96% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/FeignRibbonClientRetryTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientRetryTests.java index 3e79c91f..1adb6455 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/FeignRibbonClientRetryTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientRetryTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.ribbon; +package org.springframework.cloud.openfeign.ribbon; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; @@ -27,8 +27,8 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.feign.FeignClient; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.cloud.netflix.ribbon.StaticServerList; import org.springframework.context.annotation.Bean; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/FeignRibbonClientTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientTests.java similarity index 97% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/FeignRibbonClientTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientTests.java index 9512c886..b72e6eed 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/FeignRibbonClientTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.ribbon; +package org.springframework.cloud.openfeign.ribbon; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; @@ -37,7 +37,6 @@ import org.springframework.cloud.netflix.ribbon.ServerIntrospector; import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import static org.mockito.Matchers.any; -import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/LoadBalancerFeignClientOverrideTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/LoadBalancerFeignClientOverrideTests.java similarity index 94% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/LoadBalancerFeignClientOverrideTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/LoadBalancerFeignClientOverrideTests.java index 0efae7be..7c8c27cb 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/LoadBalancerFeignClientOverrideTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/LoadBalancerFeignClientOverrideTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.ribbon; +package org.springframework.cloud.openfeign.ribbon; import static org.junit.Assert.assertEquals; @@ -24,9 +24,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.feign.FeignClient; -import org.springframework.cloud.netflix.feign.FeignContext; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.cloud.openfeign.FeignContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/RetryableFeignLoadBalancerTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/RetryableFeignLoadBalancerTests.java similarity index 99% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/RetryableFeignLoadBalancerTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/RetryableFeignLoadBalancerTests.java index 96f9d302..8a592eb7 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/ribbon/RetryableFeignLoadBalancerTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/RetryableFeignLoadBalancerTests.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign.ribbon; +package org.springframework.cloud.openfeign.ribbon; import feign.Client; import feign.Request; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/support/FeignHttpClientPropertiesTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/FeignHttpClientPropertiesTests.java similarity index 98% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/support/FeignHttpClientPropertiesTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/FeignHttpClientPropertiesTests.java index 6431c6a4..f0f5a4b7 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/support/FeignHttpClientPropertiesTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/FeignHttpClientPropertiesTests.java @@ -16,7 +16,7 @@ * */ -package org.springframework.cloud.netflix.feign.support; +package org.springframework.cloud.openfeign.support; import org.junit.After; import org.junit.Test; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/support/SpringEncoderTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringEncoderTests.java similarity index 98% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/support/SpringEncoderTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringEncoderTests.java index 70af122d..f3672d94 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/support/SpringEncoderTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringEncoderTests.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign.support; +package org.springframework.cloud.openfeign.support; import java.io.IOException; import java.lang.reflect.Type; @@ -30,7 +30,7 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.netflix.feign.FeignContext; +import org.springframework.cloud.openfeign.FeignContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpInputMessage; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/support/SpringMvcContractTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractTests.java similarity index 99% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/support/SpringMvcContractTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractTests.java index 32570781..ab82643e 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/support/SpringMvcContractTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.support; +package org.springframework.cloud.openfeign.support; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/test/ApacheHttpClientConfigurationTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/test/ApacheHttpClientConfigurationTests.java similarity index 96% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/test/ApacheHttpClientConfigurationTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/test/ApacheHttpClientConfigurationTests.java index c84aa21b..006fe6e7 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/test/ApacheHttpClientConfigurationTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/test/ApacheHttpClientConfigurationTests.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.test; +package org.springframework.cloud.openfeign.test; import java.io.IOException; import java.lang.reflect.Field; @@ -44,9 +44,9 @@ import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionMa import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory; import org.springframework.cloud.commons.httpclient.DefaultApacheHttpClientConnectionManagerFactory; import org.springframework.cloud.commons.httpclient.DefaultApacheHttpClientFactory; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.feign.FeignClient; -import org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/test/OkHttpClientConfigurationTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/test/OkHttpClientConfigurationTests.java similarity index 95% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/test/OkHttpClientConfigurationTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/test/OkHttpClientConfigurationTests.java index 49a47d4d..e1071858 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/test/OkHttpClientConfigurationTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/test/OkHttpClientConfigurationTests.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.test; +package org.springframework.cloud.openfeign.test; import java.lang.reflect.Field; import java.util.concurrent.TimeUnit; @@ -31,8 +31,8 @@ import org.springframework.cloud.commons.httpclient.DefaultOkHttpClientConnectio import org.springframework.cloud.commons.httpclient.DefaultOkHttpClientFactory; import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory; import org.springframework.cloud.commons.httpclient.OkHttpClientFactory; -import org.springframework.cloud.netflix.feign.FeignClient; -import org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient; import org.springframework.context.annotation.Bean; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/test/TestAutoConfiguration.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/test/TestAutoConfiguration.java similarity index 98% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/test/TestAutoConfiguration.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/test/TestAutoConfiguration.java index 33b671e7..7410ca48 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/test/TestAutoConfiguration.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/test/TestAutoConfiguration.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.test; +package org.springframework.cloud.openfeign.test; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/testclients/TestClient.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/testclients/TestClient.java similarity index 88% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/testclients/TestClient.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/testclients/TestClient.java index 6788d657..77cbf14c 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/testclients/TestClient.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/testclients/TestClient.java @@ -15,9 +15,9 @@ * * limitations under the License. * */ -package org.springframework.cloud.netflix.feign.testclients; +package org.springframework.cloud.openfeign.testclients; -import org.springframework.cloud.netflix.feign.FeignClient; +import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/FeignClientNotPrimaryTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignClientNotPrimaryTests.java similarity index 94% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/FeignClientNotPrimaryTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignClientNotPrimaryTests.java index 5f11411b..76784fa8 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/FeignClientNotPrimaryTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignClientNotPrimaryTests.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign.valid; +package org.springframework.cloud.openfeign.valid; import java.util.List; @@ -26,8 +26,8 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.feign.FeignClient; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.cloud.netflix.ribbon.StaticServerList; import org.springframework.context.annotation.Bean; @@ -54,7 +54,7 @@ import static org.junit.Assert.assertNull; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = FeignClientNotPrimaryTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { "spring.application.name=feignclientnotprimarytest", - "logging.level.org.springframework.cloud.netflix.feign.valid=DEBUG", + "logging.level.org.springframework.cloud.openfeign.valid=DEBUG", "feign.httpclient.enabled=false", "feign.okhttp.enabled=false" }) @DirtiesContext public class FeignClientNotPrimaryTests { diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/FeignClientTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignClientTests.java similarity index 98% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/FeignClientTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignClientTests.java index 039b91c0..d4c55b2b 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/FeignClientTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignClientTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.valid; +package org.springframework.cloud.openfeign.valid; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; @@ -39,11 +39,11 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.feign.FeignClient; -import org.springframework.cloud.netflix.feign.FeignFormatterRegistrar; -import org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient; -import org.springframework.cloud.netflix.feign.support.FallbackCommand; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.cloud.openfeign.FeignFormatterRegistrar; +import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient; +import org.springframework.cloud.openfeign.support.FallbackCommand; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.cloud.netflix.ribbon.RibbonClients; import org.springframework.cloud.netflix.ribbon.StaticServerList; @@ -97,7 +97,7 @@ import rx.Single; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = FeignClientTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { "spring.application.name=feignclienttest", - "logging.level.org.springframework.cloud.netflix.feign.valid=DEBUG", + "logging.level.org.springframework.cloud.openfeign.valid=DEBUG", "feign.httpclient.enabled=false", "feign.okhttp.enabled=false", "feign.hystrix.enabled=true"}) @DirtiesContext diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/FeignClientValidationTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignClientValidationTests.java similarity index 90% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/FeignClientValidationTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignClientValidationTests.java index a3e7a50f..fe91ffbe 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/FeignClientValidationTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignClientValidationTests.java @@ -14,15 +14,15 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.valid; +package org.springframework.cloud.openfeign.valid; import org.junit.Test; import org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration; import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.feign.FeignAutoConfiguration; -import org.springframework.cloud.netflix.feign.FeignClient; -import org.springframework.cloud.netflix.feign.ribbon.FeignRibbonClientAutoConfiguration; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.FeignAutoConfiguration; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.cloud.openfeign.ribbon.FeignRibbonClientAutoConfiguration; import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/FeignHttpClientTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignHttpClientTests.java similarity index 96% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/FeignHttpClientTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignHttpClientTests.java index e0e12b5d..0e9f808c 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/FeignHttpClientTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignHttpClientTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.valid; +package org.springframework.cloud.openfeign.valid; import java.util.Objects; @@ -25,9 +25,9 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.feign.FeignClient; -import org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.cloud.netflix.ribbon.StaticServerList; import org.springframework.context.annotation.Bean; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/FeignOkHttpTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignOkHttpTests.java similarity index 96% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/FeignOkHttpTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignOkHttpTests.java index 5defc28c..a4b04eba 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/FeignOkHttpTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignOkHttpTests.java @@ -15,7 +15,7 @@ * */ -package org.springframework.cloud.netflix.feign.valid; +package org.springframework.cloud.openfeign.valid; import org.junit.Test; import org.junit.runner.RunWith; @@ -24,9 +24,9 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.feign.FeignClient; -import org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.cloud.netflix.ribbon.StaticServerList; import org.springframework.context.annotation.Bean; diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/scanning/FeignClientEnvVarTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/scanning/FeignClientEnvVarTests.java similarity index 91% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/scanning/FeignClientEnvVarTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/scanning/FeignClientEnvVarTests.java index 44607744..00becc0d 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/scanning/FeignClientEnvVarTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/scanning/FeignClientEnvVarTests.java @@ -15,7 +15,7 @@ * * limitations under the License. * */ -package org.springframework.cloud.netflix.feign.valid.scanning; +package org.springframework.cloud.openfeign.valid.scanning; import org.junit.Test; import org.junit.runner.RunWith; @@ -23,8 +23,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.feign.testclients.TestClient; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.testclients.TestClient; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.cloud.netflix.ribbon.StaticServerList; import org.springframework.context.annotation.Bean; @@ -47,7 +47,7 @@ import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = FeignClientEnvVarTests.Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, value = { "spring.application.name=feignclienttest", "feign.httpclient.enabled=false", - "basepackage=org.springframework.cloud.netflix.feign.testclients" }) + "basepackage=org.springframework.cloud.openfeign.testclients" }) @DirtiesContext public class FeignClientEnvVarTests { diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/scanning/FeignClientScanningTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/scanning/FeignClientScanningTests.java similarity index 95% rename from spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/scanning/FeignClientScanningTests.java rename to spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/scanning/FeignClientScanningTests.java index d408c52d..22879e8f 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/feign/valid/scanning/FeignClientScanningTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/scanning/FeignClientScanningTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.netflix.feign.valid.scanning; +package org.springframework.cloud.openfeign.valid.scanning; import org.junit.Test; import org.junit.runner.RunWith; @@ -23,8 +23,8 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.feign.FeignClient; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.cloud.netflix.ribbon.StaticServerList; import org.springframework.context.annotation.Bean; diff --git a/spring-cloud-netflix-core/src/test/resources/META-INF/spring.factories b/spring-cloud-openfeign-core/src/test/resources/META-INF/spring.factories similarity index 50% rename from spring-cloud-netflix-core/src/test/resources/META-INF/spring.factories rename to spring-cloud-openfeign-core/src/test/resources/META-INF/spring.factories index 60ea354e..84a979f1 100644 --- a/spring-cloud-netflix-core/src/test/resources/META-INF/spring.factories +++ b/spring-cloud-openfeign-core/src/test/resources/META-INF/spring.factories @@ -1,2 +1,2 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -org.springframework.cloud.netflix.test.TestAutoConfiguration +org.springframework.cloud.openfeign.test.TestAutoConfiguration diff --git a/spring-cloud-netflix-core/src/test/resources/application.yml b/spring-cloud-openfeign-core/src/test/resources/application.yml similarity index 100% rename from spring-cloud-netflix-core/src/test/resources/application.yml rename to spring-cloud-openfeign-core/src/test/resources/application.yml diff --git a/spring-cloud-netflix-core/src/test/resources/feign-properties.properties b/spring-cloud-openfeign-core/src/test/resources/feign-properties.properties similarity index 51% rename from spring-cloud-netflix-core/src/test/resources/feign-properties.properties rename to spring-cloud-openfeign-core/src/test/resources/feign-properties.properties index bc045d17..91abcebc 100644 --- a/spring-cloud-netflix-core/src/test/resources/feign-properties.properties +++ b/spring-cloud-openfeign-core/src/test/resources/feign-properties.properties @@ -1,6 +1,6 @@ -# This configuration used by test class org.springframework.cloud.netflix.feign.FeignClientUsingPropertiesTests +# This configuration used by test class FeignClientUsingPropertiesTests -logging.level.org.springframework.cloud.netflix.feign=debug +logging.level.org.springframework.cloud.openfeign=debug feign.client.default-to-properties=true feign.client.default-config=default @@ -8,12 +8,12 @@ feign.client.default-config=default feign.client.config.default.connectTimeout=5000 feign.client.config.default.readTimeout=5000 feign.client.config.default.loggerLevel=full -feign.client.config.default.errorDecoder=org.springframework.cloud.netflix.feign.FeignClientUsingPropertiesTests.DefaultErrorDecoder -feign.client.config.default.retryer=org.springframework.cloud.netflix.feign.FeignClientUsingPropertiesTests.NoRetryer +feign.client.config.default.errorDecoder=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.DefaultErrorDecoder +feign.client.config.default.retryer=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.NoRetryer feign.client.config.default.decode404=true -feign.client.config.foo.requestInterceptors[0]=org.springframework.cloud.netflix.feign.FeignClientUsingPropertiesTests.FooRequestInterceptor -feign.client.config.foo.requestInterceptors[1]=org.springframework.cloud.netflix.feign.FeignClientUsingPropertiesTests.BarRequestInterceptor +feign.client.config.foo.requestInterceptors[0]=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.FooRequestInterceptor +feign.client.config.foo.requestInterceptors[1]=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.BarRequestInterceptor feign.client.config.bar.connectTimeout=1000 feign.client.config.bar.readTimeout=1000 \ No newline at end of file diff --git a/spring-cloud-openfeign-dependencies/pom.xml b/spring-cloud-openfeign-dependencies/pom.xml new file mode 100644 index 00000000..aad79132 --- /dev/null +++ b/spring-cloud-openfeign-dependencies/pom.xml @@ -0,0 +1,153 @@ + + + 4.0.0 + + spring-cloud-dependencies-parent + org.springframework.cloud + 2.0.0.BUILD-SNAPSHOT + + + spring-cloud-openfeign-dependencies + 2.0.0.BUILD-SNAPSHOT + pom + spring-cloud-openfeign-dependencies + Spring Cloud OpenFeign Dependencies + + 9.5.1 + + + + + org.springframework.cloud + spring-cloud-openfeign-core + ${project.version} + + + io.github.openfeign + feign-core + ${feign.version} + + + io.github.openfeign + feign-slf4j + ${feign.version} + + + io.github.openfeign + feign-httpclient + ${feign.version} + + + io.github.openfeign + feign-hystrix + ${feign.version} + + + io.github.openfeign + feign-java8 + ${feign.version} + + + io.github.openfeign + feign-okhttp + ${feign.version} + + + io.github.openfeign + feign-gson + ${feign.version} + + + io.github.openfeign + feign-jackson-jaxb + ${feign.version} + + + io.github.openfeign + feign-jackson + ${feign.version} + + + io.github.openfeign + feign-java8 + ${feign.version} + + + io.github.openfeign + feign-jaxb + ${feign.version} + + + io.github.openfeign + feign-jaxrs + ${feign.version} + + + io.github.openfeign + feign-ribbon + ${feign.version} + + + io.github.openfeign + feign-sax + ${feign.version} + + + + + + spring + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/libs-snapshot-local + + true + + + false + + + + spring-milestones + Spring Milestones + https://repo.spring.io/libs-milestone-local + + false + + + + spring-releases + Spring Releases + https://repo.spring.io/release + + false + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/libs-snapshot-local + + true + + + false + + + + spring-milestones + Spring Milestones + https://repo.spring.io/libs-milestone-local + + false + + + + + + diff --git a/spring-cloud-starter-netflix/pom.xml b/spring-cloud-starter-netflix/pom.xml deleted file mode 100644 index 76aada70..00000000 --- a/spring-cloud-starter-netflix/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ - - 4.0.0 - - org.springframework.cloud - spring-cloud-netflix - 2.0.0.BUILD-SNAPSHOT - .. - - spring-cloud-starter-netflix - pom - Spring Cloud Netflix Starters - Spring Cloud Netflix Starters - - spring-cloud-starter-netflix-archaius - spring-cloud-starter-netflix-atlas - spring-cloud-starter-netflix-eureka-client - spring-cloud-starter-netflix-eureka-server - spring-cloud-starter-netflix-hystrix - spring-cloud-starter-netflix-hystrix-dashboard - spring-cloud-starter-netflix-ribbon - spring-cloud-starter-netflix-turbine - spring-cloud-starter-netflix-turbine-stream - spring-cloud-starter-netflix-zuul - spring-cloud-starter-openfeign - - \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-archaius/pom.xml b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-archaius/pom.xml deleted file mode 100644 index 9b9a4099..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-archaius/pom.xml +++ /dev/null @@ -1,60 +0,0 @@ - - 4.0.0 - - org.springframework.cloud - spring-cloud-starter-netflix - 2.0.0.BUILD-SNAPSHOT - - spring-cloud-starter-netflix-archaius - Spring Cloud Starter Netflix Archaius - Spring Cloud Starter Netflix Archaius - https://projects.spring.io/spring-cloud - - Pivotal Software, Inc. - https://www.spring.io - - - ${basedir}/../../.. - - - - org.springframework.cloud - spring-cloud-starter - - - org.springframework.cloud - spring-cloud-netflix-ribbon - - - org.springframework.cloud - spring-cloud-netflix-archaius - - - com.netflix.archaius - archaius-core - - - - commons-configuration - commons-configuration - - - com.fasterxml.jackson.core - jackson-annotations - - - com.fasterxml.jackson.core - jackson-core - - - com.fasterxml.jackson.core - jackson-databind - - - com.google.guava - guava - - - - diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-archaius/src/main/resources/META-INF/spring.provides b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-archaius/src/main/resources/META-INF/spring.provides deleted file mode 100644 index b8f657ed..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-archaius/src/main/resources/META-INF/spring.provides +++ /dev/null @@ -1 +0,0 @@ -provides: archaius-core \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-atlas/pom.xml b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-atlas/pom.xml deleted file mode 100644 index 0749a08a..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-atlas/pom.xml +++ /dev/null @@ -1,38 +0,0 @@ - - 4.0.0 - - org.springframework.cloud - spring-cloud-starter-netflix - 2.0.0.BUILD-SNAPSHOT - - spring-cloud-starter-netflix-atlas - Spring Cloud Starter Netflix Atlas - Spring Cloud Starter Netflix Atlas - https://projects.spring.io/spring-cloud - - Pivotal Software, Inc. - https://www.spring.io - - - ${basedir}/../../.. - - - - org.springframework.cloud - spring-cloud-starter - - - org.springframework.cloud - spring-cloud-netflix-core - - - com.netflix.servo - servo-core - - - com.fasterxml.jackson.dataformat - jackson-dataformat-smile - - - \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-atlas/src/main/resources/resources/META-INF/spring.provides b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-atlas/src/main/resources/resources/META-INF/spring.provides deleted file mode 100644 index ef7cba08..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-atlas/src/main/resources/resources/META-INF/spring.provides +++ /dev/null @@ -1 +0,0 @@ -provides: spring-cloud-starter, spring-cloud-netflix-core, servo-core, jackson-dataformat-smile \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-eureka-client/pom.xml b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-eureka-client/pom.xml deleted file mode 100644 index 97962377..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-eureka-client/pom.xml +++ /dev/null @@ -1,58 +0,0 @@ - - 4.0.0 - - org.springframework.cloud - spring-cloud-starter-netflix - 2.0.0.BUILD-SNAPSHOT - - spring-cloud-starter-netflix-eureka-client - Spring Cloud Starter Netflix Eureka Client - Spring Cloud Starter Netflix Eureka Client - https://projects.spring.io/spring-cloud - - Pivotal Software, Inc. - https://www.spring.io - - - ${basedir}/../../.. - - - - org.springframework.cloud - spring-cloud-starter - - - org.springframework.cloud - spring-cloud-netflix-core - - - org.springframework.cloud - spring-cloud-netflix-eureka-client - - - com.netflix.eureka - eureka-client - - - com.netflix.eureka - eureka-core - - - org.springframework.cloud - spring-cloud-starter-netflix-archaius - - - org.springframework.cloud - spring-cloud-starter-netflix-ribbon - - - com.netflix.ribbon - ribbon-eureka - - - com.thoughtworks.xstream - xstream - - - \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-eureka-server/pom.xml b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-eureka-server/pom.xml deleted file mode 100644 index 271e852c..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-eureka-server/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - 4.0.0 - - org.springframework.cloud - spring-cloud-starter-netflix - 2.0.0.BUILD-SNAPSHOT - - spring-cloud-starter-netflix-eureka-server - Spring Cloud Starter Netflix Eureka Server - Spring Cloud Starter Netflix Eureka Server - https://projects.spring.io/spring-cloud - - Pivotal Software, Inc. - https://www.spring.io - - - ${basedir}/../../.. - - - - org.springframework.cloud - spring-cloud-starter - - - org.springframework.cloud - spring-cloud-netflix-eureka-server - - - org.springframework.cloud - spring-cloud-starter-netflix-archaius - - - org.springframework.cloud - spring-cloud-starter-netflix-ribbon - - - com.netflix.ribbon - ribbon-eureka - - - \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-eureka-server/src/main/resources/META-INF/spring.provides b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-eureka-server/src/main/resources/META-INF/spring.provides deleted file mode 100644 index 3dc45a03..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-eureka-server/src/main/resources/META-INF/spring.provides +++ /dev/null @@ -1 +0,0 @@ -provides: spring-platform-netflix-core, eureka-client \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-hystrix-dashboard/pom.xml b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-hystrix-dashboard/pom.xml deleted file mode 100644 index c6c5de7a..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-hystrix-dashboard/pom.xml +++ /dev/null @@ -1,38 +0,0 @@ - - 4.0.0 - - org.springframework.cloud - spring-cloud-starter-netflix - 2.0.0.BUILD-SNAPSHOT - - spring-cloud-starter-netflix-hystrix-dashboard - Spring Cloud Starter Netflix Hystrix Dashboard - Spring Cloud Starter Netflix Hystrix Dashboard - https://projects.spring.io/spring-cloud - - Pivotal Software, Inc. - https://www.spring.io - - - ${basedir}/../../.. - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.cloud - spring-cloud-starter - - - org.springframework.cloud - spring-cloud-netflix-hystrix-dashboard - - - org.springframework.cloud - spring-cloud-starter-netflix-archaius - - - \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-hystrix-dashboard/src/main/resources/META-INF/spring.provides b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-hystrix-dashboard/src/main/resources/META-INF/spring.provides deleted file mode 100644 index 3dc45a03..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-hystrix-dashboard/src/main/resources/META-INF/spring.provides +++ /dev/null @@ -1 +0,0 @@ -provides: spring-platform-netflix-core, eureka-client \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-hystrix/pom.xml b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-hystrix/pom.xml deleted file mode 100644 index e063c85d..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-hystrix/pom.xml +++ /dev/null @@ -1,58 +0,0 @@ - - 4.0.0 - - org.springframework.cloud - spring-cloud-starter-netflix - 2.0.0.BUILD-SNAPSHOT - - spring-cloud-starter-netflix-hystrix - Spring Cloud Starter Netflix Hystrix - Spring Cloud Starter Netflix Hystrix - https://projects.spring.io/spring-cloud - - Pivotal Software, Inc. - https://www.spring.io - - - ${basedir}/../../.. - - - - org.springframework.cloud - spring-cloud-starter - - - org.springframework.cloud - spring-cloud-netflix-core - - - org.springframework.cloud - spring-cloud-netflix-ribbon - - - org.springframework.cloud - spring-cloud-starter-netflix-archaius - - - com.netflix.hystrix - hystrix-core - - - com.netflix.hystrix - hystrix-serialization - - - com.netflix.hystrix - hystrix-metrics-event-stream - - - com.netflix.hystrix - hystrix-javanica - - - io.reactivex - rxjava-reactive-streams - - - \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-hystrix/src/main/resources/META-INF/spring.provides b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-hystrix/src/main/resources/META-INF/spring.provides deleted file mode 100644 index d78c720c..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-hystrix/src/main/resources/META-INF/spring.provides +++ /dev/null @@ -1 +0,0 @@ -provides: \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-ribbon/pom.xml b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-ribbon/pom.xml deleted file mode 100644 index 9125d009..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-ribbon/pom.xml +++ /dev/null @@ -1,54 +0,0 @@ - - 4.0.0 - - org.springframework.cloud - spring-cloud-starter-netflix - 2.0.0.BUILD-SNAPSHOT - - spring-cloud-starter-netflix-ribbon - Spring Cloud Starter Netflix Ribbon - Spring Cloud Starter Netflix Ribbon - https://projects.spring.io/spring-cloud - - Pivotal Software, Inc. - https://www.spring.io - - - ${basedir}/../../.. - - - - org.springframework.cloud - spring-cloud-starter - - - org.springframework.cloud - spring-cloud-netflix-ribbon - - - org.springframework.cloud - spring-cloud-starter-netflix-archaius - - - com.netflix.ribbon - ribbon - - - com.netflix.ribbon - ribbon-core - - - com.netflix.ribbon - ribbon-httpclient - - - com.netflix.ribbon - ribbon-loadbalancer - - - io.reactivex - rxjava - - - \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-ribbon/src/main/resources/META-INF/spring.provides b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-ribbon/src/main/resources/META-INF/spring.provides deleted file mode 100644 index 40fe3422..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-ribbon/src/main/resources/META-INF/spring.provides +++ /dev/null @@ -1 +0,0 @@ -provides: spring-platform-netflix-core, ribbon-httpclient, ribbon-core \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-turbine-stream/pom.xml b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-turbine-stream/pom.xml deleted file mode 100644 index bc993e17..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-turbine-stream/pom.xml +++ /dev/null @@ -1,76 +0,0 @@ - - 4.0.0 - - org.springframework.cloud - spring-cloud-starter-netflix - 2.0.0.BUILD-SNAPSHOT - - spring-cloud-starter-netflix-turbine-stream - Spring Cloud Starter Netflix Turbine Stream - Spring Cloud Starter Netflix Turbine Stream - https://projects.spring.io/spring-cloud - - Pivotal Software, Inc. - https://www.spring.io - - - ${basedir}/../../.. - 2.0.0-DP.2 - - - - org.springframework.cloud - spring-cloud-starter-netflix-eureka-client - - - spring-boot-starter-tomcat - org.springframework.boot - - - - - org.springframework.cloud - spring-cloud-commons - - - org.springframework.cloud - spring-cloud-starter-netflix-archaius - - - org.springframework.cloud - spring-cloud-netflix-turbine-stream - - - org.springframework.cloud - spring-cloud-stream - - - com.fasterxml.jackson.core - jackson-databind - - - com.netflix.turbine - turbine-core - ${turbine.version} - - - com.netflix.rxjava - rxjava-core - - - org.slf4j - slf4j-simple - - - - - io.reactivex - rxjava - - - org.apache.tomcat.embed - tomcat-embed-el - - - \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-turbine-stream/src/main/resources/META-INF/spring.provides b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-turbine-stream/src/main/resources/META-INF/spring.provides deleted file mode 100644 index e1782585..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-turbine-stream/src/main/resources/META-INF/spring.provides +++ /dev/null @@ -1 +0,0 @@ -provides: spring-cloud-netflix-turbine-amqp \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-turbine/pom.xml b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-turbine/pom.xml deleted file mode 100644 index 9465c95c..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-turbine/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - 4.0.0 - - org.springframework.cloud - spring-cloud-starter-netflix - 2.0.0.BUILD-SNAPSHOT - - spring-cloud-starter-netflix-turbine - Spring Cloud Starter Netflix Turbine - Spring Cloud Starter Netflix Turbine - https://projects.spring.io/spring-cloud - - Pivotal Software, Inc. - https://www.spring.io - - - ${basedir}/../../.. - 1.0.0 - - - - org.springframework.cloud - spring-cloud-starter - - - org.springframework.cloud - spring-cloud-starter-netflix-eureka-client - - - org.springframework.cloud - spring-cloud-netflix-turbine - - - com.netflix.turbine - turbine-core - ${turbine.version} - - - javax.servlet - servlet-api - - - log4j - log4j - - - com.netflix.rxjava - rxjava-core - - - org.slf4j - slf4j-simple - - - org.mockito - mockito-all - - - - - \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-turbine/src/main/resources/META-INF/spring.provides b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-turbine/src/main/resources/META-INF/spring.provides deleted file mode 100644 index 05f29199..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-turbine/src/main/resources/META-INF/spring.provides +++ /dev/null @@ -1 +0,0 @@ -provides: spring-platform-netflix-turbine, turbine-core \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-zuul/pom.xml b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-zuul/pom.xml deleted file mode 100644 index 1ca7b8f7..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-zuul/pom.xml +++ /dev/null @@ -1,54 +0,0 @@ - - 4.0.0 - - org.springframework.cloud - spring-cloud-starter-netflix - 2.0.0.BUILD-SNAPSHOT - - spring-cloud-starter-netflix-zuul - Spring Cloud Starter Netflix Zuul - Spring Cloud Starter Netflix Zuul - https://projects.spring.io/spring-cloud - - Pivotal Software, Inc. - https://www.spring.io - - - ${basedir}/../../.. - - - - org.springframework.cloud - spring-cloud-netflix-zuul - - - org.springframework.cloud - spring-cloud-starter - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.cloud - spring-cloud-starter-netflix-hystrix - - - org.springframework.cloud - spring-cloud-starter-netflix-ribbon - - - org.springframework.cloud - spring-cloud-starter-netflix-archaius - - - com.netflix.zuul - zuul-core - - - \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-zuul/src/main/resources/META-INF/spring.provides b/spring-cloud-starter-netflix/spring-cloud-starter-netflix-zuul/src/main/resources/META-INF/spring.provides deleted file mode 100644 index a51ff5b9..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-zuul/src/main/resources/META-INF/spring.provides +++ /dev/null @@ -1 +0,0 @@ -provides: spring-platform-netflix-core, zuul-core diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-openfeign/src/main/resources/META-INF/spring.provides b/spring-cloud-starter-netflix/spring-cloud-starter-openfeign/src/main/resources/META-INF/spring.provides deleted file mode 100644 index 3dc45a03..00000000 --- a/spring-cloud-starter-netflix/spring-cloud-starter-openfeign/src/main/resources/META-INF/spring.provides +++ /dev/null @@ -1 +0,0 @@ -provides: spring-platform-netflix-core, eureka-client \ No newline at end of file diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-openfeign/pom.xml b/spring-cloud-starter-openfeign/pom.xml similarity index 93% rename from spring-cloud-starter-netflix/spring-cloud-starter-openfeign/pom.xml rename to spring-cloud-starter-openfeign/pom.xml index 8e52a353..607b9091 100644 --- a/spring-cloud-starter-netflix/spring-cloud-starter-openfeign/pom.xml +++ b/spring-cloud-starter-openfeign/pom.xml @@ -3,7 +3,7 @@ 4.0.0 org.springframework.cloud - spring-cloud-starter-netflix + spring-cloud-openfeign 2.0.0.BUILD-SNAPSHOT spring-cloud-starter-openfeign @@ -24,7 +24,8 @@ org.springframework.cloud - spring-cloud-netflix-core + spring-cloud-openfeign-core + 2.0.0.BUILD-SNAPSHOT org.springframework diff --git a/spring-cloud-starter-netflix/spring-cloud-starter-netflix-eureka-client/src/main/resources/META-INF/spring.provides b/spring-cloud-starter-openfeign/src/main/resources/META-INF/spring.provides similarity index 100% rename from spring-cloud-starter-netflix/spring-cloud-starter-netflix-eureka-client/src/main/resources/META-INF/spring.provides rename to spring-cloud-starter-openfeign/src/main/resources/META-INF/spring.provides