diff --git a/samples/wiremock-jetty/src/main/java/com/example/WiremockTestsApplication.java b/samples/wiremock-jetty/src/main/java/com/example/WiremockTestsApplication.java index 0608f2f338..36dcdb988e 100644 --- a/samples/wiremock-jetty/src/main/java/com/example/WiremockTestsApplication.java +++ b/samples/wiremock-jetty/src/main/java/com/example/WiremockTestsApplication.java @@ -21,6 +21,7 @@ public class WiremockTestsApplication { public static void main(String[] args) { SpringApplication.run(WiremockTestsApplication.class, args); } + } @RestController @@ -36,6 +37,7 @@ class Controller { public String home() { return this.service.go(); } + } @Component @@ -51,7 +53,8 @@ class Service { } public String go() { - return this.restTemplate.getForEntity(this.base + "/resource", String.class).getBody(); + return this.restTemplate.getForEntity(this.base + "/resource", String.class) + .getBody(); } public String getBase() { @@ -61,4 +64,5 @@ class Service { public void setBase(String base) { this.base = base; } + } diff --git a/samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsClassRuleTests.java b/samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsClassRuleTests.java index be39bc68f2..ac2f11118b 100644 --- a/samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsClassRuleTests.java +++ b/samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsClassRuleTests.java @@ -19,7 +19,7 @@ import org.springframework.test.context.junit4.SpringRunner; import com.github.tomakehurst.wiremock.junit.WireMockClassRule; @ActiveProfiles("classrule") -//tag::wiremock_test1[] +// tag::wiremock_test1[] @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class WiremockForDocsClassRuleTests { @@ -29,12 +29,14 @@ public class WiremockForDocsClassRuleTests { @ClassRule public static WireMockClassRule wiremock = new WireMockClassRule( WireMockSpring.options().dynamicPort()); -//end::wiremock_test1[] + + // end::wiremock_test1[] @Before public void setup() { this.service.setBase("http://localhost:" + wiremock.port()); } -//tag::wiremock_test2[] + + // tag::wiremock_test2[] // A service that calls out over HTTP to localhost:${wiremock.port} @Autowired private Service service; @@ -43,11 +45,11 @@ public class WiremockForDocsClassRuleTests { @Test public void contextLoads() throws Exception { // Stubbing WireMock - wiremock.stubFor(get(urlEqualTo("/resource")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + wiremock.stubFor(get(urlEqualTo("/resource")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); // We're asserting if WireMock responded properly assertThat(this.service.go()).isEqualTo("Hello World!"); } } -//end::wiremock_test2[] \ No newline at end of file +// end::wiremock_test2[] \ No newline at end of file diff --git a/samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java b/samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java index ff698af3a0..923ce4f974 100644 --- a/samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java +++ b/samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java @@ -33,5 +33,6 @@ public class WiremockForDocsMockServerApplicationTests { assertThat(this.service.go()).isEqualTo("Hello World"); server.verify(); } + } // end::wiremock_test[] diff --git a/samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsTests.java b/samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsTests.java index 60e5a7d37d..29757ff067 100644 --- a/samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsTests.java +++ b/samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsTests.java @@ -18,32 +18,37 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static org.assertj.core.api.Assertions.assertThat; @ActiveProfiles("docs") -//tag::wiremock_test1[] +// tag::wiremock_test1[] @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @AutoConfigureWireMock(port = 0) public class WiremockForDocsTests { -//end::wiremock_test1[] - @Autowired Environment environment; + // end::wiremock_test1[] + + @Autowired + Environment environment; @Before public void setup() { - service.setBase("http://localhost:" + this.environment.getProperty("wiremock.server.port")); + service.setBase("http://localhost:" + + this.environment.getProperty("wiremock.server.port")); } -//tag::wiremock_test2[] + + // tag::wiremock_test2[] // A service that calls out over HTTP - @Autowired private Service service; + @Autowired + private Service service; // Using the WireMock APIs in the normal way: @Test public void contextLoads() throws Exception { // Stubbing WireMock - stubFor(get(urlEqualTo("/resource")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + stubFor(get(urlEqualTo("/resource")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); // We're asserting if WireMock responded properly assertThat(this.service.go()).isEqualTo("Hello World!"); } } -//end::wiremock_test2[] \ No newline at end of file +// end::wiremock_test2[] \ No newline at end of file diff --git a/samples/wiremock-jetty/src/test/java/com/example/WiremockImportApplicationTests.java b/samples/wiremock-jetty/src/test/java/com/example/WiremockImportApplicationTests.java index acc0215f92..7dc6784e57 100644 --- a/samples/wiremock-jetty/src/test/java/com/example/WiremockImportApplicationTests.java +++ b/samples/wiremock-jetty/src/test/java/com/example/WiremockImportApplicationTests.java @@ -14,9 +14,8 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; import org.springframework.test.context.junit4.SpringRunner; - @RunWith(SpringRunner.class) -@SpringBootTest(properties="app.baseUrl=http://localhost:6060", webEnvironment=WebEnvironment.NONE) +@SpringBootTest(properties = "app.baseUrl=http://localhost:6060", webEnvironment = WebEnvironment.NONE) @AutoConfigureWireMock(port = 6060) public class WiremockImportApplicationTests { @@ -25,8 +24,8 @@ public class WiremockImportApplicationTests { @Test public void contextLoads() throws Exception { - stubFor(get(urlEqualTo("/resource")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + stubFor(get(urlEqualTo("/resource")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); assertThat(this.service.go()).isEqualTo("Hello World!"); } diff --git a/samples/wiremock-jetty/src/test/java/com/example/WiremockMockServerApplicationTests.java b/samples/wiremock-jetty/src/test/java/com/example/WiremockMockServerApplicationTests.java index f06509d3da..ca7ad3d93a 100644 --- a/samples/wiremock-jetty/src/test/java/com/example/WiremockMockServerApplicationTests.java +++ b/samples/wiremock-jetty/src/test/java/com/example/WiremockMockServerApplicationTests.java @@ -13,7 +13,7 @@ import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment=WebEnvironment.NONE) +@SpringBootTest(webEnvironment = WebEnvironment.NONE) public class WiremockMockServerApplicationTests { @Autowired diff --git a/samples/wiremock-jetty/src/test/java/com/example/WiremockServerApplicationTests.java b/samples/wiremock-jetty/src/test/java/com/example/WiremockServerApplicationTests.java index 2a3f475fdd..14d868f2bc 100644 --- a/samples/wiremock-jetty/src/test/java/com/example/WiremockServerApplicationTests.java +++ b/samples/wiremock-jetty/src/test/java/com/example/WiremockServerApplicationTests.java @@ -26,11 +26,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.instanceOf; @RunWith(SpringRunner.class) -@SpringBootTest(properties="app.baseUrl=http://localhost:6061", webEnvironment=WebEnvironment.NONE) +@SpringBootTest(properties = "app.baseUrl=http://localhost:6061", webEnvironment = WebEnvironment.NONE) public class WiremockServerApplicationTests { @ClassRule - public static WireMockClassRule wiremock = new WireMockClassRule(WireMockSpring.options().port(6061)); + public static WireMockClassRule wiremock = new WireMockClassRule( + WireMockSpring.options().port(6061)); @Rule public ExpectedException expected = ExpectedException.none(); @@ -40,8 +41,8 @@ public class WiremockServerApplicationTests { @Test public void hello() throws Exception { - stubFor(get(urlEqualTo("/resource")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + stubFor(get(urlEqualTo("/resource")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); assertThat(this.service.go()).isEqualTo("Hello World!"); } diff --git a/samples/wiremock-native/src/main/java/com/example/WiremockTestsApplication.java b/samples/wiremock-native/src/main/java/com/example/WiremockTestsApplication.java index fa59698f17..8ab6535d0c 100644 --- a/samples/wiremock-native/src/main/java/com/example/WiremockTestsApplication.java +++ b/samples/wiremock-native/src/main/java/com/example/WiremockTestsApplication.java @@ -20,6 +20,7 @@ public class WiremockTestsApplication { public static void main(String[] args) { SpringApplication.run(WiremockTestsApplication.class, args); } + } @RestController @@ -35,6 +36,7 @@ class Controller { public String home() { return this.service.go(); } + } @Component @@ -50,6 +52,8 @@ class Service { } public String go() { - return this.restTemplate.getForEntity(this.base + "/resource", String.class).getBody(); + return this.restTemplate.getForEntity(this.base + "/resource", String.class) + .getBody(); } + } diff --git a/samples/wiremock-native/src/test/java/com/example/WiremockServerApplicationTests.java b/samples/wiremock-native/src/test/java/com/example/WiremockServerApplicationTests.java index 46caa3a55f..8619b3efbf 100644 --- a/samples/wiremock-native/src/test/java/com/example/WiremockServerApplicationTests.java +++ b/samples/wiremock-native/src/test/java/com/example/WiremockServerApplicationTests.java @@ -17,7 +17,7 @@ import org.springframework.test.context.junit4.SpringRunner; import com.github.tomakehurst.wiremock.junit.WireMockClassRule; @RunWith(SpringRunner.class) -@SpringBootTest(properties="app.baseUrl=http://localhost:6063", webEnvironment=WebEnvironment.NONE) +@SpringBootTest(properties = "app.baseUrl=http://localhost:6063", webEnvironment = WebEnvironment.NONE) public class WiremockServerApplicationTests { @ClassRule @@ -28,8 +28,8 @@ public class WiremockServerApplicationTests { @Test public void contextLoads() throws Exception { - stubFor(get(urlEqualTo("/resource")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + stubFor(get(urlEqualTo("/resource")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); assertThat(this.service.go()).isEqualTo("Hello World!"); } diff --git a/samples/wiremock-tomcat/src/main/java/com/example/WiremockTestsApplication.java b/samples/wiremock-tomcat/src/main/java/com/example/WiremockTestsApplication.java index 926417a038..f552369004 100644 --- a/samples/wiremock-tomcat/src/main/java/com/example/WiremockTestsApplication.java +++ b/samples/wiremock-tomcat/src/main/java/com/example/WiremockTestsApplication.java @@ -21,6 +21,7 @@ public class WiremockTestsApplication { public static void main(String[] args) { SpringApplication.run(WiremockTestsApplication.class, args); } + } @RestController @@ -36,6 +37,7 @@ class Controller { public String home() { return this.service.go(); } + } @Component @@ -51,6 +53,8 @@ class Service { } public String go() { - return this.restTemplate.getForEntity(this.base + "/resource", String.class).getBody(); + return this.restTemplate.getForEntity(this.base + "/resource", String.class) + .getBody(); } + } diff --git a/samples/wiremock-tomcat/src/test/java/com/example/WiremockHttpsServerApplicationTests.java b/samples/wiremock-tomcat/src/test/java/com/example/WiremockHttpsServerApplicationTests.java index 0eed2de134..a1a98b691c 100644 --- a/samples/wiremock-tomcat/src/test/java/com/example/WiremockHttpsServerApplicationTests.java +++ b/samples/wiremock-tomcat/src/test/java/com/example/WiremockHttpsServerApplicationTests.java @@ -17,7 +17,6 @@ import org.springframework.test.context.junit4.SpringRunner; import com.github.tomakehurst.wiremock.junit.WireMockClassRule; - @RunWith(SpringRunner.class) @SpringBootTest("app.baseUrl=https://localhost:6443") @AutoConfigureHttpClient @@ -32,8 +31,8 @@ public class WiremockHttpsServerApplicationTests { @Test public void contextLoads() throws Exception { - stubFor(get(urlEqualTo("/resource")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + stubFor(get(urlEqualTo("/resource")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); assertThat(this.service.go()).isEqualTo("Hello World!"); } diff --git a/samples/wiremock-tomcat/src/test/java/com/example/WiremockImportApplicationTests.java b/samples/wiremock-tomcat/src/test/java/com/example/WiremockImportApplicationTests.java index 5d6e1081ef..f7ea1ea0da 100644 --- a/samples/wiremock-tomcat/src/test/java/com/example/WiremockImportApplicationTests.java +++ b/samples/wiremock-tomcat/src/test/java/com/example/WiremockImportApplicationTests.java @@ -14,9 +14,8 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; import org.springframework.test.context.junit4.SpringRunner; - @RunWith(SpringRunner.class) -@SpringBootTest(properties="app.baseUrl=http://localhost:6065", webEnvironment=WebEnvironment.NONE) +@SpringBootTest(properties = "app.baseUrl=http://localhost:6065", webEnvironment = WebEnvironment.NONE) @AutoConfigureWireMock(port = 6065) public class WiremockImportApplicationTests { @@ -25,8 +24,8 @@ public class WiremockImportApplicationTests { @Test public void contextLoads() throws Exception { - stubFor(get(urlEqualTo("/resource")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + stubFor(get(urlEqualTo("/resource")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); assertThat(this.service.go()).isEqualTo("Hello World!"); } diff --git a/samples/wiremock-tomcat/src/test/java/com/example/WiremockImportContextPathApplicationTests.java b/samples/wiremock-tomcat/src/test/java/com/example/WiremockImportContextPathApplicationTests.java index d0205aa2f2..f377cf7b7d 100644 --- a/samples/wiremock-tomcat/src/test/java/com/example/WiremockImportContextPathApplicationTests.java +++ b/samples/wiremock-tomcat/src/test/java/com/example/WiremockImportContextPathApplicationTests.java @@ -25,8 +25,8 @@ public class WiremockImportContextPathApplicationTests { @Test public void contextLoads() throws Exception { - stubFor(get(urlEqualTo("/resource")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + stubFor(get(urlEqualTo("/resource")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); assertThat(this.service.go()).isEqualTo("Hello World!"); } diff --git a/samples/wiremock-tomcat/src/test/java/com/example/WiremockMockServerApplicationTests.java b/samples/wiremock-tomcat/src/test/java/com/example/WiremockMockServerApplicationTests.java index c719a6de49..a9bd5cac59 100644 --- a/samples/wiremock-tomcat/src/test/java/com/example/WiremockMockServerApplicationTests.java +++ b/samples/wiremock-tomcat/src/test/java/com/example/WiremockMockServerApplicationTests.java @@ -13,7 +13,7 @@ import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment=WebEnvironment.NONE) +@SpringBootTest(webEnvironment = WebEnvironment.NONE) public class WiremockMockServerApplicationTests { @Autowired diff --git a/samples/wiremock-tomcat/src/test/java/com/example/WiremockServerApplicationTests.java b/samples/wiremock-tomcat/src/test/java/com/example/WiremockServerApplicationTests.java index fd10183cd3..5c97436a43 100644 --- a/samples/wiremock-tomcat/src/test/java/com/example/WiremockServerApplicationTests.java +++ b/samples/wiremock-tomcat/src/test/java/com/example/WiremockServerApplicationTests.java @@ -27,11 +27,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.instanceOf; @RunWith(SpringRunner.class) -@SpringBootTest(properties="app.baseUrl=http://localhost:6067", webEnvironment=WebEnvironment.NONE) +@SpringBootTest(properties = "app.baseUrl=http://localhost:6067", webEnvironment = WebEnvironment.NONE) public class WiremockServerApplicationTests { @ClassRule - public static WireMockClassRule wiremock = new WireMockClassRule(WireMockSpring.options().port(6067)); + public static WireMockClassRule wiremock = new WireMockClassRule( + WireMockSpring.options().port(6067)); @Rule public ExpectedException expected = ExpectedException.none(); @@ -41,8 +42,8 @@ public class WiremockServerApplicationTests { @Test public void contextLoads() throws Exception { - stubFor(get(urlEqualTo("/resource")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + stubFor(get(urlEqualTo("/resource")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); assertThat(this.service.go()).isEqualTo("Hello World!"); } diff --git a/samples/wiremock-undertow-ssl/src/main/java/com/example/WiremockTestsApplication.java b/samples/wiremock-undertow-ssl/src/main/java/com/example/WiremockTestsApplication.java index fa59698f17..8ab6535d0c 100644 --- a/samples/wiremock-undertow-ssl/src/main/java/com/example/WiremockTestsApplication.java +++ b/samples/wiremock-undertow-ssl/src/main/java/com/example/WiremockTestsApplication.java @@ -20,6 +20,7 @@ public class WiremockTestsApplication { public static void main(String[] args) { SpringApplication.run(WiremockTestsApplication.class, args); } + } @RestController @@ -35,6 +36,7 @@ class Controller { public String home() { return this.service.go(); } + } @Component @@ -50,6 +52,8 @@ class Service { } public String go() { - return this.restTemplate.getForEntity(this.base + "/resource", String.class).getBody(); + return this.restTemplate.getForEntity(this.base + "/resource", String.class) + .getBody(); } + } diff --git a/samples/wiremock-undertow-ssl/src/test/java/com/example/WiremockHttpsServerApplicationTests.java b/samples/wiremock-undertow-ssl/src/test/java/com/example/WiremockHttpsServerApplicationTests.java index 4064803f9f..6ac41b8879 100644 --- a/samples/wiremock-undertow-ssl/src/test/java/com/example/WiremockHttpsServerApplicationTests.java +++ b/samples/wiremock-undertow-ssl/src/test/java/com/example/WiremockHttpsServerApplicationTests.java @@ -18,23 +18,22 @@ import org.springframework.util.SocketUtils; import com.github.tomakehurst.wiremock.junit.WireMockClassRule; - @RunWith(SpringRunner.class) @SpringBootTest("app.baseUrl=https://localhost:7443") @ActiveProfiles("ssl") public class WiremockHttpsServerApplicationTests { @ClassRule - public static WireMockClassRule wiremock = new WireMockClassRule( - WireMockSpring.options().httpsPort(7443).port(SocketUtils.findAvailableTcpPort())); + public static WireMockClassRule wiremock = new WireMockClassRule(WireMockSpring + .options().httpsPort(7443).port(SocketUtils.findAvailableTcpPort())); @Autowired private Service service; @Test public void contextLoads() throws Exception { - stubFor(get(urlEqualTo("/resource")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + stubFor(get(urlEqualTo("/resource")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); assertThat(this.service.go()).isEqualTo("Hello World!"); } diff --git a/samples/wiremock-undertow/src/main/java/com/example/WiremockTestsApplication.java b/samples/wiremock-undertow/src/main/java/com/example/WiremockTestsApplication.java index fa59698f17..8ab6535d0c 100644 --- a/samples/wiremock-undertow/src/main/java/com/example/WiremockTestsApplication.java +++ b/samples/wiremock-undertow/src/main/java/com/example/WiremockTestsApplication.java @@ -20,6 +20,7 @@ public class WiremockTestsApplication { public static void main(String[] args) { SpringApplication.run(WiremockTestsApplication.class, args); } + } @RestController @@ -35,6 +36,7 @@ class Controller { public String home() { return this.service.go(); } + } @Component @@ -50,6 +52,8 @@ class Service { } public String go() { - return this.restTemplate.getForEntity(this.base + "/resource", String.class).getBody(); + return this.restTemplate.getForEntity(this.base + "/resource", String.class) + .getBody(); } + } diff --git a/samples/wiremock-undertow/src/test/java/com/example/WiremockImportApplicationTests.java b/samples/wiremock-undertow/src/test/java/com/example/WiremockImportApplicationTests.java index 9c6501404f..cb8d333821 100644 --- a/samples/wiremock-undertow/src/test/java/com/example/WiremockImportApplicationTests.java +++ b/samples/wiremock-undertow/src/test/java/com/example/WiremockImportApplicationTests.java @@ -14,9 +14,8 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; import org.springframework.test.context.junit4.SpringRunner; - @RunWith(SpringRunner.class) -@SpringBootTest(properties="app.baseUrl=http://localhost:7070", webEnvironment=WebEnvironment.NONE) +@SpringBootTest(properties = "app.baseUrl=http://localhost:7070", webEnvironment = WebEnvironment.NONE) @AutoConfigureWireMock(port = 7070) public class WiremockImportApplicationTests { @@ -25,8 +24,8 @@ public class WiremockImportApplicationTests { @Test public void contextLoads() throws Exception { - stubFor(get(urlEqualTo("/resource")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + stubFor(get(urlEqualTo("/resource")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); assertThat(this.service.go()).isEqualTo("Hello World!"); } diff --git a/samples/wiremock-undertow/src/test/java/com/example/WiremockMockServerApplicationTests.java b/samples/wiremock-undertow/src/test/java/com/example/WiremockMockServerApplicationTests.java index 3cc15b627d..47743311a5 100644 --- a/samples/wiremock-undertow/src/test/java/com/example/WiremockMockServerApplicationTests.java +++ b/samples/wiremock-undertow/src/test/java/com/example/WiremockMockServerApplicationTests.java @@ -13,7 +13,7 @@ import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment=WebEnvironment.NONE) +@SpringBootTest(webEnvironment = WebEnvironment.NONE) public class WiremockMockServerApplicationTests { @Autowired diff --git a/samples/wiremock-undertow/src/test/java/com/example/WiremockServerApplicationTests.java b/samples/wiremock-undertow/src/test/java/com/example/WiremockServerApplicationTests.java index e669ff19fc..9c79695029 100644 --- a/samples/wiremock-undertow/src/test/java/com/example/WiremockServerApplicationTests.java +++ b/samples/wiremock-undertow/src/test/java/com/example/WiremockServerApplicationTests.java @@ -18,19 +18,20 @@ import org.springframework.test.context.junit4.SpringRunner; import com.github.tomakehurst.wiremock.junit.WireMockClassRule; @RunWith(SpringRunner.class) -@SpringBootTest(properties="app.baseUrl=http://localhost:7071", webEnvironment=WebEnvironment.NONE) +@SpringBootTest(properties = "app.baseUrl=http://localhost:7071", webEnvironment = WebEnvironment.NONE) public class WiremockServerApplicationTests { @ClassRule - public static WireMockClassRule wiremock = new WireMockClassRule(WireMockSpring.options().port(7071)); + public static WireMockClassRule wiremock = new WireMockClassRule( + WireMockSpring.options().port(7071)); @Autowired private Service service; @Test public void contextLoads() throws Exception { - stubFor(get(urlEqualTo("/resource")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + stubFor(get(urlEqualTo("/resource")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); assertThat(this.service.go()).isEqualTo("Hello World!"); } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/AetherFactories.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/AetherFactories.java index 39f5707026..468e394a9e 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/AetherFactories.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/AetherFactories.java @@ -49,20 +49,24 @@ class AetherFactories { private static final Log log = LogFactory.getLog(AetherFactories.class); private static final String MAVEN_LOCAL_REPOSITORY_LOCATION = "maven.repo.local"; + private static final String MAVEN_USER_SETTINGS_LOCATION = "org.apache.maven.user-settings"; + private static final String MAVEN_GLOBAL_SETTINGS_LOCATION = "org.apache.maven.global-settings"; private static final Random RANDOM = new Random(); public static RepositorySystem newRepositorySystem() { DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator(); - locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class); + locator.addService(RepositoryConnectorFactory.class, + BasicRepositoryConnectorFactory.class); locator.addService(TransporterFactory.class, FileTransporterFactory.class); locator.addService(TransporterFactory.class, HttpTransporterFactory.class); return locator.getService(RepositorySystem.class); } - public static RepositorySystemSession newSession(RepositorySystem system, boolean workOffline) { + public static RepositorySystemSession newSession(RepositorySystem system, + boolean workOffline) { DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); session.setOffline(workOffline); if (!workOffline) { @@ -71,16 +75,19 @@ class AetherFactories { session.setChecksumPolicy(RepositoryPolicy.CHECKSUM_POLICY_WARN); String localRepositoryDirectory = localRepositoryDirectory(workOffline); if (log.isDebugEnabled()) { - log.debug("Local Repository Directory set to [" + localRepositoryDirectory + "]. Work offline: [" + workOffline + "]"); + log.debug("Local Repository Directory set to [" + localRepositoryDirectory + + "]. Work offline: [" + workOffline + "]"); } LocalRepository localRepo = new LocalRepository(localRepositoryDirectory); - session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo)); + session.setLocalRepositoryManager( + system.newLocalRepositoryManager(session, localRepo)); return session; } protected static String localRepositoryDirectory(boolean workOffline) { String localRepoLocationFromSettings = settings().getLocalRepository(); - String currentLocalRepo = readPropertyFromSystemProps(localRepoLocationFromSettings); + String currentLocalRepo = readPropertyFromSystemProps( + localRepoLocationFromSettings); if (workOffline) { return currentLocalRepo; } @@ -93,18 +100,21 @@ class AetherFactories { } catch (IOException e) { if (log.isDebugEnabled()) { - log.debug("Failed to create a new temporary directory, will generate a new one under temp dir"); + log.debug( + "Failed to create a new temporary directory, will generate a new one under temp dir"); } - return System.getProperty("java.io.tmpdir") + File.separator + RANDOM.nextInt(); + return System.getProperty("java.io.tmpdir") + File.separator + + RANDOM.nextInt(); } } private static String readPropertyFromSystemProps( String localRepoLocationFromSettings) { String mavenLocalRepo = fromSystemPropOrEnv(MAVEN_LOCAL_REPOSITORY_LOCATION); - return StringUtils.hasText(mavenLocalRepo) ? mavenLocalRepo : - localRepoLocationFromSettings != null ? localRepoLocationFromSettings - : System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository"; + return StringUtils.hasText(mavenLocalRepo) ? mavenLocalRepo + : localRepoLocationFromSettings != null ? localRepoLocationFromSettings + : System.getProperty("user.home") + File.separator + ".m2" + + File.separator + "repository"; } // system prop takes precedence over env var @@ -136,7 +146,8 @@ class AetherFactories { SettingsBuildingResult result; try { result = builder.build(request); - } catch (SettingsBuildingException ex) { + } + catch (SettingsBuildingException ex) { throw new IllegalStateException(ex); } return result.getEffectiveSettings(); diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/AetherStubDownloader.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/AetherStubDownloader.java index e81d078226..0a96bdec66 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/AetherStubDownloader.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/AetherStubDownloader.java @@ -54,28 +54,38 @@ public class AetherStubDownloader implements StubDownloader { private static final Log log = LogFactory.getLog(AetherStubDownloader.class); private static final String TEMP_DIR_PREFIX = "contracts"; + private static final String ARTIFACT_EXTENSION = "jar"; + private static final String LATEST_ARTIFACT_VERSION = "(,]"; + private static final String LATEST_VERSION_IN_IVY = "+"; + // Preloading class for the shutdown hook not to throw ClassNotFound private static final Class CLAZZ = TemporaryFileStorage.class; private final List remoteRepos; + private final RepositorySystem repositorySystem; + private final RepositorySystemSession session; + private final boolean workOffline; + private final boolean deleteStubsAfterTest; public AetherStubDownloader(StubRunnerOptions stubRunnerOptions) { this.deleteStubsAfterTest = stubRunnerOptions.isDeleteStubsAfterTest(); if (log.isDebugEnabled()) { - log.debug("Will be resolving versions for the following options: [" + stubRunnerOptions + "]"); + log.debug("Will be resolving versions for the following options: [" + + stubRunnerOptions + "]"); } this.remoteRepos = remoteRepositories(stubRunnerOptions); boolean remoteReposMissing = remoteReposMissing(); switch (stubRunnerOptions.stubsMode) { case LOCAL: - log.info("Remote repos not passed but the switch to work offline was set. " + "Stubs will be used from your local Maven repository."); + log.info("Remote repos not passed but the switch to work offline was set. " + + "Stubs will be used from your local Maven repository."); break; case REMOTE: if (remoteReposMissing) { @@ -99,7 +109,6 @@ public class AetherStubDownloader implements StubDownloader { /** * Used by the Maven Plugin - * * @param repositorySystem * @param remoteRepositories - remote artifact repositories * @param session @@ -111,26 +120,29 @@ public class AetherStubDownloader implements StubDownloader { this.repositorySystem = repositorySystem; this.session = session; if (remoteReposMissing()) { - log.error("Remote repositories for stubs are not specified and work offline flag wasn't passed"); + log.error( + "Remote repositories for stubs are not specified and work offline flag wasn't passed"); } this.workOffline = false; registerShutdownHook(); } - private List remoteRepositories(StubRunnerOptions stubRunnerOptions) { + private List remoteRepositories( + StubRunnerOptions stubRunnerOptions) { if (stubRunnerOptions.stubRepositoryRoot == null) { return new ArrayList<>(); } - final String[] repos = stubRunnerOptions.getStubRepositoryRootAsString().split(","); + final String[] repos = stubRunnerOptions.getStubRepositoryRootAsString() + .split(","); final List remoteRepos = new ArrayList<>(); for (int i = 0; i < repos.length; i++) { - if(StringUtils.hasText(repos[i])) { - final RemoteRepository.Builder builder = new RemoteRepository.Builder("remote" + i, "default", repos[i]) - .setAuthentication(new AuthenticationBuilder() - .addUsername(stubRunnerOptions.username) - .addPassword(stubRunnerOptions.password) - .build()); - if(stubRunnerOptions.getProxyOptions() != null) { + if (StringUtils.hasText(repos[i])) { + final RemoteRepository.Builder builder = new RemoteRepository.Builder( + "remote" + i, "default", repos[i]) + .setAuthentication(new AuthenticationBuilder() + .addUsername(stubRunnerOptions.username) + .addPassword(stubRunnerOptions.password).build()); + if (stubRunnerOptions.getProxyOptions() != null) { final StubRunnerProxyOptions p = stubRunnerOptions.getProxyOptions(); builder.setProxy(new Proxy(null, p.getProxyHost(), p.getProxyPort())); } @@ -155,12 +167,14 @@ public class AetherStubDownloader implements StubDownloader { } Artifact artifact = new DefaultArtifact(stubsGroup, stubsModule, classifier, ARTIFACT_EXTENSION, resolvedVersion); - ArtifactRequest request = new ArtifactRequest(artifact, this.remoteRepos, null); + ArtifactRequest request = new ArtifactRequest(artifact, this.remoteRepos, + null); if (log.isDebugEnabled()) { log.debug("Resolving artifact [" + artifact + "] using remote repositories " + this.remoteRepos); } - ArtifactResult result = this.repositorySystem.resolveArtifact(this.session, request); + ArtifactResult result = this.repositorySystem.resolveArtifact(this.session, + request); log.info("Resolved artifact [" + artifact + "] to " + result.getArtifact().getFile()); File temporaryFile = unpackStubJarToATemporaryFolder( @@ -175,7 +189,8 @@ public class AetherStubDownloader implements StubDownloader { throw new IllegalStateException( "Exception occurred while trying to download a stub for group [" + stubsGroup + "] module [" + stubsModule - + "] and classifier [" + classifier + "] in " + this.remoteRepos, + + "] and classifier [" + classifier + "] in " + + this.remoteRepos, e); } } @@ -193,13 +208,16 @@ public class AetherStubDownloader implements StubDownloader { if (StringUtils.isEmpty(version) || LATEST_VERSION_IN_IVY.equals(version)) { log.info("Desired version is [" + version + "] - will try to resolve the latest version"); - return resolveHighestArtifactVersion(stubsGroup, stubsModule, classifier, LATEST_ARTIFACT_VERSION); + return resolveHighestArtifactVersion(stubsGroup, stubsModule, classifier, + LATEST_ARTIFACT_VERSION); } - return resolveHighestArtifactVersion(stubsGroup, stubsModule, classifier, version); + return resolveHighestArtifactVersion(stubsGroup, stubsModule, classifier, + version); } @Override - public Map.Entry downloadAndUnpackStubJar(StubConfiguration stubConfiguration) { + public Map.Entry downloadAndUnpackStubJar( + StubConfiguration stubConfiguration) { String version = getVersion(stubConfiguration.groupId, stubConfiguration.artifactId, stubConfiguration.version, stubConfiguration.classifier); @@ -211,9 +229,9 @@ public class AetherStubDownloader implements StubDownloader { if (unpackedJar == null) { return null; } - return new AbstractMap.SimpleEntry<>( - new StubConfiguration(stubConfiguration.groupId, stubConfiguration.artifactId, version, - stubConfiguration.classifier), unpackedJar); + return new AbstractMap.SimpleEntry<>(new StubConfiguration( + stubConfiguration.groupId, stubConfiguration.artifactId, version, + stubConfiguration.classifier), unpackedJar); } private String resolveHighestArtifactVersion(String stubsGroup, String stubsModule, @@ -234,15 +252,19 @@ public class AetherStubDownloader implements StubDownloader { throw new IllegalStateException("Cannot resolve version range", e); } if (rangeResult.getHighestVersion() == null) { - throw new IllegalArgumentException("For groupId [" + stubsGroup + "] artifactId [" + stubsModule + "] " - + "and classifier [" + classifier + "] the version was not resolved! The following exceptions took place " + throw new IllegalArgumentException("For groupId [" + stubsGroup + + "] artifactId [" + stubsModule + "] " + "and classifier [" + + classifier + + "] the version was not resolved! The following exceptions took place " + rangeResult.getExceptions()); } - return rangeResult.getHighestVersion() == null ? null : rangeResult.getHighestVersion().toString(); + return rangeResult.getHighestVersion() == null ? null + : rangeResult.getHighestVersion().toString(); } private static File unpackStubJarToATemporaryFolder(URI stubJarUri) { - File tmpDirWhereStubsWillBeUnzipped = TemporaryFileStorage.createTempDir(TEMP_DIR_PREFIX); + File tmpDirWhereStubsWillBeUnzipped = TemporaryFileStorage + .createTempDir(TEMP_DIR_PREFIX); log.info("Unpacking stub from JAR [URI: " + stubJarUri + "]"); unzipTo(new File(stubJarUri), tmpDirWhereStubsWillBeUnzipped); TemporaryFileStorage.add(tmpDirWhereStubsWillBeUnzipped); @@ -250,8 +272,8 @@ public class AetherStubDownloader implements StubDownloader { } private void registerShutdownHook() { - Runtime.getRuntime().addShutdownHook(new Thread( - () -> TemporaryFileStorage.cleanup(AetherStubDownloader.this.deleteStubsAfterTest))); + Runtime.getRuntime().addShutdownHook(new Thread(() -> TemporaryFileStorage + .cleanup(AetherStubDownloader.this.deleteStubsAfterTest))); } } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/AetherStubDownloaderBuilder.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/AetherStubDownloaderBuilder.java index 0c73fb4f8e..14c7de2902 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/AetherStubDownloaderBuilder.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/AetherStubDownloaderBuilder.java @@ -9,13 +9,16 @@ import org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties * @since 2.0.0 */ public class AetherStubDownloaderBuilder implements StubDownloaderBuilder { + private static final Log log = LogFactory.getLog(AetherStubDownloaderBuilder.class); - @Override public StubDownloader build(StubRunnerOptions stubRunnerOptions) { + @Override + public StubDownloader build(StubRunnerOptions stubRunnerOptions) { if (stubRunnerOptions.stubsMode == StubRunnerProperties.StubsMode.CLASSPATH) { return null; } log.info("Will download stubs and contracts via Aether"); return new AetherStubDownloader(stubRunnerOptions); } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/Arguments.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/Arguments.java index fbb1e2fa99..2101169b22 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/Arguments.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/Arguments.java @@ -22,8 +22,11 @@ package org.springframework.cloud.contract.stubrunner; * @see StubRunner */ class Arguments { + final private StubRunnerOptions stubRunnerOptions; + final private String repositoryPath; + final private StubConfiguration stub; Arguments(StubRunnerOptions stubRunnerOptions) { @@ -49,8 +52,11 @@ class Arguments { return this.stub; } - @Override public String toString() { + @Override + public String toString() { return "Arguments{" + "stubRunnerOptions=" + this.stubRunnerOptions - + ", repositoryPath='" + this.repositoryPath + '\'' + ", stub=" + this.stub + '}'; + + ", repositoryPath='" + this.repositoryPath + '\'' + ", stub=" + + this.stub + '}'; } + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/AvailablePortScanner.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/AvailablePortScanner.java index 017e2db323..2150142114 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/AvailablePortScanner.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/AvailablePortScanner.java @@ -33,7 +33,9 @@ class AvailablePortScanner { private static final int MAX_RETRY_COUNT = 1000; private final int minPortNumber; + private final int maxPortNumber; + private final int maxRetryCount; AvailablePortScanner(int minPortNumber, int maxPortNumber) { @@ -64,15 +66,16 @@ class AvailablePortScanner { } catch (IOException exception) { if (log.isDebugEnabled()) { - log.debug("Failed to execute callback (try: " + i + "/" + this.maxRetryCount - + ")", exception); + log.debug("Failed to execute callback (try: " + i + "/" + + this.maxRetryCount + ")", exception); } } } throw new NoPortAvailableException(this.minPortNumber, this.maxPortNumber); } - private T executeLogicForAvailablePort(int portToScan, PortCallback closure) throws IOException { + private T executeLogicForAvailablePort(int portToScan, PortCallback closure) + throws IOException { if (log.isDebugEnabled()) { log.debug("Trying to execute closure with port [" + portToScan + "]"); } @@ -93,20 +96,28 @@ class AvailablePortScanner { @SuppressWarnings("serial") static class NoPortAvailableException extends RuntimeException { + NoPortAvailableException(int lowerBound, int upperBound) { - super("Could not find available port in range " + lowerBound + ":" + upperBound); + super("Could not find available port in range " + lowerBound + ":" + + upperBound); } + } @SuppressWarnings("serial") static class InvalidPortRange extends RuntimeException { + InvalidPortRange(int lowerBound, int upperBound) { super("Invalid bounds exceptions, min port [" + lowerBound + "] is greater to max port [" + upperBound + "]"); } + } public interface PortCallback { + T call(int port) throws IOException; + } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/BatchStubRunner.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/BatchStubRunner.java index 411b49d7d3..1b24f77404 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/BatchStubRunner.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/BatchStubRunner.java @@ -54,7 +54,9 @@ public class BatchStubRunner implements StubRunning { for (StubRunner stubRunner : this.stubRunners) { try { return stubRunner.findStubUrl(groupId, artifactId); - } catch (StubNotFoundException e) {} + } + catch (StubNotFoundException e) { + } } throw new StubNotFoundException(groupId, artifactId); } @@ -64,7 +66,9 @@ public class BatchStubRunner implements StubRunning { for (StubRunner stubRunner : this.stubRunners) { try { return stubRunner.findStubUrl(ivyNotation); - } catch (StubNotFoundException e) {} + } + catch (StubNotFoundException e) { + } } throw new StubNotFoundException(ivyNotation); } @@ -175,4 +179,5 @@ public class BatchStubRunner implements StubRunning { stubRunner.close(); } } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/BatchStubRunnerFactory.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/BatchStubRunnerFactory.java index 72282952e0..edf4ca5f50 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/BatchStubRunnerFactory.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/BatchStubRunnerFactory.java @@ -28,35 +28,44 @@ import org.springframework.cloud.contract.verifier.messaging.noop.NoOpStubMessag public class BatchStubRunnerFactory { private final StubRunnerOptions stubRunnerOptions; + private final StubDownloader stubDownloader; + private final MessageVerifier contractVerifierMessaging; public BatchStubRunnerFactory(StubRunnerOptions stubRunnerOptions) { this(stubRunnerOptions, new NoOpStubMessages()); } - public BatchStubRunnerFactory(StubRunnerOptions stubRunnerOptions, MessageVerifier verifier) { + public BatchStubRunnerFactory(StubRunnerOptions stubRunnerOptions, + MessageVerifier verifier) { this(stubRunnerOptions, aetherStubDownloader(stubRunnerOptions), verifier); } - private static StubDownloader aetherStubDownloader(StubRunnerOptions stubRunnerOptions) { + private static StubDownloader aetherStubDownloader( + StubRunnerOptions stubRunnerOptions) { StubDownloaderBuilderProvider provider = new StubDownloaderBuilderProvider(); return provider.get(stubRunnerOptions); } - public BatchStubRunnerFactory(StubRunnerOptions stubRunnerOptions, StubDownloader stubDownloader) { + public BatchStubRunnerFactory(StubRunnerOptions stubRunnerOptions, + StubDownloader stubDownloader) { this(stubRunnerOptions, stubDownloader, new NoOpStubMessages()); } - public BatchStubRunnerFactory(StubRunnerOptions stubRunnerOptions, StubDownloader stubDownloader, MessageVerifier contractVerifierMessaging) { + public BatchStubRunnerFactory(StubRunnerOptions stubRunnerOptions, + StubDownloader stubDownloader, MessageVerifier contractVerifierMessaging) { this.stubRunnerOptions = stubRunnerOptions; this.stubDownloader = stubDownloader; this.contractVerifierMessaging = contractVerifierMessaging; } public BatchStubRunner buildBatchStubRunner() { - StubRunnerFactory stubRunnerFactory = new StubRunnerFactory(this.stubRunnerOptions, this.stubDownloader, this.contractVerifierMessaging); - return new BatchStubRunner(stubRunnerFactory.createStubsFromServiceConfiguration()); + StubRunnerFactory stubRunnerFactory = new StubRunnerFactory( + this.stubRunnerOptions, this.stubDownloader, + this.contractVerifierMessaging); + return new BatchStubRunner( + stubRunnerFactory.createStubsFromServiceConfiguration()); } } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ClasspathStubProvider.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ClasspathStubProvider.java index a553f59ac0..301d87095b 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ClasspathStubProvider.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ClasspathStubProvider.java @@ -23,12 +23,13 @@ import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; /** - * Stub downloader that picks stubs and contracts from the provided resource. - * If {@link org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties#stubsMode} is set - * to {@link org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties.StubsMode#CLASSPATH} + * Stub downloader that picks stubs and contracts from the provided resource. If + * {@link org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties#stubsMode} + * is set to + * {@link org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties.StubsMode#CLASSPATH} * then classpath is searched according to what has been passed in - * {@link org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties#ids}. The - * pattern to search for stubs looks like this + * {@link org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties#ids}. + * The pattern to search for stubs looks like this * *
    *
  • {@code META-INF/group.id/artifactid/ ** /*.* }
  • @@ -51,10 +52,10 @@ import org.springframework.core.io.support.PathMatchingResourcePatternResolver; */ public class ClasspathStubProvider implements StubDownloaderBuilder { - private static final Log log = LogFactory - .getLog(ClasspathStubProvider.class); + private static final Log log = LogFactory.getLog(ClasspathStubProvider.class); private static final int TEMP_DIR_ATTEMPTS = 10000; + private final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver( new DefaultResourceLoader()); @@ -72,35 +73,41 @@ public class ClasspathStubProvider implements StubDownloaderBuilder { List paths = toPaths(repoRoots); List resources = resolveResources(paths); if (log.isDebugEnabled()) { - log.debug("For paths " + paths + " found following resources " + resources); + log.debug("For paths " + paths + " found following resources " + + resources); } if (resources.isEmpty()) { - throw new IllegalStateException("No stubs were found on classpath for [" + config.getGroupId() + ":" + config.getArtifactId() + "]"); + throw new IllegalStateException( + "No stubs were found on classpath for [" + config.getGroupId() + + ":" + config.getArtifactId() + "]"); } final File tmp = createTempDir(); if (stubRunnerOptions.isDeleteStubsAfterTest()) { tmp.deleteOnExit(); } - Pattern groupAndArtifactPattern = Pattern.compile( - "^(.*)(" + config.getGroupId() + "." + config.getArtifactId() + ")(.*)$"); + Pattern groupAndArtifactPattern = Pattern.compile("^(.*)(" + + config.getGroupId() + "." + config.getArtifactId() + ")(.*)$"); String version = config.getVersion(); for (Resource resource : resources) { try { - String relativePath = relativePathPicker(resource, groupAndArtifactPattern); + String relativePath = relativePathPicker(resource, + groupAndArtifactPattern); if (log.isDebugEnabled()) { - log.debug("Relative path for resource is [" + relativePath + "]"); + log.debug("Relative path for resource is [" + relativePath + + "]"); } // the relative path is OS agnostic and contains / only int lastIndexOf = relativePath.lastIndexOf("/"); - String relativePathWithoutFile = lastIndexOf > -1 ? - relativePath.substring(0, lastIndexOf) : - relativePath; + String relativePathWithoutFile = lastIndexOf > -1 + ? relativePath.substring(0, lastIndexOf) : relativePath; if (log.isDebugEnabled()) { - log.debug("Relative path without file name is [" + relativePathWithoutFile + "]"); + log.debug("Relative path without file name is [" + + relativePathWithoutFile + "]"); } Path directory = Files.createDirectories( new File(tmp, relativePathWithoutFile).toPath()); - File newFile = new File(directory.toFile(), resource.getFilename()); + File newFile = new File(directory.toFile(), + resource.getFilename()); if (!newFile.exists() && !isDirectory(resource)) { try (InputStream stream = resource.getInputStream()) { Files.copy(stream, newFile.toPath()); @@ -109,31 +116,38 @@ public class ClasspathStubProvider implements StubDownloaderBuilder { if (log.isDebugEnabled()) { log.debug("Stored file [" + newFile + "]"); } - } catch (IOException e) { + } + catch (IOException e) { log.error("Exception occurred while trying to create dirs", e); throw new IllegalStateException(e); } } - log.info("Unpacked files for [" + config.getGroupId() + ":" + config.getArtifactId() - + ":" + version + "] to folder [" + tmp + "]"); + log.info("Unpacked files for [" + config.getGroupId() + ":" + + config.getArtifactId() + ":" + version + "] to folder [" + tmp + + "]"); return new AbstractMap.SimpleEntry<>( - new StubConfiguration(config.getGroupId(), config.getArtifactId(), version, - config.getClassifier()), tmp); + new StubConfiguration(config.getGroupId(), config.getArtifactId(), + version, config.getClassifier()), + tmp); } boolean isDirectory(Resource resource) { try { return resource.getFile().isDirectory(); - } catch (Exception e) { + } + catch (Exception e) { if (log.isTraceEnabled()) { - log.trace("Exception occurred while trying to convert path to file for resource [" + resource + "]", e); + log.trace( + "Exception occurred while trying to convert path to file for resource [" + + resource + "]", + e); } return false; } } - String relativePathPicker(Resource resource, - Pattern groupAndArtifactPattern) throws IOException { + String relativePathPicker(Resource resource, Pattern groupAndArtifactPattern) + throws IOException { String uri = resource.getURI().toString(); Matcher groupAndArtifactMatcher = groupAndArtifactPattern.matcher(uri); if (groupAndArtifactMatcher.matches()) { @@ -165,7 +179,8 @@ public class ClasspathStubProvider implements StubDownloaderBuilder { resources.addAll(list); } catch (IOException e) { - log.error("Exception occurred while trying to fetch resources from [" + path + "]"); + log.error("Exception occurred while trying to fetch resources from [" + + path + "]"); throw new IllegalStateException(e); } } @@ -175,11 +190,12 @@ public class ClasspathStubProvider implements StubDownloaderBuilder { private List repoRoot(StubRunnerOptions stubRunnerOptions, StubConfiguration configuration) { if (stubRunnerOptions.getStubRepositoryRoot() != null) { - return Collections - .singletonList(new RepoRoot(stubRunnerOptions.getStubRepositoryRootAsString())); + return Collections.singletonList( + new RepoRoot(stubRunnerOptions.getStubRepositoryRootAsString())); } else { - String path = "/**/" + configuration.getGroupId() + "/" + configuration.getArtifactId(); + String path = "/**/" + configuration.getGroupId() + "/" + + configuration.getArtifactId(); return Arrays.asList(new RepoRoot("classpath*:/META-INF" + path, "/**/*.*"), new RepoRoot("classpath*:/contracts" + path, "/**/*.*"), new RepoRoot("classpath*:/mappings" + path, "/**/*.*")); @@ -196,14 +212,15 @@ public class ClasspathStubProvider implements StubDownloaderBuilder { return tempDir; } } - throw new IllegalStateException( - "Failed to create directory within " + TEMP_DIR_ATTEMPTS - + " attempts (tried " + baseName + "0 to " + baseName + ( - TEMP_DIR_ATTEMPTS - 1) + ")"); + throw new IllegalStateException("Failed to create directory within " + + TEMP_DIR_ATTEMPTS + " attempts (tried " + baseName + "0 to " + baseName + + (TEMP_DIR_ATTEMPTS - 1) + ")"); } private static class RepoRoot { + final String repoRoot; + final String fullPath; RepoRoot(String repoRoot) { @@ -215,5 +232,7 @@ public class ClasspathStubProvider implements StubDownloaderBuilder { this.repoRoot = repoRoot; this.fullPath = repoRoot + suffix; } + } + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/CompositeStubDownloaderBuilder.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/CompositeStubDownloaderBuilder.java index 076b6c5309..44c610dbc3 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/CompositeStubDownloaderBuilder.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/CompositeStubDownloaderBuilder.java @@ -36,12 +36,14 @@ class CompositeStubDownloaderBuilder implements StubDownloaderBuilder { this.builders = builders; } - @Override public StubDownloader build(StubRunnerOptions stubRunnerOptions) { + @Override + public StubDownloader build(StubRunnerOptions stubRunnerOptions) { if (this.builders == null) { return null; } return new CompositeStubDownloader(this.builders, stubRunnerOptions); } + } class CompositeStubDownloader implements StubDownloader { @@ -49,6 +51,7 @@ class CompositeStubDownloader implements StubDownloader { private static final Log log = LogFactory.getLog(CompositeStubDownloader.class); private final List builders; + private final StubRunnerOptions stubRunnerOptions; CompositeStubDownloader(List builders, @@ -56,14 +59,13 @@ class CompositeStubDownloader implements StubDownloader { this.builders = builders; this.stubRunnerOptions = stubRunnerOptions; if (log.isDebugEnabled()) { - log.debug("Registered following stub downloaders " + this.builders - .stream() - .map(b -> b.getClass().getName()) - .collect(Collectors.toList())); + log.debug("Registered following stub downloaders " + this.builders.stream() + .map(b -> b.getClass().getName()).collect(Collectors.toList())); } } - @Override public Map.Entry downloadAndUnpackStubJar( + @Override + public Map.Entry downloadAndUnpackStubJar( StubConfiguration stubConfiguration) { for (StubDownloaderBuilder builder : this.builders) { StubDownloader downloader = builder.build(this.stubRunnerOptions); @@ -71,21 +73,27 @@ class CompositeStubDownloader implements StubDownloader { continue; } if (log.isDebugEnabled()) { - log.debug("Found a matching stub downloader [" + downloader.getClass().getName() + "]"); + log.debug("Found a matching stub downloader [" + + downloader.getClass().getName() + "]"); } Map.Entry entry = downloader .downloadAndUnpackStubJar(stubConfiguration); if (entry != null) { if (log.isDebugEnabled()) { - log.debug("Found a matching entry [" + entry + "] by stub downloader [" + downloader.getClass().getName() + "]"); + log.debug( + "Found a matching entry [" + entry + "] by stub downloader [" + + downloader.getClass().getName() + "]"); } return entry; - } else { + } + else { log.warn("Stub Downloader [" + downloader.getClass().getName() + "] " - + "failed to find an entry for [" + stubConfiguration.toColonSeparatedDependencyNotation() + "]. " + + "failed to find an entry for [" + + stubConfiguration.toColonSeparatedDependencyNotation() + "]. " + "Will proceed to the next one"); } } return null; } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ContractDownloader.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ContractDownloader.java index daa388dc84..901888d7c1 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ContractDownloader.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ContractDownloader.java @@ -30,24 +30,28 @@ import org.springframework.util.StringUtils; * inclusion patterns * * @author Marcin Grzejszczak - * * @since 1.0.0 */ public class ContractDownloader { - private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); + private static final Log log = LogFactory + .getLog(MethodHandles.lookup().lookupClass()); private final StubDownloader stubDownloader; + private final StubConfiguration contractsJarStubConfiguration; + private final String contractsPath; + private final String projectGroupId; + private final String projectArtifactId; + private final String projectVersion; public ContractDownloader(StubDownloader stubDownloader, - StubConfiguration contractsJarStubConfiguration, - String contractsPath, String projectGroupId, String projectArtifactId, - String projectVersion) { + StubConfiguration contractsJarStubConfiguration, String contractsPath, + String projectGroupId, String projectArtifactId, String projectVersion) { this.stubDownloader = stubDownloader; this.contractsJarStubConfiguration = contractsJarStubConfiguration; this.contractsPath = contractsPath; @@ -58,10 +62,11 @@ public class ContractDownloader { /** * Downloads JAR containing all the contracts. Plugin configuration gets updated with - * the inclusion pattern for the downloaded contracts. The JAR with the contracts contains all - * the contracts for all the projects. We're interested only in its subset. - * - * @param config - Plugin configuration that will get updated with the inclusion pattern + * the inclusion pattern for the downloaded contracts. The JAR with the contracts + * contains all the contracts for all the projects. We're interested only in its + * subset. + * @param config - Plugin configuration that will get updated with the inclusion + * pattern * @return location of the unpacked downloaded stubs */ public File unpackedDownloadedContracts(ContractVerifierConfigProperties config) { @@ -70,15 +75,16 @@ public class ContractDownloader { return contractsDirectory; } - public ContractVerifierConfigProperties updatePropertiesWithInclusion(File contractsDirectory, - ContractVerifierConfigProperties config) { + public ContractVerifierConfigProperties updatePropertiesWithInclusion( + File contractsDirectory, ContractVerifierConfigProperties config) { String pattern; String includedAntPattern; if (StringUtils.hasText(this.contractsPath)) { pattern = patternFromProperty(contractsDirectory); log.info("Will pick a pattern from the contractPath property"); includedAntPattern = wrapWithAntPattern(contractsPath()); - } else { + } + else { log.info("Will pick a pattern from group id and artifact id"); if (hasGavInPath(contractsDirectory)) { if (log.isDebugEnabled()) { @@ -88,12 +94,14 @@ public class ContractDownloader { // we're already under proper folder (for the given group and artifact) pattern = fileToPattern(contractsDirectory); includedAntPattern = "**/"; - } else { + } + else { if (log.isDebugEnabled()) { log.debug("No group & artifact in path"); } pattern = groupArtifactToPattern(contractsDirectory); - includedAntPattern = wrapWithAntPattern(slashSeparatedGroupId() + "/" + this.projectArtifactId); + includedAntPattern = wrapWithAntPattern( + slashSeparatedGroupId() + "/" + this.projectArtifactId); } } log.info("Pattern to pick contracts equals [" + pattern + "]"); @@ -120,13 +128,11 @@ public class ContractDownloader { } private boolean hasVersionInPath(File file) { - return file.getAbsolutePath() - .contains(this.projectVersion); + return file.getAbsolutePath().contains(this.projectVersion); } private boolean hasSeparatedGroupInPath(File file, String separator) { - return file.getAbsolutePath() - .contains(groupAndArtifact(separator)); + return file.getAbsolutePath().contains(groupAndArtifact(separator)); } private String groupAndArtifact(String separator) { @@ -134,9 +140,9 @@ public class ContractDownloader { } private String patternFromProperty(File contractsDirectory) { - return ("^" + contractsDirectory.getAbsolutePath() + - "(" + File.separator + ")?" + ".*" + - contractsPath().replace("/", File.separator) + ".*$").replace("\\", "\\\\"); + return ("^" + contractsDirectory.getAbsolutePath() + "(" + File.separator + ")?" + + ".*" + contractsPath().replace("/", File.separator) + ".*$") + .replace("\\", "\\\\"); } private String contractsPath() { @@ -144,18 +150,21 @@ public class ContractDownloader { } private String surroundWithSeparator(String string) { - String path = string.startsWith(File.separator) ? string : File.separator + string; + String path = string.startsWith(File.separator) ? string + : File.separator + string; return path.endsWith(File.separator) ? path : path + File.separator; } private String wrapWithAntPattern(String path) { String changedPath = path.replace(File.separator, "/"); - return "**" + surroundWithSeparator(changedPath).replace(File.separator, "/") + "**/"; + return "**" + surroundWithSeparator(changedPath).replace(File.separator, "/") + + "**/"; } private File unpackAndDownloadContracts() { if (log.isDebugEnabled()) { - log.debug("Will download contracts for [" + this.contractsJarStubConfiguration + "]"); + log.debug("Will download contracts for [" + this.contractsJarStubConfiguration + + "]"); } Map.Entry unpackedContractStubs = this.stubDownloader .downloadAndUnpackStubJar(this.contractsJarStubConfiguration); @@ -166,23 +175,17 @@ public class ContractDownloader { } private String groupArtifactToPattern(File contractsDirectory) { - return ("^" + - contractsDirectory.getAbsolutePath() + - "(" + File.separator + ")?" + ".*" + - slashSeparatedGroupId() + - File.separator + - this.projectArtifactId - + File.separator + - ".*$").replace("\\", "\\\\"); + return ("^" + contractsDirectory.getAbsolutePath() + "(" + File.separator + ")?" + + ".*" + slashSeparatedGroupId() + File.separator + this.projectArtifactId + + File.separator + ".*$").replace("\\", "\\\\"); } private String fileToPattern(File contractsDirectory) { - return ("^" + - contractsDirectory.getAbsolutePath() + - ".*$").replace("\\", "\\\\"); + return ("^" + contractsDirectory.getAbsolutePath() + ".*$").replace("\\", "\\\\"); } private String slashSeparatedGroupId() { return this.projectGroupId.replace(".", File.separator); } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ContractProjectUpdater.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ContractProjectUpdater.java index bb584b5d04..fe0f1f74c7 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ContractProjectUpdater.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ContractProjectUpdater.java @@ -39,14 +39,20 @@ public class ContractProjectUpdater { private static final Log log = LogFactory.getLog(ContractProjectUpdater.class); private static final int DEFAULT_ATTEMPTS_NO = 10; + private static final long DEFAULT_WAIT_BETWEEN_ATTEMPTS = 1000; + // TODO: Add this to the documentation private static final String DEFAULT_COMMIT_MESSAGE = "Updating project [$project] with stubs"; + private static final String GIT_ATTEMPTS_NO_PROP = "git.no-of-attempts"; + private static final String GIT_WAIT_BETWEEN_ATTEMPTS = "git.wait-between-attempts"; + private static final String GIT_COMMIT_MESSAGE = "git.commit-message"; private final StubRunnerOptions stubRunnerOptions; + private final GitContractsRepo gitContractsRepo; public ContractProjectUpdater(StubRunnerOptions stubRunnerOptions) { @@ -66,40 +72,47 @@ public class ContractProjectUpdater { this.stubRunnerOptions.stubRepositoryRoot, this.stubRunnerOptions); copyStubs(projectName, rootStubsFolder, clonedRepo); GitRepo gitRepo = new GitRepo(clonedRepo, properties); - String msg = StubRunnerPropertyUtils.getProperty(this.stubRunnerOptions.getProperties(), - GIT_COMMIT_MESSAGE); - GitRepo.CommitResult commit = gitRepo - .commit(clonedRepo, commitMessage(projectName, msg)); + String msg = StubRunnerPropertyUtils + .getProperty(this.stubRunnerOptions.getProperties(), GIT_COMMIT_MESSAGE); + GitRepo.CommitResult commit = gitRepo.commit(clonedRepo, + commitMessage(projectName, msg)); if (commit == GitRepo.CommitResult.EMPTY) { log.info("There were no changes to commit. Won't push the changes"); return; } - String attempts = StubRunnerPropertyUtils.getProperty(this.stubRunnerOptions.getProperties(), - GIT_ATTEMPTS_NO_PROP); - int intAttempts = StringUtils.hasText(attempts) ? Integer.parseInt(attempts) : DEFAULT_ATTEMPTS_NO; - String wait = StubRunnerPropertyUtils.getProperty(this.stubRunnerOptions.getProperties(), - GIT_WAIT_BETWEEN_ATTEMPTS); - long longWait = StringUtils.hasText(wait) ? Long.parseLong(wait) : DEFAULT_WAIT_BETWEEN_ATTEMPTS; + String attempts = StubRunnerPropertyUtils.getProperty( + this.stubRunnerOptions.getProperties(), GIT_ATTEMPTS_NO_PROP); + int intAttempts = StringUtils.hasText(attempts) ? Integer.parseInt(attempts) + : DEFAULT_ATTEMPTS_NO; + String wait = StubRunnerPropertyUtils.getProperty( + this.stubRunnerOptions.getProperties(), GIT_WAIT_BETWEEN_ATTEMPTS); + long longWait = StringUtils.hasText(wait) ? Long.parseLong(wait) + : DEFAULT_WAIT_BETWEEN_ATTEMPTS; tryToPushCurrentBranch(clonedRepo, gitRepo, intAttempts, longWait); } private void tryToPushCurrentBranch(File clonedRepo, GitRepo gitRepo, int intAttempts, long longWait) { int currentAttempt = 0; - while(currentAttempt < intAttempts) { - log.info("Trying to push changes, attempt " + (currentAttempt + 1) + "/" + intAttempts); + while (currentAttempt < intAttempts) { + log.info("Trying to push changes, attempt " + (currentAttempt + 1) + "/" + + intAttempts); gitRepo.pull(clonedRepo); - log.info("Successfully pulled changes from remote for project with contract and stubs"); + log.info( + "Successfully pulled changes from remote for project with contract and stubs"); try { gitRepo.pushCurrentBranch(clonedRepo); log.info("Successfully pushed changes with current stubs"); break; - } catch (IllegalStateException e) { + } + catch (IllegalStateException e) { // empty log.error("Exception occurred while trying to push the changes", e); currentAttempt++; if (currentAttempt == intAttempts) { - throw new IllegalStateException("Failed to push changes to the project with contracts and stubs. Exceeded number of retries [" + intAttempts + "]"); + throw new IllegalStateException( + "Failed to push changes to the project with contracts and stubs. Exceeded number of retries [" + + intAttempts + "]"); } try { Thread.sleep(longWait); @@ -112,9 +125,8 @@ public class ContractProjectUpdater { } private String commitMessage(String projectName, String msg) { - return StringUtils.hasText(msg) ? - replaceProject(projectName, msg) : - replaceProject(projectName, DEFAULT_COMMIT_MESSAGE); + return StringUtils.hasText(msg) ? replaceProject(projectName, msg) + : replaceProject(projectName, DEFAULT_COMMIT_MESSAGE); } private String replaceProject(String projectName, String msg) { @@ -124,36 +136,44 @@ public class ContractProjectUpdater { private void copyStubs(String projectName, Path rootStubsFolder, File clonedRepo) { try { if (log.isDebugEnabled()) { - log.debug("Copying stubs from [" + rootStubsFolder.toString() + "] to the cloned repo [" + clonedRepo.getAbsolutePath() + "] for project [" + projectName + "]"); + log.debug("Copying stubs from [" + rootStubsFolder.toString() + + "] to the cloned repo [" + clonedRepo.getAbsolutePath() + + "] for project [" + projectName + "]"); } Files.walkFileTree(rootStubsFolder, new DirectoryCopyingVisitor(rootStubsFolder, clonedRepo.toPath())); if (log.isDebugEnabled()) { - log.debug("Successfully copied stubs to the cloned repo for project [" + projectName + "]"); + log.debug("Successfully copied stubs to the cloned repo for project [" + + projectName + "]"); } } catch (IOException e) { throw new IllegalStateException(e); } } + } class DirectoryCopyingVisitor extends SimpleFileVisitor { private static final Log log = LogFactory.getLog(DirectoryCopyingVisitor.class); + private final Path from; + private final Path to; DirectoryCopyingVisitor(Path from, Path to) { this.from = from; this.to = to; if (log.isDebugEnabled()) { - log.debug("Will copy from [" + from.toString() + "] to [" + to.toString() + "]"); + log.debug("Will copy from [" + from.toString() + "] to [" + to.toString() + + "]"); } } @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) + throws IOException { Path relativePath = this.from.relativize(dir); if (".git".equals(relativePath.toString())) { return FileVisitResult.SKIP_SUBTREE; @@ -164,7 +184,8 @@ class DirectoryCopyingVisitor extends SimpleFileVisitor { log.debug("Created a folder [" + targetPath.toString() + "]"); } Files.createDirectory(targetPath); - } else { + } + else { if (log.isDebugEnabled()) { log.debug("Folder [" + targetPath.toString() + "] already exists"); } @@ -173,12 +194,15 @@ class DirectoryCopyingVisitor extends SimpleFileVisitor { } @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) + throws IOException { Path relativePath = this.to.resolve(this.from.relativize(file)); Files.copy(file, relativePath, StandardCopyOption.REPLACE_EXISTING); if (log.isDebugEnabled()) { - log.debug("Copied file from [" + file.toString() + "] to [" + relativePath.toString() + "]"); + log.debug("Copied file from [" + file.toString() + "] to [" + + relativePath.toString() + "]"); } return FileVisitResult.CONTINUE; } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/GitRepo.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/GitRepo.java index a491cfd996..f660b4e533 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/GitRepo.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/GitRepo.java @@ -60,8 +60,8 @@ import org.slf4j.LoggerFactory; import org.springframework.util.ResourceUtils; /** - * Abstraction over a Git repo. Can cloned repo from a given location - * and check its branch. + * Abstraction over a Git repo. Can cloned repo from a given location and check its + * branch. * * taken from: https://github.com/spring-cloud/spring-cloud-release-tools * @@ -101,7 +101,7 @@ class GitRepo { */ File cloneProject(URI projectUri) { try { - log.info("Cloning repo from [" + projectUri + "] to [" + this.basedir + "]"); + log.info("Cloning repo from [" + projectUri + "] to [" + this.basedir + "]"); Git git = cloneToBasedir(projectUri, this.basedir); if (git != null) { git.close(); @@ -158,29 +158,34 @@ class GitRepo { * @param message - commit message */ CommitResult commit(File project, String message) { - try(Git git = this.gitFactory.open(file(project))) { + try (Git git = this.gitFactory.open(file(project))) { git.add().addFilepattern(".").call(); git.commit().setAllowEmpty(false).setMessage(message).call(); log.info("Commited successfully with message [" + message + "]"); return CommitResult.SUCCESSFUL; - } catch (EmtpyCommitException e) { + } + catch (EmtpyCommitException e) { log.info("There were no changes detected. Will not commit an empty commit"); return CommitResult.EMPTY; - } catch (Exception e) { + } + catch (Exception e) { throw new IllegalStateException(e); } } void reset(File project) { - try(Git git = this.gitFactory.open(file(project))) { + try (Git git = this.gitFactory.open(file(project))) { git.reset().setMode(ResetCommand.ResetType.HARD).call(); - } catch (Exception e) { + } + catch (Exception e) { throw new IllegalStateException(e); } } enum CommitResult { + SUCCESSFUL, EMPTY + } /** @@ -188,9 +193,10 @@ class GitRepo { * @param project - Git project */ void pushCurrentBranch(File project) { - try(Git git = this.gitFactory.open(file(project))) { + try (Git git = this.gitFactory.open(file(project))) { this.gitFactory.push(git).call(); - } catch (Exception e) { + } + catch (Exception e) { throw new IllegalStateException(e); } } @@ -223,8 +229,7 @@ class GitRepo { } } - private Ref checkoutBranch(File projectDir, String branch) - throws GitAPIException { + private Ref checkoutBranch(File projectDir, String branch) throws GitAPIException { Git git = this.gitFactory.open(projectDir); CheckoutCommand command = git.checkout().setName(branch); try { @@ -236,7 +241,8 @@ class GitRepo { catch (GitAPIException e) { deleteBaseDirIfExists(); throw e; - } finally { + } + finally { git.close(); } } @@ -272,8 +278,8 @@ class GitRepo { return containsBranch(git, label, null); } - private boolean containsBranch(Git git, String label, ListBranchCommand.ListMode listMode) - throws GitAPIException { + private boolean containsBranch(Git git, String label, + ListBranchCommand.ListMode listMode) throws GitAPIException { ListBranchCommand command = git.branchList(); if (listMode != null) { command.setListMode(listMode); @@ -299,35 +305,42 @@ class GitRepo { } /** - * Wraps the static method calls to {@link Git} and - * {@link CloneCommand} allowing for easier unit testing. + * Wraps the static method calls to {@link Git} and {@link CloneCommand} allowing for + * easier unit testing. */ static class JGitFactory { - private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); + + private static final Logger log = LoggerFactory + .getLogger(MethodHandles.lookup().lookupClass()); private final JschConfigSessionFactory factory = new JschConfigSessionFactory() { - @Override protected void configure(OpenSshConfig.Host host, Session session) { + @Override + protected void configure(OpenSshConfig.Host host, Session session) { } @Override protected JSch createDefaultJSch(FS fs) throws JSchException { Connector connector = null; try { - if(SSHAgentConnector.isConnectorAvailable()){ + if (SSHAgentConnector.isConnectorAvailable()) { USocketFactory usf = new JNAUSocketFactory(); connector = new SSHAgentConnector(usf); } log.info("Successfully connected to an agent"); - } catch (AgentProxyException e) { - log.error("Exception occurred while trying to connect to agent. Will create" - + "the default JSch connection", e); + } + catch (AgentProxyException e) { + log.error( + "Exception occurred while trying to connect to agent. Will create" + + "the default JSch connection", + e); return super.createDefaultJSch(fs); } final JSch jsch = super.createDefaultJSch(fs); if (connector != null) { JSch.setConfig("PreferredAuthentications", "publickey,password"); - IdentityRepository identityRepository = new RemoteIdentityRepository(connector); + IdentityRepository identityRepository = new RemoteIdentityRepository( + connector); jsch.setIdentityRepository(identityRepository); } return jsch; @@ -338,9 +351,11 @@ class GitRepo { JGitFactory(GitStubDownloaderProperties properties) { if (org.springframework.util.StringUtils.hasText(properties.username)) { - log.info("Passed username and password - will set a custom credentials provider"); + log.info( + "Passed username and password - will set a custom credentials provider"); this.provider = credentialsProvider(properties); - } else { + } + else { if (log.isDebugEnabled()) { log.debug("No custom credentials provider will be set"); } @@ -349,8 +364,7 @@ class GitRepo { } CredentialsProvider credentialsProvider(GitStubDownloaderProperties properties) { - return new UsernamePasswordCredentialsProvider( - properties.username, + return new UsernamePasswordCredentialsProvider(properties.username, properties.password); } @@ -367,20 +381,17 @@ class GitRepo { }; CloneCommand getCloneCommandByCloneRepository() { - return Git.cloneRepository() - .setCredentialsProvider(this.provider) + return Git.cloneRepository().setCredentialsProvider(this.provider) .setTransportConfigCallback(this.callback); } PushCommand push(Git git) { - return git.push() - .setCredentialsProvider(this.provider) + return git.push().setCredentialsProvider(this.provider) .setTransportConfigCallback(this.callback); } PullCommand pull(Git git) { - return git.pull() - .setCredentialsProvider(this.provider) + return git.pull().setCredentialsProvider(this.provider) .setTransportConfigCallback(this.callback); } @@ -392,5 +403,7 @@ class GitRepo { throw new IllegalStateException(e); } } + } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/HttpServerStub.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/HttpServerStub.java index f45ba6ad78..bc3ab3b015 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/HttpServerStub.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/HttpServerStub.java @@ -10,6 +10,7 @@ import java.util.Collection; * @since 1.1.0 */ public interface HttpServerStub { + /** * Port on which the server is running */ @@ -21,14 +22,12 @@ public interface HttpServerStub { boolean isRunning(); /** - * Starts the server on a random port. Should return itself - * to allow chaining. + * Starts the server on a random port. Should return itself to allow chaining. */ HttpServerStub start(); /** - * Starts the server on a given port. Should return itself - * to allow chaining. + * Starts the server on a given port. Should return itself to allow chaining. */ HttpServerStub start(int port); @@ -38,8 +37,8 @@ public interface HttpServerStub { HttpServerStub stop(); /** - * Registers the stub files in the HTTP server stub. Should return itself - * to allow chaining. + * Registers the stub files in the HTTP server stub. Should return itself to allow + * chaining. */ HttpServerStub registerMappings(Collection stubFiles); @@ -52,4 +51,5 @@ public interface HttpServerStub { * Returns {@code true} if the file is a valid stub mapping */ boolean isAccepted(File file); + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/MessageNotMatchingException.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/MessageNotMatchingException.java index a42fe97ea7..9e863d64b6 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/MessageNotMatchingException.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/MessageNotMatchingException.java @@ -23,4 +23,5 @@ package org.springframework.cloud.contract.stubrunner; */ @SuppressWarnings("serial") class MessageNotMatchingException extends RuntimeException { + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/NoOpHttpServerStub.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/NoOpHttpServerStub.java index 5ecf97678f..d0d1606b12 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/NoOpHttpServerStub.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/NoOpHttpServerStub.java @@ -7,6 +7,7 @@ import java.util.Collection; * @author Marcin Grzejszczak */ class NoOpHttpServerStub implements HttpServerStub { + @Override public int port() { return -1; @@ -37,11 +38,14 @@ class NoOpHttpServerStub implements HttpServerStub { return this; } - @Override public String registeredMappings() { + @Override + public String registeredMappings() { return ""; } - @Override public boolean isAccepted(File file) { + @Override + public boolean isAccepted(File file) { return true; } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ResourceResolver.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ResourceResolver.java index 1fa1a29da5..c290871244 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ResourceResolver.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ResourceResolver.java @@ -27,11 +27,11 @@ import org.springframework.core.io.Resource; import org.springframework.core.io.support.SpringFactoriesLoader; /** - * Uses {@code META-INF/spring.factories} to read {@link ProtocolResolver} list - * that gets added to {@link DefaultResourceLoader}. Each implementor of a new - * {@link org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder}, if - * one uses a new protocol, should register their own {@link ProtocolResolver} so - * that Stub Runner can convert a {@link String} version of a URI to a {@link Resource}. + * Uses {@code META-INF/spring.factories} to read {@link ProtocolResolver} list that gets + * added to {@link DefaultResourceLoader}. Each implementor of a new + * {@link org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder}, if one + * uses a new protocol, should register their own {@link ProtocolResolver} so that Stub + * Runner can convert a {@link String} version of a URI to a {@link Resource}. * * IMPORTANT! Internal tool. Do not use. * @@ -41,14 +41,16 @@ import org.springframework.core.io.support.SpringFactoriesLoader; public class ResourceResolver { private static final Log log = LogFactory.getLog(ResourceResolver.class); + private static final List RESOLVERS = new ArrayList<>(); + private static final DefaultResourceLoader LOADER = new DefaultResourceLoader(); static { RESOLVERS.addAll( - SpringFactoriesLoader.loadFactories(StubDownloaderBuilder.class, null) - ); - RESOLVERS.addAll(new StubDownloaderBuilderProvider().defaultStubDownloaderBuilders()); + SpringFactoriesLoader.loadFactories(StubDownloaderBuilder.class, null)); + RESOLVERS.addAll( + new StubDownloaderBuilderProvider().defaultStubDownloaderBuilders()); for (ProtocolResolver resolver : RESOLVERS) { LOADER.addProtocolResolver(resolver); } @@ -61,9 +63,13 @@ public class ResourceResolver { public static Resource resource(String url) { try { return LOADER.getResource(url); - } catch (Exception e) { - log.error("Exception occurred while trying to read the resource [" + url + "]", e); + } + catch (Exception e) { + log.error( + "Exception occurred while trying to read the resource [" + url + "]", + e); return null; } } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ScmStubDownloaderBuilder.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ScmStubDownloaderBuilder.java index 4d1bf8d4e5..fec9b08f0c 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ScmStubDownloaderBuilder.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ScmStubDownloaderBuilder.java @@ -60,9 +60,10 @@ public final class ScmStubDownloaderBuilder implements StubDownloaderBuilder { return ACCEPTABLE_PROTOCOLS.stream().anyMatch(url::startsWith); } - @Override public StubDownloader build(StubRunnerOptions stubRunnerOptions) { - if (stubRunnerOptions.getStubsMode() == StubRunnerProperties.StubsMode.CLASSPATH || - stubRunnerOptions.getStubRepositoryRoot() == null) { + @Override + public StubDownloader build(StubRunnerOptions stubRunnerOptions) { + if (stubRunnerOptions.getStubsMode() == StubRunnerProperties.StubsMode.CLASSPATH + || stubRunnerOptions.getStubRepositoryRoot() == null) { return null; } Resource resource = stubRunnerOptions.getStubRepositoryRoot(); @@ -72,14 +73,15 @@ public final class ScmStubDownloaderBuilder implements StubDownloaderBuilder { return new GitStubDownloader(stubRunnerOptions); } - @Override public Resource resolve(String location, ResourceLoader resourceLoader) { + @Override + public Resource resolve(String location, ResourceLoader resourceLoader) { if (StringUtils.isEmpty(location) || !isProtocolAccepted(location)) { return null; } return new GitResource(location); } -} +} /** * Primitive version of a Git {@link Resource} @@ -92,17 +94,21 @@ class GitResource extends AbstractResource { this.rawLocation = location; } - @Override public String getDescription() { + @Override + public String getDescription() { return this.rawLocation; } - @Override public InputStream getInputStream() throws IOException { + @Override + public InputStream getInputStream() throws IOException { return null; } - @Override public URI getURI() throws IOException { + @Override + public URI getURI() throws IOException { return URI.create(this.rawLocation); } + } class GitContractsRepo { @@ -120,34 +126,43 @@ class GitContractsRepo { File clonedRepo(Resource repo) { File file = CACHED_LOCATIONS.get(repo); - GitStubDownloaderProperties properties = new GitStubDownloaderProperties(repo, this.options); + GitStubDownloaderProperties properties = new GitStubDownloaderProperties(repo, + this.options); if (file == null) { - File tmpDirWhereStubsWillBeUnzipped = TemporaryFileStorage.createTempDir(TEMP_DIR_PREFIX); + File tmpDirWhereStubsWillBeUnzipped = TemporaryFileStorage + .createTempDir(TEMP_DIR_PREFIX); GitRepo gitRepo = new GitRepo(tmpDirWhereStubsWillBeUnzipped, properties); file = gitRepo.cloneProject(properties.url); gitRepo.checkout(file, properties.branch); CACHED_LOCATIONS.put(repo, file); if (log.isDebugEnabled()) { - log.debug("The project hasn't already been cloned. Cloned it to [" + file + "]"); + log.debug("The project hasn't already been cloned. Cloned it to [" + file + + "]"); } - } else { + } + else { if (log.isDebugEnabled()) { - log.debug("The project has already been cloned to [" + file + "]. Will reset any changes."); + log.debug("The project has already been cloned to [" + file + + "]. Will reset any changes."); } new GitRepo(file, properties).reset(file); } return file; } + } class GitStubDownloader implements StubDownloader { + private static final Log log = LogFactory.getLog(GitStubDownloader.class); // Preloading class for the shutdown hook not to throw ClassNotFound private static final Class CLAZZ = TemporaryFileStorage.class; private final StubRunnerOptions stubRunnerOptions; + private final boolean deleteStubsAfterTest; + private final GitContractsRepo gitContractsRepo; GitStubDownloader(StubRunnerOptions stubRunnerOptions) { @@ -157,48 +172,62 @@ class GitStubDownloader implements StubDownloader { registerShutdownHook(); } - @Override public Map.Entry downloadAndUnpackStubJar( + @Override + public Map.Entry downloadAndUnpackStubJar( StubConfiguration stubConfiguration) { - if (StringUtils.isEmpty(stubConfiguration.version) || "+".equals(stubConfiguration.version)) { - throw new IllegalStateException("Concrete version wasn't passed for [" + stubConfiguration.toColonSeparatedDependencyNotation() + "]"); + if (StringUtils.isEmpty(stubConfiguration.version) + || "+".equals(stubConfiguration.version)) { + throw new IllegalStateException("Concrete version wasn't passed for [" + + stubConfiguration.toColonSeparatedDependencyNotation() + "]"); } try { if (log.isDebugEnabled()) { - log.debug("Trying to find a contract for [" + stubConfiguration.toColonSeparatedDependencyNotation() + "]"); + log.debug("Trying to find a contract for [" + + stubConfiguration.toColonSeparatedDependencyNotation() + "]"); } Resource repo = this.stubRunnerOptions.getStubRepositoryRoot(); File clonedRepo = this.gitContractsRepo.clonedRepo(repo); FileWalker walker = new FileWalker(stubConfiguration); Files.walkFileTree(clonedRepo.toPath(), walker); if (walker.foundFile != null) { - return new AbstractMap.SimpleEntry<>(stubConfiguration, walker.foundFile.toFile()); + return new AbstractMap.SimpleEntry<>(stubConfiguration, + walker.foundFile.toFile()); } } catch (IOException e) { throw new IllegalStateException(e); } if (log.isDebugEnabled()) { - log.debug("No matching contracts were found in the repo for [" + stubConfiguration.toColonSeparatedDependencyNotation() + "]. Returning null"); + log.debug("No matching contracts were found in the repo for [" + + stubConfiguration.toColonSeparatedDependencyNotation() + + "]. Returning null"); } return null; } private void registerShutdownHook() { - Runtime.getRuntime().addShutdownHook(new Thread( - () -> TemporaryFileStorage.cleanup(GitStubDownloader.this.deleteStubsAfterTest))); + Runtime.getRuntime().addShutdownHook(new Thread(() -> TemporaryFileStorage + .cleanup(GitStubDownloader.this.deleteStubsAfterTest))); } + } class GitStubDownloaderProperties { + private static final Log log = LogFactory.getLog(GitStubDownloaderProperties.class); private static final String GIT_BRANCH_PROPERTY = "git.branch"; + private static final String GIT_USERNAME_PROPERTY = "git.username"; + private static final String GIT_PASSWORD_PROPERTY = "git.password"; final URI url; + final String username; + final String password; + final String branch; GitStubDownloaderProperties(Resource repo, StubRunnerOptions options) { @@ -206,24 +235,28 @@ class GitStubDownloaderProperties { Map args = options.getProperties(); try { repoUrl = schemeSpecificPart(repo.getURI()); - } catch (IOException e) { + } + catch (IOException e) { throw new IllegalStateException(e); } // if we had git://https://... we want the part starting from https // if we had git://git@... we want the full address again // if the URL starts with git@... and ends with .git, we want to remove it - String modifiedRepo = repoUrl.startsWith("git@") ? modifyUrlForGitRepo(repoUrl) : repoUrl; + String modifiedRepo = repoUrl.startsWith("git@") ? modifyUrlForGitRepo(repoUrl) + : repoUrl; this.url = URI.create(modifiedRepo); - String username = StubRunnerPropertyUtils.getProperty(args, GIT_USERNAME_PROPERTY); + String username = StubRunnerPropertyUtils.getProperty(args, + GIT_USERNAME_PROPERTY); this.username = StringUtils.hasText(username) ? username : options.getUsername(); - String password = StubRunnerPropertyUtils.getProperty(args, GIT_PASSWORD_PROPERTY); + String password = StubRunnerPropertyUtils.getProperty(args, + GIT_PASSWORD_PROPERTY); this.password = StringUtils.hasText(password) ? password : options.getPassword(); String branch = StubRunnerPropertyUtils.getProperty(args, GIT_BRANCH_PROPERTY); this.branch = StringUtils.hasText(branch) ? branch : "master"; if (log.isDebugEnabled()) { - log.debug("Repo url is [" + repoUrl + "], modified url string " - + "is [" + modifiedRepo + "] URL is [" + this.url + "] and " - + "branch is [" + this.branch + "]"); + log.debug("Repo url is [" + repoUrl + "], modified url string " + "is [" + + modifiedRepo + "] URL is [" + this.url + "] and " + "branch is [" + + this.branch + "]"); } } @@ -238,12 +271,15 @@ class GitStubDownloaderProperties { private String modifyUrlForGitRepo(String gitRepo) { return "git:" + gitRepo; } + } class FileWalker extends SimpleFileVisitor { private final PathMatcher matcherWithDot; + private final PathMatcher matcherWithoutDot; + Path foundFile; FileWalker(StubConfiguration stubConfiguration) { @@ -253,20 +289,21 @@ class FileWalker extends SimpleFileVisitor { .getPathMatcher("glob:" + matcherGlob(stubConfiguration, "/")); } - private String matcherGlob(StubConfiguration stubConfiguration, String groupArtifactSeparator) { + private String matcherGlob(StubConfiguration stubConfiguration, + String groupArtifactSeparator) { return "**" + stubConfiguration.groupId + groupArtifactSeparator - + stubConfiguration.artifactId + "/" - + stubConfiguration.version; + + stubConfiguration.artifactId + "/" + stubConfiguration.version; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - if (this.matcherWithDot.matches(dir.toAbsolutePath()) || - this.matcherWithoutDot.matches(dir.toAbsolutePath())) { + if (this.matcherWithDot.matches(dir.toAbsolutePath()) + || this.matcherWithoutDot.matches(dir.toAbsolutePath())) { this.foundFile = dir; return FileVisitResult.TERMINATE; } return FileVisitResult.CONTINUE; } + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubConfiguration.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubConfiguration.java index 36e070ad56..0ae6cbb333 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubConfiguration.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubConfiguration.java @@ -23,13 +23,18 @@ import org.springframework.util.StringUtils; * groupId:artifactId:version:classifier notation */ public class StubConfiguration { + private static final String STUB_COLON_DELIMITER = ":"; static final String DEFAULT_VERSION = "+"; + public static final String DEFAULT_CLASSIFIER = "stubs"; final String groupId; + final String artifactId; + final String version; + final String classifier; public StubConfiguration(String groupId, String artifactId, String version) { @@ -87,18 +92,16 @@ public class StubConfiguration { } /** - * Returns a colon separated representation of the stub configuration - * (e.g. groupid:artifactid:version:classifier) + * Returns a colon separated representation of the stub configuration (e.g. + * groupid:artifactid:version:classifier) */ public String toColonSeparatedDependencyNotation() { if (!isDefined()) { return ""; } return StringUtils.arrayToDelimitedString( - new String[] { nullCheck(this.groupId), - nullCheck(this.artifactId), - nullCheck(this.version), - nullCheck(this.classifier) }, + new String[] { nullCheck(this.groupId), nullCheck(this.artifactId), + nullCheck(this.version), nullCheck(this.classifier) }, STUB_COLON_DELIMITER); } @@ -108,10 +111,9 @@ public class StubConfiguration { /** * Checks if ivy notation matches group and artifact ids - * * @param ivyNotationAsString - e.g. group:artifact:version:classifier - * @return {@code true} if artifact id matches and there's no group id. Or if - * both group id and artifact id are present and matching + * @return {@code true} if artifact id matches and there's no group id. Or if both + * group id and artifact id are present and matching */ public boolean groupIdAndArtifactMatches(String ivyNotationAsString) { String[] parts = ivyNotationFrom(ivyNotationAsString); @@ -127,8 +129,8 @@ public class StubConfiguration { * Returns {@code true} for a snapshot or a LATEST (+) version */ public boolean isVersionChanging() { - return DEFAULT_VERSION.equals(this.version) || - this.version.toLowerCase().contains("snapshot"); + return DEFAULT_VERSION.equals(this.version) + || this.version.toLowerCase().contains("snapshot"); } public String getGroupId() { @@ -151,7 +153,8 @@ public class StubConfiguration { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((this.artifactId == null) ? 0 : this.artifactId.hashCode()); + result = prime * result + + ((this.artifactId == null) ? 0 : this.artifactId.hashCode()); result = prime * result + ((this.groupId == null) ? 0 : this.groupId.hashCode()); return result; } @@ -185,13 +188,16 @@ public class StubConfiguration { if (strings.length == 1) { return this.artifactId.equals(ivyNotationAsString); } - if (strings.length >= 2 && !(this.groupId.equals(strings[0]) && this.artifactId.equals(strings[1]))) { + if (strings.length >= 2 && !(this.groupId.equals(strings[0]) + && this.artifactId.equals(strings[1]))) { return false; } - if (strings.length >= 3 && !(this.version.equals(strings[2]) || DEFAULT_VERSION.equals(strings[2]))) { + if (strings.length >= 3 && !(this.version.equals(strings[2]) + || DEFAULT_VERSION.equals(strings[2]))) { return false; } - if (strings.length == 4 && !(this.classifier.equals(strings[3]) || DEFAULT_CLASSIFIER.equals(strings[3]))) { + if (strings.length == 4 && !(this.classifier.equals(strings[3]) + || DEFAULT_CLASSIFIER.equals(strings[3]))) { return false; } return true; @@ -210,4 +216,5 @@ public class StubConfiguration { public String toString() { return toColonSeparatedDependencyNotation(); } + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubDownloader.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubDownloader.java index de43747725..57f13be9e1 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubDownloader.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubDownloader.java @@ -20,11 +20,11 @@ import java.io.File; import java.util.Map; /** - * Contract for providing a tuple containing configuration of a downloaded - * and unpacked stub, together with the file location of that extracted artifact. + * Contract for providing a tuple containing configuration of a downloaded and unpacked + * stub, together with the file location of that extracted artifact. * - * Note: Actually the artifact doesn't have to be a JAR. method name contains - * that suffix for historical reasons. + * Note: Actually the artifact doesn't have to be a JAR. method name contains that suffix + * for historical reasons. * * @author Marcin Grzejszczak * @since 1.0.0 @@ -32,8 +32,11 @@ import java.util.Map; public interface StubDownloader { /** - * Returns a mapping of updated StubConfiguration (it will contain the resolved version) and the location of the downloaded JAR. - * If there was no artifact this method will return {@code null}. + * Returns a mapping of updated StubConfiguration (it will contain the resolved + * version) and the location of the downloaded JAR. If there was no artifact this + * method will return {@code null}. */ - Map.Entry downloadAndUnpackStubJar(StubConfiguration stubConfiguration); + Map.Entry downloadAndUnpackStubJar( + StubConfiguration stubConfiguration); + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubDownloaderBuilder.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubDownloaderBuilder.java index ea9e72cc8f..112aa9e9bd 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubDownloaderBuilder.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubDownloaderBuilder.java @@ -21,14 +21,14 @@ import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; /** - * Builder for a {@link StubDownloader}. Can't allow direct usage - * of {@link StubDownloader} cause in order to register instances - * of this interface in {@link org.springframework.core.io.support.SpringFactoriesLoader} - * one needs a default constructor whereas the {@link StubDownloader} - * instances need to be constructed from stub related options. + * Builder for a {@link StubDownloader}. Can't allow direct usage of + * {@link StubDownloader} cause in order to register instances of this interface in + * {@link org.springframework.core.io.support.SpringFactoriesLoader} one needs a default + * constructor whereas the {@link StubDownloader} instances need to be constructed from + * stub related options. * - * Since {@code 2.0.0} extends {@link ProtocolResolver}. Implementations have - * to tell Spring how to parse the repository root String into a resource. + * Since {@code 2.0.0} extends {@link ProtocolResolver}. Implementations have to tell + * Spring how to parse the repository root String into a resource. * * @author Marcin Grzejszczak * @since 1.1.0 @@ -36,11 +36,14 @@ import org.springframework.core.io.ResourceLoader; public interface StubDownloaderBuilder extends ProtocolResolver { /** - * @return {@link StubDownloader} instance of {@code null} if current parameters don't allow building the instance + * @return {@link StubDownloader} instance of {@code null} if current parameters don't + * allow building the instance */ StubDownloader build(StubRunnerOptions stubRunnerOptions); - @Override default Resource resolve(String location, ResourceLoader resourceLoader) { + @Override + default Resource resolve(String location, ResourceLoader resourceLoader) { return null; } + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubDownloaderBuilderProvider.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubDownloaderBuilderProvider.java index 646db2f403..b8b731b740 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubDownloaderBuilderProvider.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubDownloaderBuilderProvider.java @@ -7,8 +7,8 @@ import java.util.List; import org.springframework.core.io.support.SpringFactoriesLoader; /** - * Provider for {@link StubDownloaderBuilder}. It can also pick a default - * downloader if none is provided + * Provider for {@link StubDownloaderBuilder}. It can also pick a default downloader if + * none is provided * * @author Marcin Grzejszczak * @since 1.1.0 @@ -28,8 +28,10 @@ public class StubDownloaderBuilderProvider { /** * @param stubRunnerOptions - * @param additionalBuilders - optional array of {@link StubDownloaderBuilder}s to append to the list of builders - * @return composite {@link StubDownloader} that iterates over a list of stub downloaders + * @param additionalBuilders - optional array of {@link StubDownloaderBuilder}s to + * append to the list of builders + * @return composite {@link StubDownloader} that iterates over a list of stub + * downloaders */ public StubDownloader get(StubRunnerOptions stubRunnerOptions, StubDownloaderBuilder... additionalBuilders) { @@ -43,8 +45,8 @@ public class StubDownloaderBuilderProvider { } List defaultStubDownloaderBuilders() { - return Arrays - .asList(new ScmStubDownloaderBuilder(), new ClasspathStubProvider(), - new AetherStubDownloaderBuilder()); + return Arrays.asList(new ScmStubDownloaderBuilder(), new ClasspathStubProvider(), + new AetherStubDownloaderBuilder()); } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubFinder.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubFinder.java index 09e6c00858..b911679803 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubFinder.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubFinder.java @@ -23,19 +23,20 @@ import java.util.Map; import org.springframework.cloud.contract.spec.Contract; public interface StubFinder extends StubTrigger { + /** - * For the given groupId and artifactId tries to find the matching - * URL of the running stub. - * - * @param groupId - might be null. In that case a search only via artifactId takes place + * For the given groupId and artifactId tries to find the matching URL of the running + * stub. + * @param groupId - might be null. In that case a search only via artifactId takes + * place * @return URL of a running stub or throws exception if not found */ URL findStubUrl(String groupId, String artifactId) throws StubNotFoundException; /** - * For the given Ivy notation {@code [groupId]:artifactId:[version]:[classifier]} tries to - * find the matching URL of the running stub. You can also pass only {@code artifactId}. - * + * For the given Ivy notation {@code [groupId]:artifactId:[version]:[classifier]} + * tries to find the matching URL of the running stub. You can also pass only + * {@code artifactId}. * @param ivyNotation - Ivy representation of the Maven artifact * @return URL of a running stub or throws exception if not found */ @@ -50,4 +51,5 @@ public interface StubFinder extends StubTrigger { * Returns the list of Contracts */ Map> getContracts(); + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubNotFoundException.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubNotFoundException.java index 4835d2be0e..6a4f1e68ba 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubNotFoundException.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubNotFoundException.java @@ -9,10 +9,12 @@ package org.springframework.cloud.contract.stubrunner; public class StubNotFoundException extends RuntimeException { public StubNotFoundException(String groupId, String artifactId) { - super("Stub not found for groupid [" + groupId + "] and artifactid [" + artifactId + "]"); + super("Stub not found for groupid [" + groupId + "] and artifactid [" + artifactId + + "]"); } public StubNotFoundException(String ivyNotation) { super("Stub not found for stub with notation [" + ivyNotation + "]"); } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRepository.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRepository.java index 7a477b8d06..1b1c660882 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRepository.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRepository.java @@ -46,10 +46,15 @@ class StubRepository { private static final Log log = LogFactory.getLog(StubRepository.class); private final File path; + final List stubs; + final Collection contracts; + private final List contractConverters; + private final List httpServerStubs; + private final StubRunnerOptions options; StubRepository(File repository, List httpServerStubs, @@ -58,9 +63,11 @@ class StubRepository { throw new IllegalArgumentException( "Missing descriptor repository under path [" + repository + "]"); } - this.contractConverters = SpringFactoriesLoader.loadFactories(ContractConverter.class, null); + this.contractConverters = SpringFactoriesLoader + .loadFactories(ContractConverter.class, null); if (log.isTraceEnabled()) { - log.trace("Found the following contract converters " + this.contractConverters); + log.trace( + "Found the following contract converters " + this.contractConverters); } this.httpServerStubs = httpServerStubs; this.path = repository; @@ -107,8 +114,7 @@ class StubRepository { : Collections.emptyList(); } - private List collectMappings( - File descriptorsDirectory) { + private List collectMappings(File descriptorsDirectory) { final List mappingDescriptors = new ArrayList<>(); try { Files.walkFileTree(Paths.get(descriptorsDirectory.toURI()), @@ -117,7 +123,8 @@ class StubRepository { public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { File file = path.toFile(); - if (httpServerStubAccepts(file) && isStubPerConsumerPathMatching(file)) { + if (httpServerStubAccepts(file) + && isStubPerConsumerPathMatching(file)) { mappingDescriptors.add(file); } return super.visitFile(path, attrs); @@ -155,7 +162,8 @@ class StubRepository { } @SuppressWarnings("unchecked") - private Collection collectContractDescriptors(final File descriptorsDirectory) { + private Collection collectContractDescriptors( + final File descriptorsDirectory) { final List contractDescriptors = new ArrayList<>(); try { Files.walkFileTree(Paths.get(descriptorsDirectory.toURI()), @@ -168,11 +176,20 @@ class StubRepository { if (isStubPerConsumerPathMatching(file)) { if (isContractDescriptor(file)) { contractDescriptors - .addAll(ContractVerifierDslConverter.convertAsCollection(file.getParentFile(), file)); - } else if (converter != null && converter.isAccepted(file)) { - contractDescriptors.addAll(converter.convertFrom(file)); - } else if (YamlContractConverter.INSTANCE.isAccepted(file)) { - contractDescriptors.addAll(YamlContractConverter.INSTANCE.convertFrom(file)); + .addAll(ContractVerifierDslConverter + .convertAsCollection( + file.getParentFile(), file)); + } + else if (converter != null + && converter.isAccepted(file)) { + contractDescriptors + .addAll(converter.convertFrom(file)); + } + else if (YamlContractConverter.INSTANCE + .isAccepted(file)) { + contractDescriptors + .addAll(YamlContractConverter.INSTANCE + .convertFrom(file)); } } return super.visitFile(path, attrs); @@ -194,7 +211,9 @@ class StubRepository { String absolutePath = file.getAbsolutePath(); boolean stubPerConsumerMatching = absolutePath.contains(searchedConsumerName); if (log.isDebugEnabled()) { - log.debug("Absolute path [" + absolutePath + "] contains [" + searchedConsumerName + "] in its path [" + stubPerConsumerMatching + "]"); + log.debug("Absolute path [" + absolutePath + "] contains [" + + searchedConsumerName + "] in its path [" + stubPerConsumerMatching + + "]"); } return stubPerConsumerMatching; } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunner.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunner.java index 0285672bcb..db7f237ca6 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunner.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunner.java @@ -44,8 +44,11 @@ public class StubRunner implements StubRunning { private static final Log log = LogFactory.getLog(StubRunner.class); private final StubRepository stubRepository; + private final StubConfiguration stubsConfiguration; + private final StubRunnerOptions stubRunnerOptions; + private final StubRunnerExecutor localStubRunner; public StubRunner(StubRunnerOptions stubRunnerOptions, String repositoryPath, @@ -59,31 +62,40 @@ public class StubRunner implements StubRunning { MessageVerifier contractVerifierMessaging) { this.stubsConfiguration = stubsConfiguration; this.stubRunnerOptions = stubRunnerOptions; - List serverStubs = SpringFactoriesLoader.loadFactories(HttpServerStub.class, null); - this.stubRepository = new StubRepository(new File(repositoryPath), serverStubs, this.stubRunnerOptions); + List serverStubs = SpringFactoriesLoader + .loadFactories(HttpServerStub.class, null); + this.stubRepository = new StubRepository(new File(repositoryPath), serverStubs, + this.stubRunnerOptions); AvailablePortScanner portScanner = new AvailablePortScanner( stubRunnerOptions.getMinPortValue(), stubRunnerOptions.getMaxPortValue()); - this.localStubRunner = new StubRunnerExecutor(portScanner, contractVerifierMessaging, serverStubs); + this.localStubRunner = new StubRunnerExecutor(portScanner, + contractVerifierMessaging, serverStubs); } @Override public RunningStubs runStubs() { registerShutdownHook(); - RunningStubs stubs = this.localStubRunner.runStubs(this.stubRunnerOptions, this.stubRepository, - this.stubsConfiguration); + RunningStubs stubs = this.localStubRunner.runStubs(this.stubRunnerOptions, + this.stubRepository, this.stubsConfiguration); if (this.stubRunnerOptions.hasMappingsOutputFolder()) { String registeredMappings = this.localStubRunner.registeredMappings(); if (StringUtils.hasText(registeredMappings)) { - File outputMappings = new File(this.stubRunnerOptions.getMappingsOutputFolder(), + File outputMappings = new File( + this.stubRunnerOptions.getMappingsOutputFolder(), this.stubsConfiguration.artifactId + "_" - + stubs.getPort(this.stubsConfiguration.toColonSeparatedDependencyNotation())); + + stubs.getPort(this.stubsConfiguration + .toColonSeparatedDependencyNotation())); try { outputMappings.getParentFile().mkdirs(); - clearOldFiles(outputMappings.getParentFile(), this.stubsConfiguration.artifactId); + clearOldFiles(outputMappings.getParentFile(), + this.stubsConfiguration.artifactId); outputMappings.createNewFile(); - Files.write(Paths.get(outputMappings.toURI()), registeredMappings.getBytes()); + Files.write(Paths.get(outputMappings.toURI()), + registeredMappings.getBytes()); if (log.isDebugEnabled()) { - log.debug("Stored the mappings for artifactid [" + this.stubsConfiguration.artifactId + "] at [" + outputMappings + "] location"); + log.debug("Stored the mappings for artifactid [" + + this.stubsConfiguration.artifactId + "] at [" + + outputMappings + "] location"); } } catch (IOException e) { @@ -97,20 +109,22 @@ public class StubRunner implements StubRunning { private void clearOldFiles(File outputFolder, final String filename) { File[] files = outputFolder.listFiles(new FilenameFilter() { - @Override public boolean accept(final File dir, final String name) { + @Override + public boolean accept(final File dir, final String name) { return name.startsWith(filename); } }); if (files == null) { - if(log.isDebugEnabled()) { + if (log.isDebugEnabled()) { log.debug("Failed to retrieve any mappings"); } return; } for (final File file : files) { if (!file.delete()) { - if(log.isDebugEnabled()) { - log.debug("Exception occurred while trying to remove [" + file.getAbsolutePath() + "]"); + if (log.isDebugEnabled()) { + log.debug("Exception occurred while trying to remove [" + + file.getAbsolutePath() + "]"); } } } @@ -176,4 +190,5 @@ public class StubRunner implements StubRunning { this.localStubRunner.shutdown(); } } + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerExecutor.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerExecutor.java index 19e4ba0a58..514eaf9a8c 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerExecutor.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerExecutor.java @@ -51,17 +51,23 @@ class StubRunnerExecutor implements StubFinder { static final Set STUB_SERVERS = new ConcurrentHashSet<>(); private final AvailablePortScanner portScanner; + private final MessageVerifier contractVerifierMessaging; + private StubServer stubServer; + private final List serverStubs; - StubRunnerExecutor(AvailablePortScanner portScanner, MessageVerifier contractVerifierMessaging, List serverStubs) { + StubRunnerExecutor(AvailablePortScanner portScanner, + MessageVerifier contractVerifierMessaging, + List serverStubs) { this.portScanner = portScanner; this.contractVerifierMessaging = contractVerifierMessaging; this.serverStubs = serverStubs; } - StubRunnerExecutor(AvailablePortScanner portScanner, List serverStubs) { + StubRunnerExecutor(AvailablePortScanner portScanner, + List serverStubs) { this(portScanner, new NoOpStubMessages(), serverStubs); } @@ -69,12 +75,12 @@ class StubRunnerExecutor implements StubFinder { this(portScanner, new NoOpStubMessages(), new ArrayList()); } - public RunningStubs runStubs(StubRunnerOptions stubRunnerOptions, StubRepository repository, - StubConfiguration stubConfiguration) { + public RunningStubs runStubs(StubRunnerOptions stubRunnerOptions, + StubRepository repository, StubConfiguration stubConfiguration) { if (this.stubServer != null) { if (log.isDebugEnabled()) { - log.debug("Returning cached version of stubs [" + stubConfiguration.toColonSeparatedDependencyNotation() - + "]"); + log.debug("Returning cached version of stubs [" + + stubConfiguration.toColonSeparatedDependencyNotation() + "]"); } return runningStubs(); } @@ -85,8 +91,8 @@ class StubRunnerExecutor implements StubFinder { } private RunningStubs runningStubs() { - return new RunningStubs( - Collections.singletonMap(this.stubServer.getStubConfiguration(), this.stubServer.getPort())); + return new RunningStubs(Collections.singletonMap( + this.stubServer.getStubConfiguration(), this.stubServer.getPort())); } public void shutdown() { @@ -103,11 +109,13 @@ class StubRunnerExecutor implements StubFinder { public URL findStubUrl(String groupId, String artifactId) { URL url = null; if (groupId == null) { - url = findStubUrl(this.stubServer.stubConfiguration.artifactId.equals(artifactId)); + url = findStubUrl( + this.stubServer.stubConfiguration.artifactId.equals(artifactId)); } if (url == null) { - url = findStubUrl(this.stubServer.stubConfiguration.artifactId.equals(artifactId) - && this.stubServer.stubConfiguration.groupId.equals(groupId)); + url = findStubUrl( + this.stubServer.stubConfiguration.artifactId.equals(artifactId) + && this.stubServer.stubConfiguration.groupId.equals(groupId)); } if (url == null) { throw new StubNotFoundException(groupId, artifactId); @@ -119,8 +127,8 @@ class StubRunnerExecutor implements StubFinder { public URL findStubUrl(String ivyNotation) { String[] splitString = ivyNotation.split(":", -1); if (splitString.length > 4) { - throw new IllegalArgumentException( - "[" + ivyNotation + "] is an invalid notation. Pass [groupId]:artifactId[:version][:classifier]."); + throw new IllegalArgumentException("[" + ivyNotation + + "] is an invalid notation. Pass [groupId]:artifactId[:version][:classifier]."); } else if (splitString.length == 1) { return findStubUrl(null, splitString[0]); @@ -131,7 +139,8 @@ class StubRunnerExecutor implements StubFinder { else if (splitString.length == 3) { return findStubUrl(groupIdArtifactVersionMatches(splitString)); } - return findStubUrl(groupIdArtifactVersionMatches(splitString) && classifierMatches(splitString)); + return findStubUrl(groupIdArtifactVersionMatches(splitString) + && classifierMatches(splitString)); } private boolean classifierMatches(String[] splitString) { @@ -150,18 +159,21 @@ class StubRunnerExecutor implements StubFinder { @Override public RunningStubs findAllRunningStubs() { - return new RunningStubs(Collections.singletonMap(this.stubServer.stubConfiguration, this.stubServer.getPort())); + return new RunningStubs(Collections.singletonMap( + this.stubServer.stubConfiguration, this.stubServer.getPort())); } @Override public Map> getContracts() { - return Collections.singletonMap(this.stubServer.stubConfiguration, this.stubServer.getContracts()); + return Collections.singletonMap(this.stubServer.stubConfiguration, + this.stubServer.getContracts()); } @Override public boolean trigger(String ivyNotationAsString, String labelName) { Collection matchingContracts = new ArrayList<>(); - for (Entry> it : getContracts().entrySet()) { + for (Entry> it : getContracts() + .entrySet()) { if (it.getKey().groupIdAndArtifactMatches(ivyNotationAsString)) { matchingContracts.addAll(it.getValue()); } @@ -181,7 +193,8 @@ class StubRunnerExecutor implements StubFinder { private boolean triggerForDsls(Collection dsls, String labelName) { Collection matchingDsls = new ArrayList<>(); for (Contract contract : dsls) { - if (labelName.equals(contract.getLabel()) && contract.getOutputMessage() != null) { + if (labelName.equals(contract.getLabel()) + && contract.getOutputMessage() != null) { matchingDsls.add(contract); } } @@ -216,7 +229,8 @@ class StubRunnerExecutor implements StubFinder { @Override public Map> labels() { Map> labels = new LinkedHashMap<>(); - for (Entry> it : getContracts().entrySet()) { + for (Entry> it : getContracts() + .entrySet()) { Collection values = new ArrayList<>(); for (Contract contract : it.getValue()) { if (contract.getLabel() != null) { @@ -233,17 +247,18 @@ class StubRunnerExecutor implements StubFinder { DslProperty body = outputMessage.getBody(); Headers headers = outputMessage.getHeaders(); this.contractVerifierMessaging.send( - JsonOutput - .toJson(BodyExtractor.extractClientValueFromBody(body == null ? null : body.getClientValue())), - headers == null ? null : headers.asStubSideMap(), outputMessage.getSentTo().getClientValue()); + JsonOutput.toJson(BodyExtractor.extractClientValueFromBody( + body == null ? null : body.getClientValue())), + headers == null ? null : headers.asStubSideMap(), + outputMessage.getSentTo().getClientValue()); } private URL returnStubUrlIfMatches(boolean condition) { return condition ? this.stubServer.getStubUrl() : null; } - private void startStubServers(final StubRunnerOptions stubRunnerOptions, final StubConfiguration stubConfiguration, - StubRepository repository) { + private void startStubServers(final StubRunnerOptions stubRunnerOptions, + final StubConfiguration stubConfiguration, StubRepository repository) { final List mappings = repository.getStubs(); final Collection contracts = repository.contracts; Integer port = stubRunnerOptions.port(stubConfiguration); @@ -251,20 +266,23 @@ class StubRunnerExecutor implements StubFinder { if (log.isDebugEnabled()) { log.debug("There are no HTTP related contracts. Won't start any servers"); } - this.stubServer = new StubServer(stubConfiguration, mappings, contracts, new NoOpHttpServerStub()).start(); + this.stubServer = new StubServer(stubConfiguration, mappings, contracts, + new NoOpHttpServerStub()).start(); return; } if (port != null && port >= 0) { - this.stubServer = new StubServer(stubConfiguration, mappings, contracts, httpServerStub()).start(port); + this.stubServer = new StubServer(stubConfiguration, mappings, contracts, + httpServerStub()).start(port); } else { - this.stubServer = this.portScanner.tryToExecuteWithFreePort(new PortCallback() { - @Override - public StubServer call(int availablePort) { - return new StubServer(stubConfiguration, mappings, contracts, - httpServerStub()).start(availablePort); - } - }); + this.stubServer = this.portScanner + .tryToExecuteWithFreePort(new PortCallback() { + @Override + public StubServer call(int availablePort) { + return new StubServer(stubConfiguration, mappings, contracts, + httpServerStub()).start(availablePort); + } + }); } STUB_SERVERS.add(this.stubServer); } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerFactory.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerFactory.java index 6d82968d34..b3aeb65624 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerFactory.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerFactory.java @@ -32,15 +32,17 @@ import org.springframework.cloud.contract.verifier.messaging.MessageVerifier; */ class StubRunnerFactory { - private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); + private static final Log log = LogFactory + .getLog(MethodHandles.lookup().lookupClass()); private final StubRunnerOptions stubRunnerOptions; + private final StubDownloader stubDownloader; + private final MessageVerifier contractVerifierMessaging; public StubRunnerFactory(StubRunnerOptions stubRunnerOptions, - StubDownloader stubDownloader, - MessageVerifier contractVerifierMessaging) { + StubDownloader stubDownloader, MessageVerifier contractVerifierMessaging) { this.stubRunnerOptions = stubRunnerOptions; this.stubDownloader = stubDownloader; this.contractVerifierMessaging = contractVerifierMessaging; @@ -48,18 +50,22 @@ class StubRunnerFactory { public Collection createStubsFromServiceConfiguration() { if (log.isDebugEnabled()) { - log.debug("Will download stubs for dependencies " + this.stubRunnerOptions.getDependencies()); + log.debug("Will download stubs for dependencies " + + this.stubRunnerOptions.getDependencies()); } if (this.stubRunnerOptions.getDependencies().isEmpty()) { - log.warn("No stubs to download have been passed. Most likely you have forgotten to pass " - + "them either via annotation or a property"); + log.warn( + "No stubs to download have been passed. Most likely you have forgotten to pass " + + "them either via annotation or a property"); } Collection result = new ArrayList<>(); - for (StubConfiguration stubsConfiguration : this.stubRunnerOptions.getDependencies()) { + for (StubConfiguration stubsConfiguration : this.stubRunnerOptions + .getDependencies()) { Map.Entry entry = this.stubDownloader .downloadAndUnpackStubJar(stubsConfiguration); if (log.isDebugEnabled()) { - log.debug("For stub configuration [" + stubsConfiguration + "] the downloaded entry is [" + entry + "]"); + log.debug("For stub configuration [" + stubsConfiguration + + "] the downloaded entry is [" + entry + "]"); } if (entry != null) { result.add(createStubRunner(entry.getKey(), entry.getValue())); @@ -74,7 +80,8 @@ class StubRunnerFactory { if (unzipedStubDir == null) { return null; } - return createStubRunner(unzipedStubDir, stubsConfiguration, this.stubRunnerOptions); + return createStubRunner(unzipedStubDir, stubsConfiguration, + this.stubRunnerOptions); } private StubRunner createStubRunner(File unzippedStubsDir, diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerMain.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerMain.java index 587d490c78..29559852fb 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerMain.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerMain.java @@ -41,49 +41,55 @@ public class StubRunnerMain { private StubRunnerMain(String[] args) throws Exception { OptionParser parser = new OptionParser(); try { - ArgumentAcceptingOptionSpec minPortValueOpt = parser - .acceptsAll(Arrays.asList("minp", "minPort"), - "Minimum port value to be assigned to the WireMock instance. Defaults to 10000") + ArgumentAcceptingOptionSpec minPortValueOpt = parser.acceptsAll( + Arrays.asList("minp", "minPort"), + "Minimum port value to be assigned to the WireMock instance. Defaults to 10000") .withRequiredArg().ofType(Integer.class).defaultsTo(10000); - ArgumentAcceptingOptionSpec maxPortValueOpt = parser - .acceptsAll(Arrays.asList("maxp", "maxPort"), - "Maximum port value to be assigned to the WireMock instance. Defaults to 15000") + ArgumentAcceptingOptionSpec maxPortValueOpt = parser.acceptsAll( + Arrays.asList("maxp", "maxPort"), + "Maximum port value to be assigned to the WireMock instance. Defaults to 15000") .withRequiredArg().ofType(Integer.class).defaultsTo(15000); - ArgumentAcceptingOptionSpec stubsOpt = parser - .acceptsAll(Arrays.asList("s", "stubs"), - "Comma separated list of Ivy representation of jars with stubs. Eg. groupid:artifactid1,groupid2:artifactid2:classifier") + ArgumentAcceptingOptionSpec stubsOpt = parser.acceptsAll( + Arrays.asList("s", "stubs"), + "Comma separated list of Ivy representation of jars with stubs. Eg. groupid:artifactid1,groupid2:artifactid2:classifier") .withRequiredArg(); - ArgumentAcceptingOptionSpec classifierOpt = parser - .acceptsAll(Arrays.asList("c", "classifier"), - "Suffix for the jar containing stubs (e.g. 'stubs' if the stub jar would have a 'stubs' classifier for stubs: foobar-stubs ). Defaults to 'stubs'") + ArgumentAcceptingOptionSpec classifierOpt = parser.acceptsAll( + Arrays.asList("c", "classifier"), + "Suffix for the jar containing stubs (e.g. 'stubs' if the stub jar would have a 'stubs' classifier for stubs: foobar-stubs ). Defaults to 'stubs'") .withRequiredArg().defaultsTo("stubs"); - ArgumentAcceptingOptionSpec rootOpt = parser - .acceptsAll(Arrays.asList("r", "root"),"Location of a Jar containing server where you keep your stubs (e.g. http://nexus.net/content/repositories/repository)") + ArgumentAcceptingOptionSpec rootOpt = parser.acceptsAll( + Arrays.asList("r", "root"), + "Location of a Jar containing server where you keep your stubs (e.g. http://nexus.net/content/repositories/repository)") .withRequiredArg(); ArgumentAcceptingOptionSpec usernameOpt = parser - .acceptsAll(Arrays.asList("u", "username"),"Username to user when connecting to repository") + .acceptsAll(Arrays.asList("u", "username"), + "Username to user when connecting to repository") .withOptionalArg(); ArgumentAcceptingOptionSpec passwordOpt = parser - .acceptsAll(Arrays.asList("p", "password"),"Password to user when connecting to repository") + .acceptsAll(Arrays.asList("p", "password"), + "Password to user when connecting to repository") .withOptionalArg(); ArgumentAcceptingOptionSpec proxyHostOpt = parser - .acceptsAll(Arrays.asList("phost", "proxyHost"),"Proxy host to use for repository requests") + .acceptsAll(Arrays.asList("phost", "proxyHost"), + "Proxy host to use for repository requests") .withOptionalArg(); ArgumentAcceptingOptionSpec proxyPortOpt = parser - .acceptsAll(Arrays.asList("pport", "proxyPort"),"Proxy port to use for repository requests") - .withOptionalArg() - .ofType(Integer.class); + .acceptsAll(Arrays.asList("pport", "proxyPort"), + "Proxy port to use for repository requests") + .withOptionalArg().ofType(Integer.class); ArgumentAcceptingOptionSpec stubsMode = parser - .acceptsAll(Arrays.asList("sm", "stubsMode"),"Stubs mode to be used. Acceptable values " + Arrays - .toString(StubRunnerProperties.StubsMode.values())) - .withRequiredArg().defaultsTo(StubRunnerProperties.StubsMode.CLASSPATH.toString()); + .acceptsAll(Arrays.asList("sm", "stubsMode"), + "Stubs mode to be used. Acceptable values " + Arrays + .toString(StubRunnerProperties.StubsMode.values())) + .withRequiredArg() + .defaultsTo(StubRunnerProperties.StubsMode.CLASSPATH.toString()); OptionSet options = parser.parse(args); String stubs = options.valueOf(stubsOpt); - StubRunnerProperties.StubsMode stubsModeValue = StubRunnerProperties.StubsMode.valueOf( - options.valueOf(stubsMode)); + StubRunnerProperties.StubsMode stubsModeValue = StubRunnerProperties.StubsMode + .valueOf(options.valueOf(stubsMode)); Integer minPortValue = options.valueOf(minPortValueOpt); Integer maxPortValue = options.valueOf(maxPortValueOpt); - String stubRepositoryRoot= options.valueOf(rootOpt); + String stubRepositoryRoot = options.valueOf(rootOpt); String stubsSuffix = options.valueOf(classifierOpt); final String username = options.valueOf(usernameOpt); final String password = options.valueOf(passwordOpt); @@ -93,9 +99,7 @@ public class StubRunnerMain { .withMinMaxPort(minPortValue, maxPortValue) .withStubRepositoryRoot(stubRepositoryRoot) .withStubsMode(stubsModeValue).withStubsClassifier(stubsSuffix) - .withUsername(username) - .withPassword(password) - .withStubs(stubs); + .withUsername(username).withPassword(password).withStubs(stubs); if (proxyHost != null) { builder.withProxy(proxyHost, proxyPort); } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerOptions.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerOptions.java index b7569140f5..6afca207c0 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerOptions.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerOptions.java @@ -94,35 +94,38 @@ public class StubRunnerOptions { private String consumerName; /** - * For debugging purposes you can output the registered mappings to a given folder. Each HTTP server - * stub will have its own subfolder where all the mappings will get stored. + * For debugging purposes you can output the registered mappings to a given folder. + * Each HTTP server stub will have its own subfolder where all the mappings will get + * stored. */ private String mappingsOutputFolder; final StubRunnerProperties.StubsMode stubsMode; /** - * If set to {@code false} will NOT delete stubs from a temporary - * folder after running tests + * If set to {@code false} will NOT delete stubs from a temporary folder after running + * tests */ private boolean deleteStubsAfterTest; /** - * Map of properties that can be passed to custom {@link org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder} + * Map of properties that can be passed to custom + * {@link org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder} */ private Map properties = new HashMap<>(); StubRunnerOptions(Integer minPortValue, Integer maxPortValue, - Resource stubRepositoryRoot, StubRunnerProperties.StubsMode stubsMode, String stubsClassifier, - Collection dependencies, - Map stubIdsToPortMapping, - String username, String password, final StubRunnerProxyOptions stubRunnerProxyOptions, + Resource stubRepositoryRoot, StubRunnerProperties.StubsMode stubsMode, + String stubsClassifier, Collection dependencies, + Map stubIdsToPortMapping, String username, + String password, final StubRunnerProxyOptions stubRunnerProxyOptions, boolean stubsPerConsumer, String consumerName, String mappingsOutputFolder, boolean deleteStubsAfterTest, Map properties) { this.minPortValue = minPortValue; this.maxPortValue = maxPortValue; this.stubRepositoryRoot = stubRepositoryRoot; - this.stubsMode = stubsMode != null ? stubsMode : StubRunnerProperties.StubsMode.CLASSPATH; + this.stubsMode = stubsMode != null ? stubsMode + : StubRunnerProperties.StubsMode.CLASSPATH; this.stubsClassifier = stubsClassifier; this.dependencies = dependencies; this.stubIdsToPortMapping = stubIdsToPortMapping; @@ -147,8 +150,10 @@ public class StubRunnerOptions { public static StubRunnerOptions fromSystemProps() { StubRunnerOptionsBuilder builder = new StubRunnerOptionsBuilder() - .withMinPort(Integer.valueOf(System.getProperty("stubrunner.port.range.min", "10000"))) - .withMaxPort(Integer.valueOf(System.getProperty("stubrunner.port.range.max", "15000"))) + .withMinPort(Integer.valueOf( + System.getProperty("stubrunner.port.range.min", "10000"))) + .withMaxPort(Integer.valueOf( + System.getProperty("stubrunner.port.range.max", "15000"))) .withStubRepositoryRoot(ResourceResolver .resource(System.getProperty("stubrunner.repository.root", ""))) .withStubsMode(System.getProperty("stubrunner.stubs-mode", "LOCAL")) @@ -156,14 +161,18 @@ public class StubRunnerOptions { .withStubs(System.getProperty("stubrunner.ids", "")) .withUsername(System.getProperty("stubrunner.username")) .withPassword(System.getProperty("stubrunner.password")) - .withStubPerConsumer(Boolean.parseBoolean(System.getProperty("stubrunner.stubs-per-consumer", "false"))) + .withStubPerConsumer(Boolean.parseBoolean( + System.getProperty("stubrunner.stubs-per-consumer", "false"))) .withConsumerName(System.getProperty("stubrunner.consumer-name")) - .withMappingsOutputFolder(System.getProperty("stubrunner.mappings-output-folder")) - .withDeleteStubsAfterTest(Boolean.parseBoolean(System.getProperty("stubrunner.delete-stubs-after-test", "true"))) + .withMappingsOutputFolder( + System.getProperty("stubrunner.mappings-output-folder")) + .withDeleteStubsAfterTest(Boolean.parseBoolean( + System.getProperty("stubrunner.delete-stubs-after-test", "true"))) .withProperties(stubRunnerProps()); String proxyHost = System.getProperty("stubrunner.proxy.host"); if (proxyHost != null) { - builder.withProxy(proxyHost, Integer.parseInt(System.getProperty("stubrunner.proxy.port"))); + builder.withProxy(proxyHost, + Integer.parseInt(System.getProperty("stubrunner.proxy.port"))); } return builder.build(); } @@ -172,12 +181,12 @@ public class StubRunnerOptions { Map map = new HashMap<>(); Properties properties = System.getProperties(); Set propertyNames = properties.stringPropertyNames(); - propertyNames - .stream() + propertyNames.stream() // stubrunner.properties.foo.bar=baz .filter(s -> s.toLowerCase().startsWith("stubrunner.properties")) // foo.bar=baz - .forEach(s -> map.put(s.substring("stubrunner.properties".length() + 1), System.getProperty(s))); + .forEach(s -> map.put(s.substring("stubrunner.properties".length() + 1), + System.getProperty(s))); return map; } @@ -287,6 +296,7 @@ public class StubRunnerOptions { public static class StubRunnerProxyOptions { private final String proxyHost; + private final int proxyPort; public StubRunnerProxyOptions(final String proxyHost, final int proxyPort) { @@ -302,25 +312,30 @@ public class StubRunnerOptions { return this.proxyPort; } - @Override public String toString() { + @Override + public String toString() { return "StubRunnerProxyOptions{" + "proxyHost='" + this.proxyHost + '\'' + ", proxyPort=" + this.proxyPort + '}'; } + } - @Override public String toString() { - return "StubRunnerOptions{" + "minPortValue=" + this.minPortValue + ", maxPortValue=" - + this.maxPortValue + ", stubRepositoryRoot='" + this.stubRepositoryRoot + '\'' - + ", stubsMode='" + this.stubsMode + "', stubsClassifier='" + this.stubsClassifier - + '\'' + ", dependencies=" + this.dependencies + ", stubIdsToPortMapping=" - + this.stubIdsToPortMapping + ", username='" + obfuscate(this.username) + '\'' + ", password='" - + obfuscate(this.password) + '\'' + ", stubRunnerProxyOptions='" + this.stubRunnerProxyOptions + "', stubsPerConsumer='" - + this.stubsPerConsumer - + '\'' + ", stubsPerConsumer='" + this.stubsPerConsumer + '\'' - + '}'; + @Override + public String toString() { + return "StubRunnerOptions{" + "minPortValue=" + this.minPortValue + + ", maxPortValue=" + this.maxPortValue + ", stubRepositoryRoot='" + + this.stubRepositoryRoot + '\'' + ", stubsMode='" + this.stubsMode + + "', stubsClassifier='" + this.stubsClassifier + '\'' + ", dependencies=" + + this.dependencies + ", stubIdsToPortMapping=" + + this.stubIdsToPortMapping + ", username='" + obfuscate(this.username) + + '\'' + ", password='" + obfuscate(this.password) + '\'' + + ", stubRunnerProxyOptions='" + this.stubRunnerProxyOptions + + "', stubsPerConsumer='" + this.stubsPerConsumer + '\'' + + ", stubsPerConsumer='" + this.stubsPerConsumer + '\'' + '}'; } private String obfuscate(String string) { return StringUtils.hasText(string) ? "****" : ""; } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerOptionsBuilder.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerOptionsBuilder.java index 5d60221106..097eaed7e4 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerOptionsBuilder.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerOptionsBuilder.java @@ -33,22 +33,37 @@ import org.springframework.util.StringUtils; public class StubRunnerOptionsBuilder { private static final String DELIMITER = ":"; + private LinkedList stubs = new LinkedList<>(); + private Collection stubConfigurations = new ArrayList<>(); + private Map stubIdsToPortMapping = new LinkedHashMap<>(); private Integer minPortValue = 10000; + private Integer maxPortValue = 15000; + private Resource stubRepositoryRoot; + private String stubsClassifier = "stubs"; + private String username; + private String password; + private StubRunnerOptions.StubRunnerProxyOptions stubRunnerProxyOptions; + private boolean stubsPerConsumer = false; + private String consumerName; + private String mappingsOutputFolder; + private StubRunnerProperties.StubsMode stubsMode; + private boolean deleteStubsAfterTest = true; + private Map properties = new HashMap<>(); public StubRunnerOptionsBuilder() { @@ -70,7 +85,8 @@ public class StubRunnerOptionsBuilder { return this; } - public StubRunnerOptionsBuilder withMinMaxPort(Integer minPortValue, Integer maxPortValue) { + public StubRunnerOptionsBuilder withMinMaxPort(Integer minPortValue, + Integer maxPortValue) { this.minPortValue = minPortValue; this.maxPortValue = maxPortValue; return this; @@ -98,7 +114,8 @@ public class StubRunnerOptionsBuilder { return this; } - public StubRunnerOptionsBuilder withStubsMode(StubRunnerProperties.StubsMode stubsMode) { + public StubRunnerOptionsBuilder withStubsMode( + StubRunnerProperties.StubsMode stubsMode) { this.stubsMode = stubsMode; return this; } @@ -131,21 +148,23 @@ public class StubRunnerOptionsBuilder { this.stubsPerConsumer = options.isStubsPerConsumer(); this.consumerName = options.getConsumerName(); this.mappingsOutputFolder = options.getMappingsOutputFolder(); - this.stubConfigurations = options.dependencies != null ? - options.dependencies : new ArrayList<>(); - this.stubIdsToPortMapping = options.stubIdsToPortMapping != null ? - options.stubIdsToPortMapping : new LinkedHashMap<>(); + this.stubConfigurations = options.dependencies != null ? options.dependencies + : new ArrayList<>(); + this.stubIdsToPortMapping = options.stubIdsToPortMapping != null + ? options.stubIdsToPortMapping : new LinkedHashMap<>(); this.deleteStubsAfterTest = options.isDeleteStubsAfterTest(); this.properties = options.getProperties(); return this; } - public StubRunnerOptionsBuilder withMappingsOutputFolder(String mappingsOutputFolder) { + public StubRunnerOptionsBuilder withMappingsOutputFolder( + String mappingsOutputFolder) { this.mappingsOutputFolder = mappingsOutputFolder; return this; } - public StubRunnerOptionsBuilder withDeleteStubsAfterTest(boolean deleteStubsAfterTest) { + public StubRunnerOptionsBuilder withDeleteStubsAfterTest( + boolean deleteStubsAfterTest) { this.deleteStubsAfterTest = deleteStubsAfterTest; return this; } @@ -156,15 +175,17 @@ public class StubRunnerOptionsBuilder { } public StubRunnerOptions build() { - return new StubRunnerOptions(this.minPortValue, this.maxPortValue, this.stubRepositoryRoot, - this.stubsMode, this.stubsClassifier, buildDependencies(), this.stubIdsToPortMapping, - this.username, this.password, this.stubRunnerProxyOptions, this.stubsPerConsumer, this.consumerName, - this.mappingsOutputFolder, this.deleteStubsAfterTest, this.properties); + return new StubRunnerOptions(this.minPortValue, this.maxPortValue, + this.stubRepositoryRoot, this.stubsMode, this.stubsClassifier, + buildDependencies(), this.stubIdsToPortMapping, this.username, + this.password, this.stubRunnerProxyOptions, this.stubsPerConsumer, + this.consumerName, this.mappingsOutputFolder, this.deleteStubsAfterTest, + this.properties); } private Collection buildDependencies() { - List stubConfigurations = StubsParser - .fromString(this.stubs, this.stubsClassifier); + List stubConfigurations = StubsParser.fromString(this.stubs, + this.stubsClassifier); this.stubConfigurations.addAll(stubConfigurations); return this.stubConfigurations; } @@ -174,14 +195,17 @@ public class StubRunnerOptionsBuilder { if (stubIdsToPortMapping.length == 1 && !containsRange(stubIdsToPortMapping[0])) { list.addAll(StringUtils.commaDelimitedListToSet(stubIdsToPortMapping[0])); return list; - } else if (stubIdsToPortMapping.length == 1 && containsRange(stubIdsToPortMapping[0])) { + } + else if (stubIdsToPortMapping.length == 1 + && containsRange(stubIdsToPortMapping[0])) { LinkedList linkedList = new LinkedList<>(); String[] split = stubIdsToPortMapping[0].split(","); for (String string : split) { if (containsClosingRange(string)) { String last = linkedList.pop(); linkedList.push(last + "," + string); - } else { + } + else { linkedList.push(string); } } @@ -210,7 +234,8 @@ public class StubRunnerOptionsBuilder { if (StubsParser.hasPort(notation)) { addPort(notation); this.stubs.add(StubsParser.ivyFromStringWithPort(notation)); - } else { + } + else { this.stubs.add(notation); } } @@ -234,8 +259,10 @@ public class StubRunnerOptionsBuilder { return this; } - public StubRunnerOptionsBuilder withProxy(final String proxyHost, final int proxyPort) { - this.stubRunnerProxyOptions = new StubRunnerOptions.StubRunnerProxyOptions(proxyHost, proxyPort); + public StubRunnerOptionsBuilder withProxy(final String proxyHost, + final int proxyPort) { + this.stubRunnerProxyOptions = new StubRunnerOptions.StubRunnerProxyOptions( + proxyHost, proxyPort); return this; } @@ -248,4 +275,5 @@ public class StubRunnerOptionsBuilder { this.consumerName = consumerName; return this; } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerPropertyUtils.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerPropertyUtils.java index 6c4f301436..53a5145371 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerPropertyUtils.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunnerPropertyUtils.java @@ -38,8 +38,8 @@ class StubRunnerPropertyUtils { static PropertyFetcher FETCHER = new PropertyFetcher(); /** - * For Env vars takes the prop name, converts dots to underscores and applies - * upper case + * For Env vars takes the prop name, converts dots to underscores and applies upper + * case */ static boolean isPropertySet(String propName) { String value = getProperty(new HashMap<>(), propName); @@ -47,8 +47,7 @@ class StubRunnerPropertyUtils { } /** - * For options, system props and env vars returns {@code true} - * when property is set + * For options, system props and env vars returns {@code true} when property is set */ static boolean hasProperty(Map options, String propName) { String value = getProperty(options, propName); @@ -56,14 +55,15 @@ class StubRunnerPropertyUtils { } /** - * Tries to pick a value from options, for Env vars takes the prop name, converts - * dots to underscores and applies upper case + * Tries to pick a value from options, for Env vars takes the prop name, converts dots + * to underscores and applies upper case */ static String getProperty(Map options, String propName) { if (options != null && options.containsKey(propName)) { String value = options.get(propName); if (log.isTraceEnabled()) { - log.trace("Options map contains the prop [" + propName + "] with value [" + value + "]"); + log.trace("Options map contains the prop [" + propName + "] with value [" + + value + "]"); } return value; } @@ -81,7 +81,8 @@ class StubRunnerPropertyUtils { String systemProp = FETCHER.systemProp(stubRunnerProp); if (StringUtils.hasText(systemProp)) { if (log.isTraceEnabled()) { - log.trace("System property [" + stubRunnerProp + "] has value [" + systemProp + "]"); + log.trace("System property [" + stubRunnerProp + "] has value [" + + systemProp + "]"); } return systemProp; } @@ -89,17 +90,22 @@ class StubRunnerPropertyUtils { .replaceAll("-", "_").toUpperCase(); String envVar = FETCHER.envVar(convertedEnvProp); if (log.isTraceEnabled()) { - log.trace("Environment variable [" + convertedEnvProp + "] has value [" + envVar + "]"); + log.trace("Environment variable [" + convertedEnvProp + "] has value [" + + envVar + "]"); } return envVar; } + } class PropertyFetcher { + String systemProp(String prop) { return System.getProperty(prop); } + String envVar(String prop) { return System.getenv(prop); } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunning.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunning.java index 8401a81d78..6156d58b1d 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunning.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubRunning.java @@ -21,8 +21,8 @@ import java.io.Closeable; public interface StubRunning extends Closeable, StubFinder { /** - * Runs the stubs and returns the {@link RunningStubs}. If the stubs were - * already started then a cached version will be returned. + * Runs the stubs and returns the {@link RunningStubs}. If the stubs were already + * started then a cached version will be returned. */ RunningStubs runStubs(); diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubServer.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubServer.java index f0d98fd12f..7da9023cba 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubServer.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubServer.java @@ -31,8 +31,11 @@ class StubServer { private static final Log log = LogFactory.getLog(StubServer.class); private final HttpServerStub httpServerStub; + final StubConfiguration stubConfiguration; + final Collection mappings; + final Collection contracts; StubServer(StubConfiguration stubConfiguration, Collection mappings, @@ -54,7 +57,8 @@ class StubServer { } private StubServer stubServer() { - log.info("Started stub server for project [" + this.stubConfiguration.toColonSeparatedDependencyNotation() + log.info("Started stub server for project [" + + this.stubConfiguration.toColonSeparatedDependencyNotation() + "] on port " + this.httpServerStub.port()); this.httpServerStub.registerMappings(this.mappings); return this; @@ -103,22 +107,26 @@ class StubServer { return this.httpServerStub.registeredMappings(); } - @Override public boolean equals(Object o) { + @Override + public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StubServer that = (StubServer) o; - return Objects.equals(this.stubConfiguration, that.stubConfiguration) && Objects - .equals(this.contracts, that.contracts); + return Objects.equals(this.stubConfiguration, that.stubConfiguration) + && Objects.equals(this.contracts, that.contracts); } - @Override public int hashCode() { + @Override + public int hashCode() { return Objects.hash(this.stubConfiguration, this.contracts); } - @Override public String toString() { - return "StubServer{" + "stubConfiguration=" + this.stubConfiguration + ", mappingsSize=" - + this.mappings.size() + '}'; + @Override + public String toString() { + return "StubServer{" + "stubConfiguration=" + this.stubConfiguration + + ", mappingsSize=" + this.mappings.size() + '}'; } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubTrigger.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubTrigger.java index 853e95fe49..3a8bd65e6b 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubTrigger.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/StubTrigger.java @@ -22,10 +22,10 @@ import java.util.Map; public interface StubTrigger { /** - * Triggers an event by a given label for a given {@code groupid:artifactid} notation. You can use only {@code artifactId} too. + * Triggers an event by a given label for a given {@code groupid:artifactid} notation. + * You can use only {@code artifactId} too. * * Feature related to messaging. - * * @return true - if managed to run a trigger */ boolean trigger(String ivyNotation, String labelName); @@ -34,7 +34,6 @@ public interface StubTrigger { * Triggers an event by a given label. * * Feature related to messaging. - * * @return true - if managed to run a trigger */ boolean trigger(String labelName); @@ -43,7 +42,6 @@ public interface StubTrigger { * Triggers all possible events. * * Feature related to messaging. - * * @return true - if managed to run a trigger */ boolean trigger(); @@ -54,4 +52,5 @@ public interface StubTrigger { * Feature related to messaging. */ Map> labels(); + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/TemporaryFileStorage.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/TemporaryFileStorage.java index abd2735297..153e7654be 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/TemporaryFileStorage.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/TemporaryFileStorage.java @@ -42,9 +42,9 @@ class TemporaryFileStorage { private static final Log log = LogFactory.getLog(TemporaryFileStorage.class); /** - * There are problems with removal of stubs unpacked to a temporary folder. - * That's why we're creating a bounded in-memory storage of unpacked files - * and later we register a shutdown hook to remove all these files. + * There are problems with removal of stubs unpacked to a temporary folder. That's why + * we're creating a bounded in-memory storage of unpacked files and later we register + * a shutdown hook to remove all these files. */ private static final Queue TEMP_FILES_LOG = new LinkedBlockingQueue<>(1000); @@ -66,8 +66,8 @@ class TemporaryFileStorage { if (file.isDirectory()) { Files.walkFileTree(file.toPath(), new SimpleFileVisitor() { @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws - IOException { + public FileVisitResult visitFile(Path file, + BasicFileAttributes attrs) throws IOException { if (log.isTraceEnabled()) { log.trace("Removing file [" + file + "]"); } @@ -76,7 +76,8 @@ class TemporaryFileStorage { } @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + public FileVisitResult postVisitDirectory(Path dir, + IOException exc) throws IOException { if (log.isTraceEnabled()) { log.trace("Removing dir [" + dir + "]"); } @@ -84,11 +85,13 @@ class TemporaryFileStorage { return FileVisitResult.CONTINUE; } }); - } else { + } + else { Files.delete(file.toPath()); } } - } catch (NoClassDefFoundError | IOException e) { + } + catch (NoClassDefFoundError | IOException e) { // Added NoClassDefFoundError cause sometimes it's visible in the builds // this error is completely harmless if (log.isTraceEnabled()) { @@ -99,12 +102,12 @@ class TemporaryFileStorage { static File createTempDir(String tempDirPrefix) { try { - return createTempDirectory(tempDirPrefix) - .toFile(); + return createTempDirectory(tempDirPrefix).toFile(); } catch (IOException e) { throw new IllegalStateException( "Cannot create tmp dir with prefix: [" + tempDirPrefix + "]", e); } } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRule.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRule.java index 6e440b3537..024590e02e 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRule.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRule.java @@ -43,12 +43,18 @@ import org.springframework.cloud.contract.verifier.messaging.MessageVerifier; * @author Marcin Grzejszczak */ public class StubRunnerRule implements TestRule, StubFinder, StubRunnerRuleOptions { + private static final String DELIMITER = ":"; + private static final String LATEST_VERSION = "+"; - StubRunnerOptionsBuilder stubRunnerOptionsBuilder = new StubRunnerOptionsBuilder(StubRunnerOptions.fromSystemProps()); + StubRunnerOptionsBuilder stubRunnerOptionsBuilder = new StubRunnerOptionsBuilder( + StubRunnerOptions.fromSystemProps()); + BatchStubRunner stubFinder; + MessageVerifier verifier = new ExceptionThrowingMessageVerifier(); + StubRunnerRule delegate = this; public StubRunnerRule() { @@ -65,102 +71,122 @@ public class StubRunnerRule implements TestRule, StubFinder, StubRunnerRuleOptio } private void before() { - stubFinder(new BatchStubRunnerFactory(builder().build(), verifier()).buildBatchStubRunner()); + stubFinder(new BatchStubRunnerFactory(builder().build(), verifier()) + .buildBatchStubRunner()); StubRunnerRule.this.stubFinder().runStubs(); } }; } - @Override public StubRunnerRule messageVerifier(MessageVerifier messageVerifier) { + @Override + public StubRunnerRule messageVerifier(MessageVerifier messageVerifier) { verifier(messageVerifier); return this.delegate; } - @Override public StubRunnerRule options(StubRunnerOptions stubRunnerOptions) { + @Override + public StubRunnerRule options(StubRunnerOptions stubRunnerOptions) { builder().withOptions(stubRunnerOptions); return this.delegate; } - @Override public StubRunnerRule minPort(int minPort) { + @Override + public StubRunnerRule minPort(int minPort) { builder().withMinPort(minPort); return this.delegate; } - @Override public StubRunnerRule maxPort(int maxPort) { + @Override + public StubRunnerRule maxPort(int maxPort) { builder().withMaxPort(maxPort); return this.delegate; } - @Override public StubRunnerRule repoRoot(String repoRoot) { + @Override + public StubRunnerRule repoRoot(String repoRoot) { builder().withStubRepositoryRoot(repoRoot); return this.delegate; } - @Override public StubRunnerRule stubsMode(StubRunnerProperties.StubsMode stubsMode) { + @Override + public StubRunnerRule stubsMode(StubRunnerProperties.StubsMode stubsMode) { builder().withStubsMode(stubsMode); return this.delegate; } - @Override public PortStubRunnerRule downloadStub(String groupId, String artifactId, + @Override + public PortStubRunnerRule downloadStub(String groupId, String artifactId, String version, String classifier) { - builder().withStubs(groupId + DELIMITER + artifactId + DELIMITER + version + DELIMITER + classifier); + builder().withStubs(groupId + DELIMITER + artifactId + DELIMITER + version + + DELIMITER + classifier); return new PortStubRunnerRule(this.delegate); } - @Override public PortStubRunnerRule downloadLatestStub(String groupId, String artifactId, + @Override + public PortStubRunnerRule downloadLatestStub(String groupId, String artifactId, String classifier) { - builder().withStubs(groupId + DELIMITER + artifactId + DELIMITER + LATEST_VERSION + DELIMITER + classifier); + builder().withStubs(groupId + DELIMITER + artifactId + DELIMITER + LATEST_VERSION + + DELIMITER + classifier); return new PortStubRunnerRule(this.delegate); } - @Override public PortStubRunnerRule downloadStub(String groupId, String artifactId, + @Override + public PortStubRunnerRule downloadStub(String groupId, String artifactId, String version) { builder().withStubs(groupId + DELIMITER + artifactId + DELIMITER + version); return new PortStubRunnerRule(this.delegate); } - @Override public PortStubRunnerRule downloadStub(String groupId, String artifactId) { + @Override + public PortStubRunnerRule downloadStub(String groupId, String artifactId) { builder().withStubs(groupId + DELIMITER + artifactId); return new PortStubRunnerRule(this.delegate); } - @Override public PortStubRunnerRule downloadStub(String ivyNotation) { + @Override + public PortStubRunnerRule downloadStub(String ivyNotation) { builder().withStubs(ivyNotation); return new PortStubRunnerRule(this.delegate); } - @Override public StubRunnerRule downloadStubs(String... ivyNotations) { + @Override + public StubRunnerRule downloadStubs(String... ivyNotations) { builder().withStubs(Arrays.asList(ivyNotations)); return new PortStubRunnerRule(this.delegate); } - @Override public StubRunnerRule downloadStubs(List ivyNotations) { + @Override + public StubRunnerRule downloadStubs(List ivyNotations) { builder().withStubs(ivyNotations); return new PortStubRunnerRule(this.delegate); } - @Override public StubRunnerRule withStubPerConsumer(boolean stubPerConsumer) { + @Override + public StubRunnerRule withStubPerConsumer(boolean stubPerConsumer) { builder().withStubPerConsumer(stubPerConsumer); return this.delegate; } - @Override public StubRunnerRule withConsumerName(String consumerName) { + @Override + public StubRunnerRule withConsumerName(String consumerName) { builder().withConsumerName(consumerName); return this.delegate; } - @Override public StubRunnerRule withMappingsOutputFolder(String mappingsOutputFolder) { + @Override + public StubRunnerRule withMappingsOutputFolder(String mappingsOutputFolder) { builder().withMappingsOutputFolder(mappingsOutputFolder); return this.delegate; } - @Override public StubRunnerRule withDeleteStubsAfterTest( - boolean deleteStubsAfterTest) { + @Override + public StubRunnerRule withDeleteStubsAfterTest(boolean deleteStubsAfterTest) { builder().withDeleteStubsAfterTest(deleteStubsAfterTest); return this.delegate; } - @Override public StubRunnerRule withProperties(Map properties) { + @Override + public StubRunnerRule withProperties(Map properties) { builder().withProperties(properties); return this.delegate; } @@ -189,7 +215,8 @@ public class StubRunnerRule implements TestRule, StubFinder, StubRunnerRuleOptio public boolean trigger(String ivyNotation, String labelName) { boolean result = this.stubFinder().trigger(ivyNotation, labelName); if (!result) { - throw new IllegalStateException("Failed to trigger a message with notation [" + ivyNotation + "] and label [" + labelName + "]"); + throw new IllegalStateException("Failed to trigger a message with notation [" + + ivyNotation + "] and label [" + labelName + "]"); } return result; } @@ -198,7 +225,8 @@ public class StubRunnerRule implements TestRule, StubFinder, StubRunnerRuleOptio public boolean trigger(String labelName) { boolean result = this.stubFinder().trigger(labelName); if (!result) { - throw new IllegalStateException("Failed to trigger a message with label [" + labelName + "]"); + throw new IllegalStateException( + "Failed to trigger a message with label [" + labelName + "]"); } return result; } @@ -245,22 +273,26 @@ public class StubRunnerRule implements TestRule, StubFinder, StubRunnerRuleOptio private static final String EXCEPTION_MESSAGE = "Please provide a custom MessageVerifier to use this feature"; - @Override public void send(Object message, String destination) { + @Override + public void send(Object message, String destination) { throw new UnsupportedOperationException(EXCEPTION_MESSAGE); } - @Override public Object receive(String destination, long timeout, - TimeUnit timeUnit) { + @Override + public Object receive(String destination, long timeout, TimeUnit timeUnit) { throw new UnsupportedOperationException(EXCEPTION_MESSAGE); } - @Override public Object receive(String destination) { + @Override + public Object receive(String destination) { throw new UnsupportedOperationException(EXCEPTION_MESSAGE); } - @Override public void send(Object payload, Map headers, String destination) { + @Override + public void send(Object payload, Map headers, String destination) { throw new UnsupportedOperationException(EXCEPTION_MESSAGE); } + } /** @@ -268,15 +300,19 @@ public class StubRunnerRule implements TestRule, StubFinder, StubRunnerRuleOptio * * @since 1.2.0 */ - public static class PortStubRunnerRule extends StubRunnerRule implements PortStubRunnerRuleOptions { + public static class PortStubRunnerRule extends StubRunnerRule + implements PortStubRunnerRuleOptions { + PortStubRunnerRule(StubRunnerRule delegate) { super(delegate); } - @Override public StubRunnerRule withPort(Integer port) { + @Override + public StubRunnerRule withPort(Integer port) { builder().withPort(port); return this.delegate; } + } } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleOptions.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleOptions.java index 4981ca334d..f5441e0da9 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleOptions.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleOptions.java @@ -8,10 +8,12 @@ import org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties import org.springframework.cloud.contract.verifier.messaging.MessageVerifier; interface StubRunnerRuleOptions { + /** - * Pass the {@link MessageVerifier} that this rule should use. - * If you don't pass anything a {@link StubRunnerRule.ExceptionThrowingMessageVerifier} will be used. - * That means that an exception will be thrown whenever you try to do sth messaging related. + * Pass the {@link MessageVerifier} that this rule should use. If you don't pass + * anything a {@link StubRunnerRule.ExceptionThrowingMessageVerifier} will be used. + * That means that an exception will be thrown whenever you try to do sth messaging + * related. */ StubRunnerRule messageVerifier(MessageVerifier messageVerifier); @@ -45,11 +47,12 @@ interface StubRunnerRuleOptions { /** * Group Id, artifact Id, version and classifier of a single stub to download */ - PortStubRunnerRuleOptions downloadStub(String groupId, String artifactId, String version, - String classifier); + PortStubRunnerRuleOptions downloadStub(String groupId, String artifactId, + String version, String classifier); /** - * Group Id, artifact Id and classifier of a single stub to download in the latest version + * Group Id, artifact Id and classifier of a single stub to download in the latest + * version */ PortStubRunnerRuleOptions downloadLatestStub(String groupId, String artifactId, String classifier); @@ -61,7 +64,8 @@ interface StubRunnerRuleOptions { String version); /** - * Group Id, artifact Id of a single stub to download. Default classifier will be picked. + * Group Id, artifact Id of a single stub to download. Default classifier will be + * picked. */ PortStubRunnerRuleOptions downloadStub(String groupId, String artifactId); @@ -96,13 +100,15 @@ interface StubRunnerRuleOptions { StubRunnerRule withMappingsOutputFolder(String mappingsOutputFolder); /** - * If set to {@code false} will NOT delete stubs from a temporary - * folder after running tests + * If set to {@code false} will NOT delete stubs from a temporary folder after running + * tests */ StubRunnerRule withDeleteStubsAfterTest(boolean deleteStubsAfterTest); /** - * Map of properties that can be passed to custom {@link org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder} + * Map of properties that can be passed to custom + * {@link org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder} */ StubRunnerRule withProperties(Map properties); + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/StubRunnerStreamsIntegrationAutoConfiguration.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/StubRunnerStreamsIntegrationAutoConfiguration.java index 6feca9536c..15626d5069 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/StubRunnerStreamsIntegrationAutoConfiguration.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/StubRunnerStreamsIntegrationAutoConfiguration.java @@ -12,7 +12,7 @@ import org.springframework.context.annotation.Configuration; * {@link org.springframework.cloud.contract.stubrunner.spring.AutoConfigureStubRunner} by * loading in AutoConfigurations related to Stream and Integration only if the relevant * jars are in classpath. - * + * * @author Biju Kunjummen */ @Configuration @@ -32,4 +32,5 @@ public class StubRunnerStreamsIntegrationAutoConfiguration { static class IntegrationRelatedAutoConfiguration { } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/integration/StubRunnerIntegrationConfiguration.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/integration/StubRunnerIntegrationConfiguration.java index c01d094891..5c34c03908 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/integration/StubRunnerIntegrationConfiguration.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/integration/StubRunnerIntegrationConfiguration.java @@ -46,22 +46,24 @@ import org.springframework.messaging.Message; */ @Configuration @ConditionalOnClass(IntegrationFlowBuilder.class) -@ConditionalOnProperty(name="stubrunner.integration.enabled", havingValue="true", matchIfMissing=true) +@ConditionalOnProperty(name = "stubrunner.integration.enabled", havingValue = "true", matchIfMissing = true) public class StubRunnerIntegrationConfiguration { @Bean - @ConditionalOnMissingBean(name="stubFlowRegistrar") + @ConditionalOnMissingBean(name = "stubFlowRegistrar") public FlowRegistrar stubFlowRegistrar(AutowireCapableBeanFactory beanFactory, BatchStubRunner batchStubRunner) { Map> contracts = batchStubRunner .getContracts(); - for (Entry> entry : contracts.entrySet()) { + for (Entry> entry : contracts + .entrySet()) { String name = entry.getKey().getGroupId() + "_" + entry.getKey().getArtifactId(); for (Contract dsl : entry.getValue()) { if (dsl.getInput() != null && dsl.getInput().getMessageFrom() != null && dsl.getInput().getMessageFrom().getClientValue() != null) { - final String flowName = name + "_" + dsl.getLabel() + "_" + dsl.hashCode(); + final String flowName = name + "_" + dsl.getLabel() + "_" + + dsl.hashCode(); IntegrationFlowBuilder builder = IntegrationFlows .from(dsl.getInput().getMessageFrom().getClientValue()) .filter(new StubRunnerIntegrationMessageSelector(dsl), @@ -90,18 +92,22 @@ public class StubRunnerIntegrationConfiguration { beanFactory.getBean(flowName + ".filter", Lifecycle.class).start(); beanFactory.getBean(flowName + ".transformer", Lifecycle.class) .start(); - } + } } } return new FlowRegistrar(); } private static class DummyMessageHandler { + @SuppressWarnings("unused") public void handle(Message message) { } + } static class FlowRegistrar { + } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/integration/StubRunnerIntegrationMessageSelector.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/integration/StubRunnerIntegrationMessageSelector.java index e9da60e4be..fcc7a98e74 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/integration/StubRunnerIntegrationMessageSelector.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/integration/StubRunnerIntegrationMessageSelector.java @@ -45,6 +45,7 @@ import com.toomuchcoding.jsonassert.JsonAssertion; class StubRunnerIntegrationMessageSelector implements MessageSelector { private final Contract groovyDsl; + private final ContractVerifierObjectMapper objectMapper = new ContractVerifierObjectMapper(); StubRunnerIntegrationMessageSelector(Contract groovyDsl) { @@ -58,7 +59,8 @@ class StubRunnerIntegrationMessageSelector implements MessageSelector { } Object inputMessage = message.getPayload(); BodyMatchers matchers = this.groovyDsl.getInput().getBodyMatchers(); - Object dslBody = MapConverter.getStubSideValues(this.groovyDsl.getInput().getMessageBody()); + Object dslBody = MapConverter + .getStubSideValues(this.groovyDsl.getInput().getMessageBody()); Object matchingInputMessage = JsonToJsonPathsConverter .removeMatchingJsonPaths(dslBody, matchers); JsonPaths jsonPaths = JsonToJsonPathsConverter @@ -66,7 +68,8 @@ class StubRunnerIntegrationMessageSelector implements MessageSelector { matchingInputMessage); DocumentContext parsedJson; try { - parsedJson = JsonPath.parse(this.objectMapper.writeValueAsString(inputMessage)); + parsedJson = JsonPath + .parse(this.objectMapper.writeValueAsString(inputMessage)); } catch (JsonProcessingException e) { throw new IllegalStateException("Cannot serialize to JSON", e); @@ -77,7 +80,8 @@ class StubRunnerIntegrationMessageSelector implements MessageSelector { } if (matchers != null && matchers.hasMatchers()) { for (BodyMatcher matcher : matchers.jsonPathMatchers()) { - String jsonPath = JsonToJsonPathsConverter.convertJsonPathAndRegexToAJsonPath(matcher, dslBody); + String jsonPath = JsonToJsonPathsConverter + .convertJsonPathAndRegexToAJsonPath(matcher, dslBody); matches &= matchesJsonPath(parsedJson, jsonPath); } } @@ -86,8 +90,7 @@ class StubRunnerIntegrationMessageSelector implements MessageSelector { private boolean matchesJsonPath(DocumentContext parsedJson, String jsonPath) { try { - JsonAssertion.assertThat(parsedJson) - .matchesJsonPath(jsonPath); + JsonAssertion.assertThat(parsedJson).matchesJsonPath(jsonPath); return true; } catch (Exception e) { @@ -102,10 +105,11 @@ class StubRunnerIntegrationMessageSelector implements MessageSelector { String name = it.getName(); Object value = it.getClientValue(); Object valueInHeader = headers.get(name); - matches &= value instanceof Pattern ? - ((Pattern) value).matcher(valueInHeader.toString()).matches() : - valueInHeader!=null && valueInHeader.equals(value); + matches &= value instanceof Pattern + ? ((Pattern) value).matcher(valueInHeader.toString()).matches() + : valueInHeader != null && valueInHeader.equals(value); } return matches; } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/integration/StubRunnerIntegrationTransformer.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/integration/StubRunnerIntegrationTransformer.java index 5bc54fc057..0e40fda256 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/integration/StubRunnerIntegrationTransformer.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/integration/StubRunnerIntegrationTransformer.java @@ -30,7 +30,8 @@ import org.springframework.messaging.support.MessageBuilder; * * @author Marcin Grzejszczak */ -class StubRunnerIntegrationTransformer implements GenericTransformer, Message> { +class StubRunnerIntegrationTransformer + implements GenericTransformer, Message> { private final Contract groovyDsl; @@ -43,8 +44,11 @@ class StubRunnerIntegrationTransformer implements GenericTransformer, if (this.groovyDsl.getOutputMessage() == null) { return source; } - String payload = BodyExtractor.extractStubValueFrom(this.groovyDsl.getOutputMessage().getBody()); - Map headers = this.groovyDsl.getOutputMessage().getHeaders().asStubSideMap(); + String payload = BodyExtractor + .extractStubValueFrom(this.groovyDsl.getOutputMessage().getBody()); + Map headers = this.groovyDsl.getOutputMessage().getHeaders() + .asStubSideMap(); return MessageBuilder.createMessage(payload, new MessageHeaders(headers)); } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/stream/StubRunnerStreamConfiguration.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/stream/StubRunnerStreamConfiguration.java index e859f86f2a..7511a02681 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/stream/StubRunnerStreamConfiguration.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/stream/StubRunnerStreamConfiguration.java @@ -55,15 +55,15 @@ import org.springframework.util.StringUtils; * @author Marcin Grzejszczak */ @Configuration -@ConditionalOnClass({IntegrationFlows.class, EnableBinding.class}) -@ConditionalOnProperty(name="stubrunner.stream.enabled", havingValue="true", matchIfMissing=true) +@ConditionalOnClass({ IntegrationFlows.class, EnableBinding.class }) +@ConditionalOnProperty(name = "stubrunner.stream.enabled", havingValue = "true", matchIfMissing = true) @AutoConfigureBefore(StubRunnerIntegrationConfiguration.class) public class StubRunnerStreamConfiguration { private static final Log log = LogFactory.getLog(StubRunnerStreamConfiguration.class); @Bean - @ConditionalOnMissingBean(name="stubFlowRegistrar") + @ConditionalOnMissingBean(name = "stubFlowRegistrar") @ConditionalOnBean(BindingServiceProperties.class) public FlowRegistrar stubFlowRegistrar(AutowireCapableBeanFactory beanFactory, BatchStubRunner batchStubRunner) { @@ -78,10 +78,9 @@ public class StubRunnerStreamConfiguration { if (dsl == null) { continue; } - if (dsl.getInput() != null - && dsl.getInput().getMessageFrom() != null - && StringUtils.hasText( - dsl.getInput().getMessageFrom().getClientValue())) { + if (dsl.getInput() != null && dsl.getInput().getMessageFrom() != null + && StringUtils.hasText( + dsl.getInput().getMessageFrom().getClientValue())) { final String flowName = name + "_" + dsl.getLabel() + "_" + dsl.hashCode(); String from = resolvedDestination(beanFactory, @@ -111,16 +110,18 @@ public class StubRunnerStreamConfiguration { builder = builder.handle(new DummyMessageHandler(), "handle"); } beanFactory.initializeBean(builder.get(), flowName); - beanFactory.getBean(flowName + ".filter", Lifecycle.class) - .start(); + beanFactory.getBean(flowName + ".filter", Lifecycle.class).start(); beanFactory.getBean(flowName + ".transformer", Lifecycle.class) .start(); - } else if (dsl.getOutputMessage() != null + } + else if (dsl.getOutputMessage() != null && dsl.getOutputMessage().getSentTo() != null && StringUtils.hasText( - dsl.getOutputMessage().getSentTo().getClientValue())) { - BinderAwareChannelResolver resolver = beanFactory.getBean(BinderAwareChannelResolver.class); - resolver.resolveDestination(dsl.getOutputMessage().getSentTo().getClientValue()); + dsl.getOutputMessage().getSentTo().getClientValue())) { + BinderAwareChannelResolver resolver = beanFactory + .getBean(BinderAwareChannelResolver.class); + resolver.resolveDestination( + dsl.getOutputMessage().getSentTo().getClientValue()); } } } @@ -133,26 +134,33 @@ public class StubRunnerStreamConfiguration { for (Map.Entry entry : bindings.entrySet()) { if (destination.equals(entry.getValue().getDestination())) { if (log.isDebugEnabled()) { - log.debug("Found a channel named [" + entry.getKey() + "] with destination [" + destination + "]"); + log.debug("Found a channel named [" + entry.getKey() + + "] with destination [" + destination + "]"); } return entry.getKey(); } } if (log.isDebugEnabled()) { - log.debug( - "No destination named [" + destination + "] was found. Assuming that the destination equals the channel name"); + log.debug("No destination named [" + destination + + "] was found. Assuming that the destination equals the channel name"); } return destination; } - private Map bindingProperties(AutowireCapableBeanFactory context) { + private Map bindingProperties( + AutowireCapableBeanFactory context) { return context.getBean(BindingServiceProperties.class).getBindings(); } private static class DummyMessageHandler { - public void handle(Message message) {} + + public void handle(Message message) { + } + } static class FlowRegistrar { + } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/stream/StubRunnerStreamMessageSelector.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/stream/StubRunnerStreamMessageSelector.java index 2af00362a4..19d6e33bba 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/stream/StubRunnerStreamMessageSelector.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/stream/StubRunnerStreamMessageSelector.java @@ -48,9 +48,11 @@ import com.toomuchcoding.jsonassert.JsonAssertion; */ class StubRunnerStreamMessageSelector implements MessageSelector { - private static final Log log = LogFactory.getLog(StubRunnerStreamMessageSelector.class); + private static final Log log = LogFactory + .getLog(StubRunnerStreamMessageSelector.class); private final Contract groovyDsl; + private final ContractVerifierObjectMapper objectMapper = new ContractVerifierObjectMapper(); StubRunnerStreamMessageSelector(Contract groovyDsl) { @@ -62,13 +64,15 @@ class StubRunnerStreamMessageSelector implements MessageSelector { List unmatchedHeaders = headersMatch(message); if (!unmatchedHeaders.isEmpty()) { if (log.isDebugEnabled()) { - log.debug("Contract [" + this.groovyDsl + "] hasn't matched the following headers " + unmatchedHeaders); + log.debug("Contract [" + this.groovyDsl + + "] hasn't matched the following headers " + unmatchedHeaders); } return false; } Object inputMessage = message.getPayload(); BodyMatchers matchers = this.groovyDsl.getInput().getBodyMatchers(); - Object dslBody = MapConverter.getStubSideValues(this.groovyDsl.getInput().getMessageBody()); + Object dslBody = MapConverter + .getStubSideValues(this.groovyDsl.getInput().getMessageBody()); Object matchingInputMessage = JsonToJsonPathsConverter .removeMatchingJsonPaths(dslBody, matchers); JsonPaths jsonPaths = JsonToJsonPathsConverter @@ -76,7 +80,8 @@ class StubRunnerStreamMessageSelector implements MessageSelector { matchingInputMessage); DocumentContext parsedJson; try { - parsedJson = JsonPath.parse(this.objectMapper.writeValueAsString(inputMessage)); + parsedJson = JsonPath + .parse(this.objectMapper.writeValueAsString(inputMessage)); } catch (JsonProcessingException e) { throw new IllegalStateException("Cannot serialize to JSON", e); @@ -88,23 +93,27 @@ class StubRunnerStreamMessageSelector implements MessageSelector { } if (matchers != null && matchers.hasMatchers()) { for (BodyMatcher matcher : matchers.jsonPathMatchers()) { - String jsonPath = JsonToJsonPathsConverter.convertJsonPathAndRegexToAJsonPath(matcher, dslBody); + String jsonPath = JsonToJsonPathsConverter + .convertJsonPathAndRegexToAJsonPath(matcher, dslBody); matches &= matchesJsonPath(unmatchedJsonPath, parsedJson, jsonPath); } } if (!unmatchedJsonPath.isEmpty()) { if (log.isDebugEnabled()) { - log.debug("Contract [" + this.groovyDsl + "] didn't much the body due to " + unmatchedJsonPath); + log.debug("Contract [" + this.groovyDsl + "] didn't much the body due to " + + unmatchedJsonPath); } } return matches; } - private boolean matchesJsonPath(List unmatchedJsonPath, DocumentContext parsedJson, String jsonPath) { + private boolean matchesJsonPath(List unmatchedJsonPath, + DocumentContext parsedJson, String jsonPath) { try { JsonAssertion.assertThat(parsedJson).matchesJsonPath(jsonPath); return true; - } catch (Exception e) { + } + catch (Exception e) { unmatchedJsonPath.add(e.getLocalizedMessage()); return false; } @@ -121,20 +130,25 @@ class StubRunnerStreamMessageSelector implements MessageSelector { if (value instanceof Pattern) { Pattern pattern = (Pattern) value; matches = pattern.matcher(valueInHeader.toString()).matches(); - } else { - matches = valueInHeader != null && valueInHeader.toString().equals(value.toString()); + } + else { + matches = valueInHeader != null + && valueInHeader.toString().equals(value.toString()); } if (!matches) { - unmatchedHeaders.add("Header with name [" + name + "] was supposed to " + - unmatchedText(value) + " but the value is [" + (valueInHeader != null ? - valueInHeader.toString() : "null") + "]"); + unmatchedHeaders.add("Header with name [" + name + "] was supposed to " + + unmatchedText(value) + " but the value is [" + + (valueInHeader != null ? valueInHeader.toString() : "null") + + "]"); } } return unmatchedHeaders; } private String unmatchedText(Object expectedValue) { - return expectedValue instanceof Pattern ? "match pattern [" + ((Pattern) expectedValue).pattern() + "]" : - "be equal to [" + expectedValue + "]"; + return expectedValue instanceof Pattern + ? "match pattern [" + ((Pattern) expectedValue).pattern() + "]" + : "be equal to [" + expectedValue + "]"; } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/stream/StubRunnerStreamTransformer.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/stream/StubRunnerStreamTransformer.java index f419ae365d..b4d6673903 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/stream/StubRunnerStreamTransformer.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/stream/StubRunnerStreamTransformer.java @@ -40,11 +40,15 @@ class StubRunnerStreamTransformer implements GenericTransformer, Mess @Override public Message transform(Message source) { - if (this.groovyDsl.getOutputMessage()==null) { + if (this.groovyDsl.getOutputMessage() == null) { return source; } - String payload = BodyExtractor.extractStubValueFrom(this.groovyDsl.getOutputMessage().getBody()); - Map headers = this.groovyDsl.getOutputMessage().getHeaders().asStubSideMap(); - return MessageBuilder.createMessage(payload.getBytes(), new MessageHeaders(headers)); + String payload = BodyExtractor + .extractStubValueFrom(this.groovyDsl.getOutputMessage().getBody()); + Map headers = this.groovyDsl.getOutputMessage().getHeaders() + .asStubSideMap(); + return MessageBuilder.createMessage(payload.getBytes(), + new MessageHeaders(headers)); } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/provider/wiremock/StubRunnerWireMockTestExecutionListener.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/provider/wiremock/StubRunnerWireMockTestExecutionListener.java index 7bd3005ffa..aecbfb0b21 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/provider/wiremock/StubRunnerWireMockTestExecutionListener.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/provider/wiremock/StubRunnerWireMockTestExecutionListener.java @@ -20,46 +20,59 @@ import org.springframework.web.client.RestTemplate; * @author Marcin Grzejszczak * @since 1.2.6 */ -public final class StubRunnerWireMockTestExecutionListener extends AbstractTestExecutionListener { +public final class StubRunnerWireMockTestExecutionListener + extends AbstractTestExecutionListener { - private static final Log log = LogFactory.getLog(StubRunnerWireMockTestExecutionListener.class); + private static final Log log = LogFactory + .getLog(StubRunnerWireMockTestExecutionListener.class); private static Map> STUBS = new ConcurrentHashMap<>(); - @Override public void beforeTestClass(TestContext testContext) { + @Override + public void beforeTestClass(TestContext testContext) { Map stubs = STUBS .get(testContext.getApplicationContext()); if (stubs != null) { if (log.isDebugEnabled()) { - log.debug("Found a matching application context from [" + testContext.getTestClass().getName() + "]"); + log.debug("Found a matching application context from [" + + testContext.getTestClass().getName() + "]"); } - for (Map.Entry entry : stubs.entrySet()) { + for (Map.Entry entry : stubs + .entrySet()) { while (entry.getKey().isRunning()) { entry.getKey().stop(); } List mappings = entry.getValue().mappings; if (log.isDebugEnabled()) { - log.debug("Stopped a running WireMock instance at " - + "port [" + entry.getValue().port + "] with stub mappings " - + "size [" + mappings.size() + "]. Restarting the stub."); + log.debug("Stopped a running WireMock instance at " + "port [" + + entry.getValue().port + "] with stub mappings " + "size [" + + mappings.size() + "]. Restarting the stub."); } entry.getKey().start(entry.getValue().port); entry.getKey().registerDescriptors(mappings); /* - Thanks to Tom Akehurst: - I looked at tcpdump while running the failing test. HttpUrlConnection is doing something weird - it's creating a connection in a - previous test case, which works fine, then the usual fin -> fin ack etc. etc. ending handshake happens. But it seems it - isn't discarded, but reused after that. Because the server thinks (rightly) that the connection is closed, it just sends a RST packet. - Calling the admin endpoint just happened to remove the dead connection from the pool. - This also fixes the problem (which using the Java HTTP client): System.setProperty("http.keepAlive", "false"); + * Thanks to Tom Akehurst: I looked at tcpdump while running the failing + * test. HttpUrlConnection is doing something weird - it's creating a + * connection in a previous test case, which works fine, then the usual + * fin -> fin ack etc. etc. ending handshake happens. But it seems it + * isn't discarded, but reused after that. Because the server thinks + * (rightly) that the connection is closed, it just sends a RST packet. + * Calling the admin endpoint just happened to remove the dead connection + * from the pool. This also fixes the problem (which using the Java HTTP + * client): System.setProperty("http.keepAlive", "false"); */ - Assert.isTrue(new RestTemplate().getForEntity("http://localhost:" + entry.getValue().port + "/__admin/mappings", String.class) - .getStatusCode().is2xxSuccessful(), "__admin/mappings endpoint wasn't accessible"); + Assert.isTrue( + new RestTemplate() + .getForEntity("http://localhost:" + entry.getValue().port + + "/__admin/mappings", String.class) + .getStatusCode().is2xxSuccessful(), + "__admin/mappings endpoint wasn't accessible"); } } } - @Override public void afterTestClass(TestContext testContext) { + @Override + public void afterTestClass(TestContext testContext) { STUBS.put(testContext.getApplicationContext(), WireMockHttpServerStub.SERVERS); if (log.isDebugEnabled()) { log.debug("Stopping servers " + WireMockHttpServerStub.SERVERS); @@ -68,4 +81,5 @@ public final class StubRunnerWireMockTestExecutionListener extends AbstractTestE serverStub.stop(); } } + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/provider/wiremock/WireMockHttpServerStub.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/provider/wiremock/WireMockHttpServerStub.java index e08a310f52..c13290a9dc 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/provider/wiremock/WireMockHttpServerStub.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/provider/wiremock/WireMockHttpServerStub.java @@ -50,9 +50,9 @@ public class WireMockHttpServerStub implements HttpServerStub { private WireMockServer wireMockServer; private WireMockConfiguration config() { - if (ClassUtils.isPresent("org.springframework.cloud.contract.wiremock.WireMockSpring", null)) { - return WireMockSpring.options() - .extensions(responseTransformers()); + if (ClassUtils.isPresent( + "org.springframework.cloud.contract.wiremock.WireMockSpring", null)) { + return WireMockSpring.options().extensions(responseTransformers()); } return new WireMockConfiguration().extensions(responseTransformers()); } @@ -65,7 +65,8 @@ public class WireMockHttpServerStub implements HttpServerStub { for (WireMockExtensions wireMockExtension : wireMockExtensions) { extensions.addAll(wireMockExtension.extensions()); } - } else { + } + else { extensions.add(new DefaultResponseTransformer(false, helpers())); } return extensions.toArray(new Extension[extensions.size()]); @@ -73,9 +74,8 @@ public class WireMockHttpServerStub implements HttpServerStub { /** * Override this if you want to register your own helpers - * - * @deprecated - please use the {@link WireMockExtensions} mechanism and pass - * the helpers in your implementation + * @deprecated - please use the {@link WireMockExtensions} mechanism and pass the + * helpers in your implementation */ @Deprecated protected Map helpers() { @@ -108,8 +108,8 @@ public class WireMockHttpServerStub implements HttpServerStub { @Override public HttpServerStub start(int port) { - this.wireMockServer = new WireMockServer(config().port(port) - .notifier(new Slf4jNotifier(true))); + this.wireMockServer = new WireMockServer( + config().port(port).notifier(new Slf4jNotifier(true))); this.wireMockServer.start(); if (log.isDebugEnabled()) { log.debug("Started WireMock at port [" + port + "]"); @@ -141,7 +141,8 @@ public class WireMockHttpServerStub implements HttpServerStub { return this; } - @Override public String registeredMappings() { + @Override + public String registeredMappings() { Collection mappings = new ArrayList<>(); for (StubMapping stubMapping : this.wireMockServer.getStubMappings()) { mappings.add(stubMapping.toString()); @@ -189,12 +190,14 @@ public class WireMockHttpServerStub implements HttpServerStub { try { stubMappings.add(registerDescriptor(wireMock, mappingDescriptor)); if (log.isDebugEnabled()) { - log.debug("Registered stub mappings from [" + mappingDescriptor + "]"); + log.debug( + "Registered stub mappings from [" + mappingDescriptor + "]"); } } catch (Exception e) { if (log.isDebugEnabled()) { - log.debug("Failed to register the stub mapping [" + mappingDescriptor + "]", e); + log.debug("Failed to register the stub mapping [" + mappingDescriptor + + "]", e); } } } @@ -210,7 +213,8 @@ public class WireMockHttpServerStub implements HttpServerStub { void registerDescriptors(List stubMappings) { if (log.isDebugEnabled()) { - log.debug("Registering stub mappings size [" + stubMappings.size() + "] at port [" + port() + "]"); + log.debug("Registering stub mappings size [" + stubMappings.size() + + "] at port [" + port() + "]"); } for (StubMapping mapping : stubMappings) { wireMock().register(mapping); @@ -222,13 +226,16 @@ public class WireMockHttpServerStub implements HttpServerStub { } private void registerHealthCheck(WireMock wireMock, String url, String body) { - wireMock.register( - WireMock.get(WireMock.urlEqualTo(url)).willReturn(WireMock.aResponse().withBody(body).withStatus(200))); + wireMock.register(WireMock.get(WireMock.urlEqualTo(url)) + .willReturn(WireMock.aResponse().withBody(body).withStatus(200))); } + } class PortAndMappings { + final Integer port; + final List mappings; PortAndMappings(Integer port, List mappings) { @@ -236,7 +243,10 @@ class PortAndMappings { this.mappings = mappings; } - @Override public String toString() { - return "PortAndMappings{" + "port=" + this.port + ", mappings=" + this.mappings.size() + '}'; + @Override + public String toString() { + return "PortAndMappings{" + "port=" + this.port + ", mappings=" + + this.mappings.size() + '}'; } + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/server/EnableStubRunnerServer.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/server/EnableStubRunnerServer.java index c50223e419..c0862755f2 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/server/EnableStubRunnerServer.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/server/EnableStubRunnerServer.java @@ -34,7 +34,8 @@ import org.springframework.context.annotation.Import; @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited -@Import({HttpStubsController.class, TriggerController.class, StubRunnerConfiguration.class}) +@Import({ HttpStubsController.class, TriggerController.class, + StubRunnerConfiguration.class }) public @interface EnableStubRunnerServer { } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/server/HttpStubsController.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/server/HttpStubsController.java index 444a5fe8aa..d6f20d6fd4 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/server/HttpStubsController.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/server/HttpStubsController.java @@ -49,9 +49,10 @@ public class HttpStubsController { @RequestMapping(path = "/{ivy:.*}") public ResponseEntity consumer(@PathVariable String ivy) { Integer port = this.stubRunning.runStubs().getPort(ivy); - if (port!=null) { + if (port != null) { return ResponseEntity.ok(port); } return new ResponseEntity<>(HttpStatus.NOT_FOUND); } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/server/TriggerController.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/server/TriggerController.java index e3de4cce89..5b5b6861c1 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/server/TriggerController.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/server/TriggerController.java @@ -49,22 +49,32 @@ public class TriggerController { } @PostMapping("/{label:.*}") - public ResponseEntity>> trigger(@PathVariable String label) { + public ResponseEntity>> trigger( + @PathVariable String label) { try { this.stubFinder.trigger(label); - return ResponseEntity.ok().body(Collections.>emptyMap()); - } catch (Exception e) { - throw new RuntimeException("Exception occurred while trying to return [" + label + "] label. \n\nAvailable labels are [" + this.stubFinder.labels() +" ]", e); + return ResponseEntity.ok() + .body(Collections.>emptyMap()); + } + catch (Exception e) { + throw new RuntimeException("Exception occurred while trying to return [" + + label + "] label. \n\nAvailable labels are [" + + this.stubFinder.labels() + " ]", e); } } @PostMapping("/{ivyNotation:.*}/{label:.*}") - public ResponseEntity>> triggerByArtifact(@PathVariable String ivyNotation, @PathVariable String label) { + public ResponseEntity>> triggerByArtifact( + @PathVariable String ivyNotation, @PathVariable String label) { try { this.stubFinder.trigger(ivyNotation, label); - return ResponseEntity.ok().body(Collections.>emptyMap()); - } catch (Exception e) { - throw new RuntimeException("Exception occurred while trying to return [" + label + "] label. \n\nAvailable labels are [" + this.stubFinder.labels() +" ]", e); + return ResponseEntity.ok() + .body(Collections.>emptyMap()); + } + catch (Exception e) { + throw new RuntimeException("Exception occurred while trying to return [" + + label + "] label. \n\nAvailable labels are [" + + this.stubFinder.labels() + " ]", e); } } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/AutoConfigureStubRunner.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/AutoConfigureStubRunner.java index c5aba14dd0..5b3a44423c 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/AutoConfigureStubRunner.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/AutoConfigureStubRunner.java @@ -55,8 +55,9 @@ public @interface AutoConfigureStubRunner { String repositoryRoot() default ""; /** - * The ids of the stubs to run in "ivy" notation ([groupId]:artifactId[:version][:classifier][:port]). - * {@code groupId}, {@code version}, {@code classifier} and {@code port} can be optional. + * The ids of the stubs to run in "ivy" notation + * ([groupId]:artifactId[:version][:classifier][:port]). {@code groupId}, + * {@code version}, {@code classifier} and {@code port} can be optional. */ String[] ids() default {}; @@ -66,39 +67,50 @@ public @interface AutoConfigureStubRunner { String classifier() default "stubs"; /** - * On the producer side the consumers can have a folder that contains contracts related only to them. By setting the flag to {@code true} - * we no longer register all stubs but only those that correspond to the consumer application's name. In other words - * we'll scan the path of every stub and if it contains the name of the consumer in the path only then will it get registered. + * On the producer side the consumers can have a folder that contains contracts + * related only to them. By setting the flag to {@code true} we no longer register all + * stubs but only those that correspond to the consumer application's name. In other + * words we'll scan the path of every stub and if it contains the name of the consumer + * in the path only then will it get registered. * - * Let's look at this example. Let's assume - * that we have a producer called {@code foo} and two consumers {@code baz} and {@code bar}. On the {@code foo} producer side the + * Let's look at this example. Let's assume that we have a producer called {@code foo} + * and two consumers {@code baz} and {@code bar}. On the {@code foo} producer side the * contracts would look like this * {@code src/test/resources/contracts/baz-service/some/contracts/...} and * {@code src/test/resources/contracts/bar-service/some/contracts/...}. * - * Then when the consumer with {@code spring.application.name} or the {@link AutoConfigureStubRunner#consumerName()} - * annotation parameter set to {@code baz-service} will define the test setup as follows - * {@code @AutoConfigureStubRunner(ids = "com.example:foo:+:stubs:8095", stubsPerConsumer=true)} then only the stubs registered - * under {@code src/test/resources/contracts/baz-service/some/contracts/...} will get registered and those under - * {@code src/test/resources/contracts/bar-service/some/contracts/...} will get ignored. + * Then when the consumer with {@code spring.application.name} or the + * {@link AutoConfigureStubRunner#consumerName()} annotation parameter set to + * {@code baz-service} will define the test setup as follows + * {@code @AutoConfigureStubRunner(ids = "com.example:foo:+:stubs:8095", stubsPerConsumer=true)} + * then only the stubs registered under + * {@code src/test/resources/contracts/baz-service/some/contracts/...} will get + * registered and those under + * {@code src/test/resources/contracts/bar-service/some/contracts/...} will get + * ignored. * - * @see issue 224 + * @see issue 224 * */ boolean stubsPerConsumer() default false; /** - * You can override the default {@code spring.application.name} of this field by setting a value to this parameter. + * You can override the default {@code spring.application.name} of this field by + * setting a value to this parameter. * - * @see issue 224 + * @see issue 224 */ String consumerName() default ""; /** - * For debugging purposes you can output the registered mappings to a given folder. Each HTTP server - * stub will have its own subfolder where all the mappings will get stored. + * For debugging purposes you can output the registered mappings to a given folder. + * Each HTTP server stub will have its own subfolder where all the mappings will get + * stored. * - * @see issue 355 + * @see issue 355 */ String mappingsOutputFolder() default ""; @@ -114,4 +126,5 @@ public @interface AutoConfigureStubRunner { * @return the properties to add */ String[] properties() default {}; + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfiguration.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfiguration.java index af6db728e1..5b8377660e 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfiguration.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfiguration.java @@ -54,9 +54,12 @@ public class StubRunnerConfiguration { @Autowired(required = false) private MessageVerifier contractVerifierMessaging; + private StubDownloaderBuilderProvider provider = new StubDownloaderBuilderProvider(); + @Autowired private StubRunnerProperties props; + @Autowired private ConfigurableEnvironment environment; @@ -84,18 +87,17 @@ public class StubRunnerConfiguration { private StubRunnerOptionsBuilder builder() throws IOException { return new StubRunnerOptionsBuilder() - .withMinMaxPort(this.props.getMinPort(), this.props.getMaxPort()) - .withStubRepositoryRoot(this.props.getRepositoryRoot()) - .withStubsMode(this.props.getStubsMode()) - .withStubsClassifier(this.props.getClassifier()) - .withStubs(this.props.getIds()) - .withUsername(this.props.getUsername()) - .withPassword(this.props.getPassword()) - .withStubPerConsumer(this.props.isStubsPerConsumer()) - .withConsumerName(consumerName()) - .withMappingsOutputFolder(this.props.getMappingsOutputFolder()) - .withDeleteStubsAfterTest(this.props.isDeleteStubsAfterTest()) - .withProperties(this.props.getProperties()); + .withMinMaxPort(this.props.getMinPort(), this.props.getMaxPort()) + .withStubRepositoryRoot(this.props.getRepositoryRoot()) + .withStubsMode(this.props.getStubsMode()) + .withStubsClassifier(this.props.getClassifier()) + .withStubs(this.props.getIds()).withUsername(this.props.getUsername()) + .withPassword(this.props.getPassword()) + .withStubPerConsumer(this.props.isStubsPerConsumer()) + .withConsumerName(consumerName()) + .withMappingsOutputFolder(this.props.getMappingsOutputFolder()) + .withDeleteStubsAfterTest(this.props.isDeleteStubsAfterTest()) + .withProperties(this.props.getProperties()); } private String consumerName() { @@ -108,15 +110,19 @@ public class StubRunnerConfiguration { private void registerPort(RunningStubs runStubs) { MutablePropertySources propertySources = this.environment.getPropertySources(); if (!propertySources.contains(STUBRUNNER_PREFIX)) { - propertySources.addFirst( - new MapPropertySource(STUBRUNNER_PREFIX, new HashMap())); + propertySources.addFirst(new MapPropertySource(STUBRUNNER_PREFIX, + new HashMap())); } Map source = ((MapPropertySource) propertySources .get(STUBRUNNER_PREFIX)).getSource(); - for (Map.Entry entry : runStubs.validNamesAndPorts().entrySet()) { - source.put(STUBRUNNER_PREFIX + "." + entry.getKey().getArtifactId() + ".port", entry.getValue()); - // there are projects where artifact id is the same, what differs is the group id - source.put(STUBRUNNER_PREFIX + "." + entry.getKey().getGroupId() + "." + entry.getKey().getArtifactId() + ".port", entry.getValue()); + for (Map.Entry entry : runStubs.validNamesAndPorts() + .entrySet()) { + source.put(STUBRUNNER_PREFIX + "." + entry.getKey().getArtifactId() + ".port", + entry.getValue()); + // there are projects where artifact id is the same, what differs is the group + // id + source.put(STUBRUNNER_PREFIX + "." + entry.getKey().getGroupId() + "." + + entry.getKey().getArtifactId() + ".port", entry.getValue()); } } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/StubRunnerPort.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/StubRunnerPort.java index c6c202c2d8..fcde1763cc 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/StubRunnerPort.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/StubRunnerPort.java @@ -7,13 +7,12 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * The annotated field with this annotation will have the port of a running stub - * injected. + * The annotated field with this annotation will have the port of a running stub injected. * * @author Marcin Grzejszczak * @since 2.0.0 */ -@Target({ElementType.FIELD}) +@Target({ ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface StubRunnerPort { diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/StubRunnerPortBeanPostProcessor.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/StubRunnerPortBeanPostProcessor.java index 54fb9a1e2e..daabea879c 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/StubRunnerPortBeanPostProcessor.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/StubRunnerPortBeanPostProcessor.java @@ -21,7 +21,8 @@ class StubRunnerPortBeanPostProcessor implements BeanPostProcessor { this.environment = environment; } - @Override public Object postProcessAfterInitialization(Object bean, String beanName) + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { injectStubRunnerPort(bean); return bean; @@ -29,15 +30,17 @@ class StubRunnerPortBeanPostProcessor implements BeanPostProcessor { private void injectStubRunnerPort(Object bean) { Class clazz = bean.getClass(); - ReflectionUtils.FieldCallback fieldCallback = - new StubRunnerPortFieldCallback(this.environment, bean); + ReflectionUtils.FieldCallback fieldCallback = new StubRunnerPortFieldCallback( + this.environment, bean); ReflectionUtils.doWithFields(clazz, fieldCallback); } + } class StubRunnerPortFieldCallback implements ReflectionUtils.FieldCallback { private final Environment environment; + private final Object bean; StubRunnerPortFieldCallback(Environment environment, Object bean) { @@ -45,17 +48,20 @@ class StubRunnerPortFieldCallback implements ReflectionUtils.FieldCallback { this.bean = bean; } - @Override public void doWith(Field field) + @Override + public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { if (!field.isAnnotationPresent(StubRunnerPort.class)) { return; } ReflectionUtils.makeAccessible(field); String stub = field.getDeclaredAnnotation(StubRunnerPort.class).value(); - Integer port = this.environment.getProperty( - StubRunnerConfiguration.STUBRUNNER_PREFIX + "." + stub.replace(":", ".") + ".port", Integer.class); + Integer port = this.environment + .getProperty(StubRunnerConfiguration.STUBRUNNER_PREFIX + "." + + stub.replace(":", ".") + ".port", Integer.class); if (port != null) { field.set(this.bean, port); } } + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/StubRunnerProperties.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/StubRunnerProperties.java index 926ad8486a..3cc6dc3034 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/StubRunnerProperties.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/StubRunnerProperties.java @@ -49,8 +49,9 @@ public class StubRunnerProperties { private Resource repositoryRoot; /** - * The ids of the stubs to run in "ivy" notation ([groupId]:artifactId:[version]:[classifier][:port]). - * {@code groupId}, {@code classifier}, {@code version} and {@code port} can be optional. + * The ids of the stubs to run in "ivy" notation + * ([groupId]:artifactId:[version]:[classifier][:port]). {@code groupId}, + * {@code classifier}, {@code version} and {@code port} can be optional. */ private String[] ids = new String[0]; @@ -85,7 +86,8 @@ public class StubRunnerProperties { private boolean stubsPerConsumer; /** - * You can override the default {@code spring.application.name} of this field by setting a value to this parameter. + * You can override the default {@code spring.application.name} of this field by + * setting a value to this parameter. */ private String consumerName; @@ -100,13 +102,14 @@ public class StubRunnerProperties { private StubsMode stubsMode; /** - * If set to {@code false} will NOT delete stubs from a temporary - * folder after running tests + * If set to {@code false} will NOT delete stubs from a temporary folder after running + * tests */ private boolean deleteStubsAfterTest = true; /** - * Map of properties that can be passed to custom {@link org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder} + * Map of properties that can be passed to custom + * {@link org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder} */ private Map properties = new HashMap<>(); @@ -129,6 +132,7 @@ public class StubRunnerProperties { * Fetch the stubs from a remote location */ REMOTE, + } public int getMinPort() { @@ -248,8 +252,8 @@ public class StubRunnerProperties { } public void setProperties(String[] properties) { - Properties elements = StringUtils - .splitArrayElementsIntoProperties(properties, "="); + Properties elements = StringUtils.splitArrayElementsIntoProperties(properties, + "="); if (elements == null) { return; } @@ -258,13 +262,14 @@ public class StubRunnerProperties { } } - @Override public String toString() { - return "StubRunnerProperties{" + "minPort=" + this.minPort + ", maxPort=" + this.maxPort - + ", repositoryRoot=" + this.repositoryRoot - + ", ids=" + Arrays.toString(this.ids) + ", classifier='" + this.classifier + '\'' - + ", setStubsPerConsumer='" + this.stubsPerConsumer + "', consumerName='" + this.consumerName + '\'' - + ", stubsMode='" + this.stubsMode + '\'' - + ", size of properties=" + this.properties.size() - + '}'; + @Override + public String toString() { + return "StubRunnerProperties{" + "minPort=" + this.minPort + ", maxPort=" + + this.maxPort + ", repositoryRoot=" + this.repositoryRoot + ", ids=" + + Arrays.toString(this.ids) + ", classifier='" + this.classifier + '\'' + + ", setStubsPerConsumer='" + this.stubsPerConsumer + "', consumerName='" + + this.consumerName + '\'' + ", stubsMode='" + this.stubsMode + '\'' + + ", size of properties=" + this.properties.size() + '}'; } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ConditionalOnStubbedDiscoveryDisabled.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ConditionalOnStubbedDiscoveryDisabled.java index 290b7c3d94..cbd54032e7 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ConditionalOnStubbedDiscoveryDisabled.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ConditionalOnStubbedDiscoveryDisabled.java @@ -36,4 +36,5 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @Documented @ConditionalOnProperty(value = "stubrunner.cloud.stubbed.discovery.enabled", havingValue = "false") public @interface ConditionalOnStubbedDiscoveryDisabled { + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ConditionalOnStubbedDiscoveryEnabled.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ConditionalOnStubbedDiscoveryEnabled.java index 3d0b81392b..a7c75056b5 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ConditionalOnStubbedDiscoveryEnabled.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ConditionalOnStubbedDiscoveryEnabled.java @@ -25,8 +25,8 @@ import java.lang.annotation.Target; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; /** - * Conditional that checks if the user turned on the stubbed discovery mode. - * The feature is turned on by default. + * Conditional that checks if the user turned on the stubbed discovery mode. The feature + * is turned on by default. * * @author Marcin Grzejszczak * @@ -37,4 +37,5 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @Documented @ConditionalOnProperty(value = "stubrunner.cloud.stubbed.discovery.enabled", havingValue = "true", matchIfMissing = true) public @interface ConditionalOnStubbedDiscoveryEnabled { + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubMapperProperties.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubMapperProperties.java index edee0cad48..6cd59be3c9 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubMapperProperties.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubMapperProperties.java @@ -24,30 +24,27 @@ import org.springframework.cloud.contract.stubrunner.StubConfiguration; import org.springframework.util.StringUtils; /** - * Maps Ivy based ids to service Ids. You might want to name the service you're calling - * in another way than artifact id. If that's the case then this class should be used - * to change do the proper mapping. + * Maps Ivy based ids to service Ids. You might want to name the service you're calling in + * another way than artifact id. If that's the case then this class should be used to + * change do the proper mapping. * * Just provide in your properties file for example: * - * stubrunner.idsToServiceIds: - * fraudDetectionServer: someNameThatShouldMapFraudDetectionServer + * stubrunner.idsToServiceIds: fraudDetectionServer: + * someNameThatShouldMapFraudDetectionServer * * @author Marcin Grzejszczak - * * @since 1.0.0 */ @ConfigurationProperties("stubrunner") public class StubMapperProperties { /** - * Mapping of Ivy notation based ids to serviceIds - * inside your application + * Mapping of Ivy notation based ids to serviceIds inside your application * * Example * - * "a:b" -> "myService" - * "artifactId" -> "myOtherService" + * "a:b" -> "myService" "artifactId" -> "myOtherService" */ private Map idsToServiceIds = new HashMap<>(); @@ -65,8 +62,8 @@ public class StubMapperProperties { if (StringUtils.hasText(id)) { return id; } - String groupAndArtifact = this.idsToServiceIds.get(stubConfiguration.getGroupId() + - ":" + stubConfiguration.getArtifactId()); + String groupAndArtifact = this.idsToServiceIds.get( + stubConfiguration.getGroupId() + ":" + stubConfiguration.getArtifactId()); if (StringUtils.hasText(groupAndArtifact)) { return groupAndArtifact; } @@ -81,4 +78,5 @@ public class StubMapperProperties { } return null; } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerDiscoveryClient.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerDiscoveryClient.java index 243514b4b2..ca059d59f7 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerDiscoveryClient.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerDiscoveryClient.java @@ -32,27 +32,30 @@ import org.springframework.cloud.contract.stubrunner.StubFinder; import org.springframework.util.StringUtils; /** - * Custom version of {@link DiscoveryClient} that tries to find an instance - * in one of the started WireMock servers + * Custom version of {@link DiscoveryClient} that tries to find an instance in one of the + * started WireMock servers * * @author Marcin Grzejszczak - * * @since 1.0.0 */ class StubRunnerDiscoveryClient implements DiscoveryClient { - private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); + private static final Log log = LogFactory + .getLog(MethodHandles.lookup().lookupClass()); private final DiscoveryClient delegate; + private final StubFinder stubFinder; + private final StubMapperProperties stubMapperProperties; public StubRunnerDiscoveryClient(DiscoveryClient delegate, StubFinder stubFinder, StubMapperProperties stubMapperProperties, String springAppName) { - this.delegate = delegate instanceof StubRunnerDiscoveryClient ? - noOpDiscoveryClient() : delegate; + this.delegate = delegate instanceof StubRunnerDiscoveryClient + ? noOpDiscoveryClient() : delegate; if (log.isDebugEnabled()) { - log.debug("Will delegate calls to discovery service [" + this.delegate + "] if a stub is not found"); + log.debug("Will delegate calls to discovery service [" + this.delegate + + "] if a stub is not found"); } this.stubFinder = stubFinder; this.stubMapperProperties = stubMapperProperties; @@ -62,7 +65,8 @@ class StubRunnerDiscoveryClient implements DiscoveryClient { StubMapperProperties stubMapperProperties, String springAppName) { this.delegate = noOpDiscoveryClient(); if (log.isDebugEnabled()) { - log.debug("Will delegate calls to discovery service [" + this.delegate + "] if a stub is not found"); + log.debug("Will delegate calls to discovery service [" + this.delegate + + "] if a stub is not found"); } this.stubFinder = stubFinder; this.stubMapperProperties = stubMapperProperties; @@ -76,7 +80,8 @@ class StubRunnerDiscoveryClient implements DiscoveryClient { public String description() { try { return this.delegate.description(); - } catch (Exception e) { + } + catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to fetch description from delegate", e); } @@ -86,23 +91,25 @@ class StubRunnerDiscoveryClient implements DiscoveryClient { @Override public List getInstances(String serviceId) { - String ivyNotation = this.stubMapperProperties.fromServiceIdToIvyNotation(serviceId); + String ivyNotation = this.stubMapperProperties + .fromServiceIdToIvyNotation(serviceId); String serviceToFind = StringUtils.hasText(ivyNotation) ? ivyNotation : serviceId; URL stubUrl = this.stubFinder.findStubUrl(serviceToFind); - log.info("Resolved from ivy [" + ivyNotation + "] service to find [" + serviceToFind + "]. " - + "Found stub is available under URL [" + stubUrl + "]"); + log.info("Resolved from ivy [" + ivyNotation + "] service to find [" + + serviceToFind + "]. " + "Found stub is available under URL [" + stubUrl + + "]"); if (stubUrl == null) { return getInstancesFromDelegate(serviceId); } - return Collections.singletonList( - new StubRunnerServiceInstance(serviceId, stubUrl.getHost(), stubUrl.getPort(), toUri(stubUrl)) - ); + return Collections.singletonList(new StubRunnerServiceInstance( + serviceId, stubUrl.getHost(), stubUrl.getPort(), toUri(stubUrl))); } private List getInstancesFromDelegate(String serviceId) { try { return new ArrayList<>(this.delegate.getInstances(serviceId)); - } catch (Exception e) { + } + catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to fetch instances from delegate", e); } @@ -113,7 +120,8 @@ class StubRunnerDiscoveryClient implements DiscoveryClient { private URI toUri(URL url) { try { return url.toURI(); - } catch (Exception e) { + } + catch (Exception e) { return null; } } @@ -131,7 +139,8 @@ class StubRunnerDiscoveryClient implements DiscoveryClient { private List getServicesFromDelegate() { try { return new ArrayList<>(this.delegate.getServices()); - } catch (Exception e) { + } + catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to fetch services from delegate", e); } @@ -143,6 +152,7 @@ class StubRunnerDiscoveryClient implements DiscoveryClient { public int getOrder() { return this.delegate.getOrder(); } + } class StubRunnerNoOpDiscoveryClient implements DiscoveryClient { @@ -161,4 +171,5 @@ class StubRunnerNoOpDiscoveryClient implements DiscoveryClient { public List getServices() { return Collections.emptyList(); } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerServiceInstance.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerServiceInstance.java index d7cfb65cbe..f16ad745e7 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerServiceInstance.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerServiceInstance.java @@ -26,14 +26,16 @@ import org.springframework.cloud.client.ServiceInstance; * {@link ServiceInstance} with a helpful constructor * * @author Marcin Grzejszczak - * * @since 1.0.0 */ class StubRunnerServiceInstance implements ServiceInstance { private final String serviceId; + private final String host; + private final int port; + private final URI uri; public StubRunnerServiceInstance(String serviceId, String host, int port, URI uri) { @@ -72,4 +74,5 @@ class StubRunnerServiceInstance implements ServiceInstance { public Map getMetadata() { return new HashMap<>(); } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerSpringCloudAutoConfiguration.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerSpringCloudAutoConfiguration.java index 832b533db6..a4017c60bd 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerSpringCloudAutoConfiguration.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerSpringCloudAutoConfiguration.java @@ -32,8 +32,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; /** - * Wraps {@link DiscoveryClient} in a Stub Runner implementation that tries to find - * a corresponding WireMock server for a searched dependency + * Wraps {@link DiscoveryClient} in a Stub Runner implementation that tries to find a + * corresponding WireMock server for a searched dependency * * @since 1.0.0 */ @@ -43,7 +43,8 @@ import org.springframework.core.env.Environment; @ConditionalOnProperty(value = "stubrunner.cloud.enabled", matchIfMissing = true) public class StubRunnerSpringCloudAutoConfiguration { - @Autowired BeanFactory beanFactory; + @Autowired + BeanFactory beanFactory; @Bean public StubRunnerDiscoveryClientWrapper stubRunnerDiscoveryClientWrapper() { @@ -57,7 +58,8 @@ public class StubRunnerSpringCloudAutoConfiguration { public DiscoveryClient noOpStubRunnerDiscoveryClient(StubFinder stubFinder, StubMapperProperties stubMapperProperties, @Value("${spring.application.name:unknown}") String springAppName) { - return new StubRunnerDiscoveryClient(stubFinder, stubMapperProperties, springAppName); + return new StubRunnerDiscoveryClient(stubFinder, stubMapperProperties, + springAppName); } } @@ -65,33 +67,43 @@ public class StubRunnerSpringCloudAutoConfiguration { class StubRunnerDiscoveryClientWrapper implements BeanPostProcessor { private final BeanFactory beanFactory; + DiscoveryClient discoveryClient; + StubFinder stubFinder; + StubMapperProperties stubMapperProperties; + String springAppName; + Boolean stubbedDiscoveryEnabled; + Boolean cloudDelegateEnabled; StubRunnerDiscoveryClientWrapper(BeanFactory beanFactory) { this.beanFactory = beanFactory; } - @Override public Object postProcessBeforeInitialization(Object bean, String beanName) + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } - @Override public Object postProcessAfterInitialization(Object bean, String beanName) + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - if (bean instanceof DiscoveryClient && !(bean instanceof StubRunnerDiscoveryClient)) { + if (bean instanceof DiscoveryClient + && !(bean instanceof StubRunnerDiscoveryClient)) { if (!isStubbedDiscoveryEnabled()) { return bean; } if (isCloudDelegateEnabled()) { - return new StubRunnerDiscoveryClient((DiscoveryClient) bean, - stubFinder(), stubMapperProperties(), springAppName()); + return new StubRunnerDiscoveryClient((DiscoveryClient) bean, stubFinder(), + stubMapperProperties(), springAppName()); } - return new StubRunnerDiscoveryClient(stubFinder(), stubMapperProperties(), springAppName()); + return new StubRunnerDiscoveryClient(stubFinder(), stubMapperProperties(), + springAppName()); } return bean; } @@ -105,7 +117,8 @@ class StubRunnerDiscoveryClientWrapper implements BeanPostProcessor { StubMapperProperties stubMapperProperties() { if (this.stubMapperProperties == null) { - this.stubMapperProperties = this.beanFactory.getBean(StubMapperProperties.class); + this.stubMapperProperties = this.beanFactory + .getBean(StubMapperProperties.class); } return this.stubMapperProperties; } @@ -120,21 +133,20 @@ class StubRunnerDiscoveryClientWrapper implements BeanPostProcessor { boolean isStubbedDiscoveryEnabled() { if (this.stubbedDiscoveryEnabled == null) { - this.stubbedDiscoveryEnabled = Boolean.valueOf( - this.beanFactory.getBean(Environment.class) - .getProperty("stubrunner.cloud.stubbed.discovery.enabled", "true") - ); + this.stubbedDiscoveryEnabled = Boolean + .valueOf(this.beanFactory.getBean(Environment.class).getProperty( + "stubrunner.cloud.stubbed.discovery.enabled", "true")); } return this.stubbedDiscoveryEnabled; } boolean isCloudDelegateEnabled() { if (this.cloudDelegateEnabled == null) { - this.cloudDelegateEnabled = Boolean.valueOf( - this.beanFactory.getBean(Environment.class) - .getProperty("stubrunner.cloud.delegate.enabled", "false") - ); + this.cloudDelegateEnabled = Boolean + .valueOf(this.beanFactory.getBean(Environment.class) + .getProperty("stubrunner.cloud.delegate.enabled", "false")); } return this.cloudDelegateEnabled; } + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubsRegistrar.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubsRegistrar.java index 0a344e4355..5ef7755245 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubsRegistrar.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/StubsRegistrar.java @@ -4,9 +4,10 @@ package org.springframework.cloud.contract.stubrunner.spring.cloud; * Contract for registering stubs in a Service Discovery. * * @author Marcin Grzejszczak - * * @since 1.0.0 */ public interface StubsRegistrar extends AutoCloseable { + void registerStubs(); + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/consul/ConsulStubsRegistrar.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/consul/ConsulStubsRegistrar.java index 6b4fa7c0ff..6aa61477f7 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/consul/ConsulStubsRegistrar.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/consul/ConsulStubsRegistrar.java @@ -20,24 +20,28 @@ import org.springframework.util.StringUtils; * Registers all stubs in Zookeeper Service Discovery * * @author Marcin Grzejszczak - * * @since 1.0.0 */ public class ConsulStubsRegistrar implements StubsRegistrar { - private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); + private static final Log log = LogFactory + .getLog(MethodHandles.lookup().lookupClass()); private final StubRunning stubRunning; + private final ConsulClient consulClient; + private final StubMapperProperties stubMapperProperties; + private final ConsulDiscoveryProperties consulDiscoveryProperties; + private final InetUtils inetUtils; + private final List services = new LinkedList<>(); public ConsulStubsRegistrar(StubRunning stubRunning, ConsulClient consulClient, - StubMapperProperties stubMapperProperties, - ConsulDiscoveryProperties consulDiscoveryProperties, - InetUtils inetUtils) { + StubMapperProperties stubMapperProperties, + ConsulDiscoveryProperties consulDiscoveryProperties, InetUtils inetUtils) { this.stubRunning = stubRunning; this.consulClient = consulClient; this.stubMapperProperties = stubMapperProperties; @@ -45,7 +49,8 @@ public class ConsulStubsRegistrar implements StubsRegistrar { this.inetUtils = inetUtils; } - @Override public void registerStubs() { + @Override + public void registerStubs() { Map activeStubs = this.stubRunning.runStubs() .validNamesAndPorts(); for (Map.Entry entry : activeStubs.entrySet()) { @@ -54,12 +59,14 @@ public class ConsulStubsRegistrar implements StubsRegistrar { try { this.consulClient.agentServiceRegister(newService); if (log.isDebugEnabled()) { - log.debug("Successfully registered stub [" + entry.getKey().toColonSeparatedDependencyNotation() + log.debug("Successfully registered stub [" + + entry.getKey().toColonSeparatedDependencyNotation() + "] in Service Discovery"); } } catch (Exception e) { - log.warn("Exception occurred while trying to register a stub [" + entry.getKey().toColonSeparatedDependencyNotation() + log.warn("Exception occurred while trying to register a stub [" + + entry.getKey().toColonSeparatedDependencyNotation() + "] in Service Discovery", e); } } @@ -67,9 +74,10 @@ public class ConsulStubsRegistrar implements StubsRegistrar { protected NewService newService(StubConfiguration stubConfiguration, Integer port) { NewService newService = new NewService(); - newService.setAddress(StringUtils.hasText(this.consulDiscoveryProperties.getHostname()) ? - this.consulDiscoveryProperties.getHostname() : - this.inetUtils.findFirstNonLoopbackAddress().getHostName()); + newService.setAddress( + StringUtils.hasText(this.consulDiscoveryProperties.getHostname()) + ? this.consulDiscoveryProperties.getHostname() + : this.inetUtils.findFirstNonLoopbackAddress().getHostName()); newService.setId(stubConfiguration.getArtifactId()); newService.setName(name(stubConfiguration)); newService.setPort(port); @@ -91,4 +99,5 @@ public class ConsulStubsRegistrar implements StubsRegistrar { this.consulClient.agentServiceDeregister(service.getId()); } } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/consul/StubRunnerSpringCloudConsulAutoConfiguration.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/consul/StubRunnerSpringCloudConsulAutoConfiguration.java index 6dffca3cd2..ef782b84a8 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/consul/StubRunnerSpringCloudConsulAutoConfiguration.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/consul/StubRunnerSpringCloudConsulAutoConfiguration.java @@ -38,19 +38,19 @@ import org.springframework.context.annotation.Configuration; * @since 1.0.0 */ @Configuration -@AutoConfigureAfter(value = {StubRunnerConfiguration.class, - ConsulServiceRegistryAutoConfiguration.class}) +@AutoConfigureAfter(value = { StubRunnerConfiguration.class, + ConsulServiceRegistryAutoConfiguration.class }) @ConditionalOnClass(ConsulClient.class) @ConditionalOnStubbedDiscoveryDisabled @ConditionalOnProperty(value = "stubrunner.cloud.consul.enabled", matchIfMissing = true) public class StubRunnerSpringCloudConsulAutoConfiguration { @Bean(initMethod = "registerStubs") - public StubsRegistrar stubsRegistrar(StubRunning stubRunning, ConsulClient consulClient, - StubMapperProperties stubMapperProperties, - ConsulDiscoveryProperties consulDiscoveryProperties, - InetUtils inetUtils) { + public StubsRegistrar stubsRegistrar(StubRunning stubRunning, + ConsulClient consulClient, StubMapperProperties stubMapperProperties, + ConsulDiscoveryProperties consulDiscoveryProperties, InetUtils inetUtils) { return new ConsulStubsRegistrar(stubRunning, consulClient, stubMapperProperties, - consulDiscoveryProperties, inetUtils); + consulDiscoveryProperties, inetUtils); } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/eureka/ConditionalOnEurekaEnabled.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/eureka/ConditionalOnEurekaEnabled.java index 1e202a722b..4fa0c722b2 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/eureka/ConditionalOnEurekaEnabled.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/eureka/ConditionalOnEurekaEnabled.java @@ -36,4 +36,5 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @Documented @ConditionalOnProperty(value = "eureka.client.enabled", havingValue = "true", matchIfMissing = true) @interface ConditionalOnEurekaEnabled { + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/eureka/EurekaStubsRegistrar.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/eureka/EurekaStubsRegistrar.java index e1ff0f1905..d404e647c2 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/eureka/EurekaStubsRegistrar.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/eureka/EurekaStubsRegistrar.java @@ -32,28 +32,34 @@ import com.netflix.discovery.EurekaClient; * Registers all stubs in Eureka Service Discovery * * @author Marcin Grzejszczak - * * @since 1.0.0 */ public class EurekaStubsRegistrar implements StubsRegistrar { - private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); + private static final Log log = LogFactory + .getLog(MethodHandles.lookup().lookupClass()); private final StubRunning stubRunning; + private final StubMapperProperties stubMapperProperties; + private final InetUtils inetUtils; + private final EurekaInstanceConfigBean eurekaInstanceConfigBean; + private final EurekaClientConfigBean eurekaClientConfigBean; + private final List registrations = new LinkedList<>(); + private final ServiceRegistry serviceRegistry; + private final ApplicationContext context; public EurekaStubsRegistrar(StubRunning stubRunning, ServiceRegistry serviceRegistry, StubMapperProperties stubMapperProperties, InetUtils inetUtils, EurekaInstanceConfigBean eurekaInstanceConfigBean, - EurekaClientConfigBean eurekaClientConfigBean, - ApplicationContext context) { + EurekaClientConfigBean eurekaClientConfigBean, ApplicationContext context) { this.stubRunning = stubRunning; this.stubMapperProperties = stubMapperProperties; this.serviceRegistry = serviceRegistry; @@ -63,7 +69,8 @@ public class EurekaStubsRegistrar implements StubsRegistrar { this.context = context; } - @Override public void registerStubs() { + @Override + public void registerStubs() { Map activeStubs = this.stubRunning.runStubs() .validNamesAndPorts(); for (Map.Entry entry : activeStubs.entrySet()) { @@ -72,21 +79,23 @@ public class EurekaStubsRegistrar implements StubsRegistrar { + instance.getHostname() + ", " + instance.getNonSecurePort() + ", " + instance.getInstanceId() + "]"); InstanceInfo instanceInfo = new InstanceInfoFactory().create(instance); - ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(instance, instanceInfo); + ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager( + instance, instanceInfo); AbstractDiscoveryClientOptionalArgs args = args(); - EurekaClient client = new CloudEurekaClient(applicationInfoManager, this.eurekaClientConfigBean, args, this.context); + EurekaClient client = new CloudEurekaClient(applicationInfoManager, + this.eurekaClientConfigBean, args, this.context); EurekaRegistration registration = EurekaRegistration.builder(instance) - .with(this.eurekaClientConfigBean, this.context) - .with(client) - .build(); + .with(this.eurekaClientConfigBean, this.context).with(client).build(); this.registrations.add(registration); try { this.serviceRegistry.register(registration); - log.info("Successfully registered stub " + "[" + entry.getKey() - .toColonSeparatedDependencyNotation() + "] in Service Discovery"); + log.info("Successfully registered stub " + "[" + + entry.getKey().toColonSeparatedDependencyNotation() + + "] in Service Discovery"); } catch (Exception e) { - log.warn("Exception occurred while trying to register a stub [" + entry.getKey().toColonSeparatedDependencyNotation() + log.warn("Exception occurred while trying to register a stub [" + + entry.getKey().toColonSeparatedDependencyNotation() + "] in Service Discovery", e); } } @@ -94,27 +103,29 @@ public class EurekaStubsRegistrar implements StubsRegistrar { private AbstractDiscoveryClientOptionalArgs args() { try { - return this.context - .getBean(AbstractDiscoveryClientOptionalArgs.class); - } catch (BeansException e) { + return this.context.getBean(AbstractDiscoveryClientOptionalArgs.class); + } + catch (BeansException e) { return null; } } - private EurekaInstanceConfigBean registration(Map.Entry entry) { + private EurekaInstanceConfigBean registration( + Map.Entry entry) { EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(this.inetUtils); String appName = name(entry.getKey()); config.setInstanceEnabledOnit(true); InetAddress address = this.inetUtils.findFirstNonLoopbackAddress(); config.setIpAddress(address.getHostAddress()); - config.setHostname(StringUtils.hasText(hostName(entry)) ? - hostName(entry) : address.getHostName()); + config.setHostname(StringUtils.hasText(hostName(entry)) ? hostName(entry) + : address.getHostName()); config.setAppname(appName); config.setVirtualHostName(appName); config.setSecureVirtualHostName(appName); int port = port(entry); config.setNonSecurePort(port); - config.setInstanceId(address.getHostAddress() + ":" + entry.getKey().getArtifactId() + ":" + port); + config.setInstanceId(address.getHostAddress() + ":" + + entry.getKey().getArtifactId() + ":" + port); config.setLeaseRenewalIntervalInSeconds(1); return config; } @@ -142,4 +153,5 @@ public class EurekaStubsRegistrar implements StubsRegistrar { this.serviceRegistry.deregister(registration); } } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/eureka/StubRunnerSpringCloudEurekaAutoConfiguration.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/eureka/StubRunnerSpringCloudEurekaAutoConfiguration.java index 08fda3ec9c..e7535563f3 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/eureka/StubRunnerSpringCloudEurekaAutoConfiguration.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/eureka/StubRunnerSpringCloudEurekaAutoConfiguration.java @@ -47,11 +47,11 @@ import org.springframework.core.env.Environment; * Autoconfiguration for registering stubs in a Eureka Service discovery * * @author Marcin Grzejszczak - * * @since 1.0.0 */ @Configuration -@AutoConfigureAfter({StubRunnerConfiguration.class, EurekaClientAutoConfiguration.class}) +@AutoConfigureAfter({ StubRunnerConfiguration.class, + EurekaClientAutoConfiguration.class }) @ConditionalOnClass(CloudEurekaClient.class) @ConditionalOnStubbedDiscoveryDisabled @ConditionalOnEurekaEnabled @@ -61,43 +61,58 @@ public class StubRunnerSpringCloudEurekaAutoConfiguration { @Profile("!cloud") @Configuration protected static class NonCloudConfig { + @Bean(initMethod = "registerStubs") public StubsRegistrar stubsRegistrar(StubRunning stubRunning, - ServiceRegistry serviceRegistry, ApplicationContext context, - StubMapperProperties stubMapperProperties, InetUtils inetUtils, - EurekaInstanceConfigBean eurekaInstanceConfigBean, EurekaClientConfigBean eurekaClientConfigBean) { - return new EurekaStubsRegistrar(stubRunning, serviceRegistry, stubMapperProperties, inetUtils, - eurekaInstanceConfigBean, eurekaClientConfigBean, context); + ServiceRegistry serviceRegistry, + ApplicationContext context, StubMapperProperties stubMapperProperties, + InetUtils inetUtils, EurekaInstanceConfigBean eurekaInstanceConfigBean, + EurekaClientConfigBean eurekaClientConfigBean) { + return new EurekaStubsRegistrar(stubRunning, serviceRegistry, + stubMapperProperties, inetUtils, eurekaInstanceConfigBean, + eurekaClientConfigBean, context); } + } @Profile("cloud") @Configuration protected static class CloudConfig { + private static final int DEFAULT_PORT = 80; + private static final Log log = LogFactory.getLog(CloudConfig.class); - @Autowired Environment environment; + @Autowired + Environment environment; @Bean(initMethod = "registerStubs") public StubsRegistrar stubsRegistrar(StubRunning stubRunning, - ServiceRegistry serviceRegistry, ApplicationContext context, - StubMapperProperties stubMapperProperties, InetUtils inetUtils, - EurekaInstanceConfigBean eurekaInstanceConfigBean, EurekaClientConfigBean eurekaClientConfigBean) { - return new EurekaStubsRegistrar(stubRunning, serviceRegistry, stubMapperProperties, inetUtils, - eurekaInstanceConfigBean, eurekaClientConfigBean, context) { - @Override protected String hostName(Map.Entry entry) { - String hostname = - CloudConfig.this.environment.getProperty("application.hostname") + - "-" + entry.getValue() + "." + CloudConfig.this.environment.getProperty("application.domain"); - log.info("Registering stub [" + entry.getKey().getArtifactId() + "] with hostname [" + hostname + "]"); + ServiceRegistry serviceRegistry, + ApplicationContext context, StubMapperProperties stubMapperProperties, + InetUtils inetUtils, EurekaInstanceConfigBean eurekaInstanceConfigBean, + EurekaClientConfigBean eurekaClientConfigBean) { + return new EurekaStubsRegistrar(stubRunning, serviceRegistry, + stubMapperProperties, inetUtils, eurekaInstanceConfigBean, + eurekaClientConfigBean, context) { + @Override + protected String hostName(Map.Entry entry) { + String hostname = CloudConfig.this.environment + .getProperty("application.hostname") + "-" + entry.getValue() + + "." + CloudConfig.this.environment + .getProperty("application.domain"); + log.info("Registering stub [" + entry.getKey().getArtifactId() + + "] with hostname [" + hostname + "]"); return hostname; } - @Override protected int port(Map.Entry entry) { + @Override + protected int port(Map.Entry entry) { return DEFAULT_PORT; } }; } + } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ribbon/StubRunnerRibbonBeanPostProcessor.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ribbon/StubRunnerRibbonBeanPostProcessor.java index 4284a5c82e..3d1072c835 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ribbon/StubRunnerRibbonBeanPostProcessor.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ribbon/StubRunnerRibbonBeanPostProcessor.java @@ -26,18 +26,20 @@ import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.ServerList; /** - * Ribbon AutoConfiguration that manipulates the service id to make the service - * be picked from the list of available WireMock instance if one is available. + * Ribbon AutoConfiguration that manipulates the service id to make the service be picked + * from the list of available WireMock instance if one is available. * * @author Marcin Grzejszczak - * * @since 1.0.0 */ class StubRunnerRibbonBeanPostProcessor implements BeanPostProcessor { private final BeanFactory beanFactory; + private StubFinder stubFinder; + private StubMapperProperties stubMapperProperties; + private IClientConfig clientConfig; StubRunnerRibbonBeanPostProcessor(BeanFactory beanFactory) { @@ -53,7 +55,8 @@ class StubRunnerRibbonBeanPostProcessor implements BeanPostProcessor { private StubMapperProperties stubMapperProperties() { if (this.stubMapperProperties == null) { - this.stubMapperProperties = this.beanFactory.getBean(StubMapperProperties.class); + this.stubMapperProperties = this.beanFactory + .getBean(StubMapperProperties.class); } return this.stubMapperProperties; } @@ -66,15 +69,19 @@ class StubRunnerRibbonBeanPostProcessor implements BeanPostProcessor { } @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) + throws BeansException { if (bean instanceof ServerList && !(bean instanceof StubRunnerRibbonServerList)) { - return new StubRunnerRibbonServerList(stubFinder(), stubMapperProperties(), clientConfig()); + return new StubRunnerRibbonServerList(stubFinder(), stubMapperProperties(), + clientConfig()); } return bean; } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) + throws BeansException { return bean; } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ribbon/StubRunnerRibbonConfiguration.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ribbon/StubRunnerRibbonConfiguration.java index fb6aa3f371..b0296c5ea3 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ribbon/StubRunnerRibbonConfiguration.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ribbon/StubRunnerRibbonConfiguration.java @@ -32,8 +32,10 @@ import org.springframework.context.annotation.Role; @Configuration @Role(BeanDefinition.ROLE_INFRASTRUCTURE) class StubRunnerRibbonConfiguration { + @Bean - static StubRunnerRibbonBeanPostProcessor stubRunnerRibbonBeanPostProcessor(BeanFactory beanFactory) { + static StubRunnerRibbonBeanPostProcessor stubRunnerRibbonBeanPostProcessor( + BeanFactory beanFactory) { return new StubRunnerRibbonBeanPostProcessor(beanFactory); } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ribbon/StubRunnerRibbonServerList.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ribbon/StubRunnerRibbonServerList.java index 541d52793d..42e5622d30 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ribbon/StubRunnerRibbonServerList.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/ribbon/StubRunnerRibbonServerList.java @@ -36,12 +36,12 @@ import org.springframework.util.StringUtils; * Stub Runner representation of a server list * * @author Marcin Grzejszczak - * * @since 1.0.0 */ class StubRunnerRibbonServerList implements ServerList { - private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); + private static final Log log = LogFactory + .getLog(MethodHandles.lookup().lookupClass()); private final ServerList serverList; @@ -50,10 +50,12 @@ class StubRunnerRibbonServerList implements ServerList { final IClientConfig clientConfig) { String serviceName = clientConfig.getClientName(); String mappedServiceName = StringUtils - .hasText(stubMapperProperties.fromServiceIdToIvyNotation(serviceName)) ? - stubMapperProperties.fromServiceIdToIvyNotation(serviceName) : serviceName; + .hasText(stubMapperProperties.fromServiceIdToIvyNotation(serviceName)) + ? stubMapperProperties.fromServiceIdToIvyNotation(serviceName) + : serviceName; RunningStubs runningStubs = stubFinder.findAllRunningStubs(); - final Map.Entry entry = runningStubs.getEntry(mappedServiceName); + final Map.Entry entry = runningStubs + .getEntry(mappedServiceName); final List servers = new ArrayList<>(); if (entry != null) { servers.add(new Server("localhost", entry.getValue()) { @@ -62,7 +64,8 @@ class StubRunnerRibbonServerList implements ServerList { return new MetaInfo() { @Override public String getAppName() { - return stubMapperProperties.fromIvyNotationToId(entry.getKey().toColonSeparatedDependencyNotation()); + return stubMapperProperties.fromIvyNotationToId( + entry.getKey().toColonSeparatedDependencyNotation()); } @Override @@ -72,12 +75,14 @@ class StubRunnerRibbonServerList implements ServerList { @Override public String getServiceIdForDiscovery() { - return stubMapperProperties.fromIvyNotationToId(entry.getKey().getArtifactId()); + return stubMapperProperties + .fromIvyNotationToId(entry.getKey().getArtifactId()); } @Override public String getInstanceId() { - return stubMapperProperties.fromIvyNotationToId(entry.getKey().getArtifactId()); + return stubMapperProperties + .fromIvyNotationToId(entry.getKey().getArtifactId()); } }; } @@ -105,4 +110,5 @@ class StubRunnerRibbonServerList implements ServerList { public List getUpdatedListOfServers() { return this.serverList.getUpdatedListOfServers(); } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/zookeeper/StubRunnerSpringCloudZookeeperAutoConfiguration.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/zookeeper/StubRunnerSpringCloudZookeeperAutoConfiguration.java index 43ac937621..97a66c7124 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/zookeeper/StubRunnerSpringCloudZookeeperAutoConfiguration.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/zookeeper/StubRunnerSpringCloudZookeeperAutoConfiguration.java @@ -35,11 +35,11 @@ import org.springframework.context.annotation.Configuration; * Autoconfiguration for registering stubs in a Zookeeper Service discovery * * @author Marcin Grzejszczak - * * @since 1.0.0 */ @Configuration -@AutoConfigureAfter({ StubRunnerConfiguration.class, CuratorServiceDiscoveryAutoConfiguration.class }) +@AutoConfigureAfter({ StubRunnerConfiguration.class, + CuratorServiceDiscoveryAutoConfiguration.class }) @ConditionalOnClass(org.apache.curator.x.discovery.ServiceInstance.class) @ConditionalOnStubbedDiscoveryDisabled @ConditionalOnZookeeperDiscoveryEnabled @@ -47,8 +47,11 @@ import org.springframework.context.annotation.Configuration; public class StubRunnerSpringCloudZookeeperAutoConfiguration { @Bean(initMethod = "registerStubs") - public StubsRegistrar stubsRegistrar(StubRunning stubRunning, CuratorFramework curatorFramework, - StubMapperProperties stubMapperProperties, ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) { - return new ZookeeperStubsRegistrar(stubRunning, curatorFramework, stubMapperProperties, zookeeperDiscoveryProperties); + public StubsRegistrar stubsRegistrar(StubRunning stubRunning, + CuratorFramework curatorFramework, StubMapperProperties stubMapperProperties, + ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) { + return new ZookeeperStubsRegistrar(stubRunning, curatorFramework, + stubMapperProperties, zookeeperDiscoveryProperties); } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/zookeeper/ZookeeperStubsRegistrar.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/zookeeper/ZookeeperStubsRegistrar.java index 2473211582..5de594771b 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/zookeeper/ZookeeperStubsRegistrar.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/spring/cloud/zookeeper/ZookeeperStubsRegistrar.java @@ -23,21 +23,25 @@ import org.springframework.util.StringUtils; * Registers all stubs in Zookeeper Service Discovery * * @author Marcin Grzejszczak - * * @since 1.0.0 */ public class ZookeeperStubsRegistrar implements StubsRegistrar { - private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); + private static final Log log = LogFactory + .getLog(MethodHandles.lookup().lookupClass()); private final StubRunning stubRunning; + private final CuratorFramework curatorFramework; + private final StubMapperProperties stubMapperProperties; + private final ZookeeperDiscoveryProperties zookeeperDiscoveryProperties; + private final List discoveryList = new LinkedList<>(); - public ZookeeperStubsRegistrar(StubRunning stubRunning, CuratorFramework curatorFramework, - StubMapperProperties stubMapperProperties, + public ZookeeperStubsRegistrar(StubRunning stubRunning, + CuratorFramework curatorFramework, StubMapperProperties stubMapperProperties, ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) { this.stubRunning = stubRunning; this.curatorFramework = curatorFramework; @@ -45,30 +49,36 @@ public class ZookeeperStubsRegistrar implements StubsRegistrar { this.zookeeperDiscoveryProperties = zookeeperDiscoveryProperties; } - @Override public void registerStubs() { + @Override + public void registerStubs() { Map activeStubs = this.stubRunning.runStubs() .validNamesAndPorts(); for (Map.Entry entry : activeStubs.entrySet()) { - ServiceInstance serviceInstance = serviceInstance(entry.getKey(), entry.getValue()); + ServiceInstance serviceInstance = serviceInstance(entry.getKey(), + entry.getValue()); ServiceDiscovery serviceDiscovery = serviceDiscovery(serviceInstance); this.discoveryList.add(serviceDiscovery); try { serviceDiscovery.start(); if (log.isDebugEnabled()) { - log.debug("Successfully registered stub [" + entry.getKey().toColonSeparatedDependencyNotation() + log.debug("Successfully registered stub [" + + entry.getKey().toColonSeparatedDependencyNotation() + "] in Service Discovery"); } } catch (Exception e) { - log.warn("Exception occurred while trying to register a stub [" + entry.getKey().toColonSeparatedDependencyNotation() + log.warn("Exception occurred while trying to register a stub [" + + entry.getKey().toColonSeparatedDependencyNotation() + "] in Service Discovery", e); } } } - protected ServiceInstance serviceInstance(StubConfiguration stubConfiguration, int port) { + protected ServiceInstance serviceInstance(StubConfiguration stubConfiguration, + int port) { try { - return ServiceInstance.builder().uriSpec(new UriSpec(this.zookeeperDiscoveryProperties.getUriSpec())) + return ServiceInstance.builder() + .uriSpec(new UriSpec(this.zookeeperDiscoveryProperties.getUriSpec())) .address("localhost").port(port).name(name(stubConfiguration)) .build(); } @@ -98,4 +108,5 @@ public class ZookeeperStubsRegistrar implements StubsRegistrar { discovery.close(); } } + } diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/util/StubsParser.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/util/StubsParser.java index 612081164d..c7f3899297 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/util/StubsParser.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/util/StubsParser.java @@ -31,8 +31,8 @@ import org.springframework.util.StringUtils; public class StubsParser { /** - * The string is expected to be a map with entry called "stubs" - * that contains a list of Strings in the format + * The string is expected to be a map with entry called "stubs" that contains a list + * of Strings in the format * *
      *
    • groupid:artifactid:version:classifier:port
    • @@ -47,7 +47,8 @@ public class StubsParser { * * "a:b,c:d:e" */ - public static List fromString(Collection collection, String defaultClassifier) { + public static List fromString(Collection collection, + String defaultClassifier) { List stubs = new ArrayList<>(); for (String config : collection) { if (StringUtils.hasText(config)) { @@ -58,7 +59,8 @@ public class StubsParser { } public static Map fromStringWithPort(String notation) { - StubSpecification stub = StubSpecification.parse(notation, StubConfiguration.DEFAULT_CLASSIFIER); + StubSpecification stub = StubSpecification.parse(notation, + StubConfiguration.DEFAULT_CLASSIFIER); if (!stub.hasPort()) { return Collections.emptyMap(); } @@ -66,7 +68,8 @@ public class StubsParser { } public static String ivyFromStringWithPort(String notation) { - StubSpecification stub = StubSpecification.parse(notation, StubConfiguration.DEFAULT_CLASSIFIER); + StubSpecification stub = StubSpecification.parse(notation, + StubConfiguration.DEFAULT_CLASSIFIER); if (!stub.hasPort()) { return ""; } @@ -76,16 +79,18 @@ public class StubsParser { public static boolean hasPort(String id) { String[] splitEntry = id.split(":"); try { - Integer.valueOf(splitEntry[splitEntry.length-1]); + Integer.valueOf(splitEntry[splitEntry.length - 1]); return true; - } catch (NumberFormatException e) { + } + catch (NumberFormatException e) { return false; } } - + private static class StubSpecification { private final StubConfiguration stub; + private final Integer port; public StubSpecification(StubConfiguration stub, Integer port) { @@ -96,16 +101,20 @@ public class StubsParser { public boolean hasPort() { return this.port != null; } - + private static StubSpecification parse(String id, String defaultClassifier) { String[] splitEntry = id.split(":"); Integer port = null; try { - port = Integer.valueOf(splitEntry[splitEntry.length-1]); + port = Integer.valueOf(splitEntry[splitEntry.length - 1]); id = id.substring(0, id.lastIndexOf(":")); - } catch (NumberFormatException e) {} - return new StubSpecification(new StubConfiguration(id, defaultClassifier), port); + } + catch (NumberFormatException e) { + } + return new StubSpecification(new StubConfiguration(id, defaultClassifier), + port); } } + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/util/ZipCategory.java b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/util/ZipCategory.java index 03af8e75dc..ba738c7f0d 100644 --- a/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/util/ZipCategory.java +++ b/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/util/ZipCategory.java @@ -43,7 +43,6 @@ public class ZipCategory { /** * Unzips this file. If the destination directory is not provided, it will * fall back to this file's parent directory. - * * @param self * @param destination (optional), the destination directory where this file's content * will be unzipped to. @@ -58,8 +57,8 @@ public class ZipCategory { List unzippedFiles = new ArrayList<>(); try (InputStream fileInputStream = Files.newInputStream(self.toPath())) { try (ZipInputStream zipInput = new ZipInputStream(fileInputStream)) { - for (ZipEntry entry = zipInput.getNextEntry(); entry != null; entry = zipInput - .getNextEntry()) { + for (ZipEntry entry = zipInput + .getNextEntry(); entry != null; entry = zipInput.getNextEntry()) { if (!entry.isDirectory()) { final File file = new File(destination, entry.getName()); if (file.getParentFile() != null) { @@ -77,7 +76,8 @@ public class ZipCategory { } } } - } catch (IOException e) { + } + catch (IOException e) { throw new IllegalStateException("Cannot unzip archive", e); } return unzippedFiles; @@ -87,4 +87,5 @@ public class ZipCategory { if (file != null && !file.isDirectory()) throw new IllegalArgumentException("'destination' has to be a directory."); } + } diff --git a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/AbstractGitTest.java b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/AbstractGitTest.java index 637a182ad2..ec144f6a28 100644 --- a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/AbstractGitTest.java +++ b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/AbstractGitTest.java @@ -39,7 +39,9 @@ import org.junit.rules.TemporaryFolder; */ public abstract class AbstractGitTest { - @Rule public TemporaryFolder tmp = new TemporaryFolder(); + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + File tmpFolder; @Before @@ -53,7 +55,7 @@ public abstract class AbstractGitTest { try (PrintStream out = new PrintStream(new FileOutputStream(newFile))) { out.print("foo"); } - try(Git git = openGitProject(project)) { + try (Git git = openGitProject(project)) { git.add().addFilepattern("newFile").call(); } return newFile; @@ -61,7 +63,7 @@ public abstract class AbstractGitTest { void setOriginOnProjectToTmp(File origin, File project, boolean push) throws GitAPIException, IOException, URISyntaxException { - try(Git git = openGitProject(project)) { + try (Git git = openGitProject(project)) { RemoteRemoveCommand remove = git.remoteRemove(); remove.setName("origin"); remove.call(); @@ -72,7 +74,8 @@ public abstract class AbstractGitTest { command.call(); StoredConfig config = git.getRepository().getConfig(); RemoteConfig originConfig = new RemoteConfig(config, "origin"); - originConfig.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*")); + originConfig + .addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*")); originConfig.update(config); config.save(); } @@ -87,4 +90,5 @@ public abstract class AbstractGitTest { projectRepo.cloneProject(projectToClone.toURI()); return baseDir; } + } diff --git a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/ClasspathStubProviderTest.java b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/ClasspathStubProviderTest.java index c53c69858e..8c318b3524 100644 --- a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/ClasspathStubProviderTest.java +++ b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/ClasspathStubProviderTest.java @@ -10,10 +10,13 @@ import static org.assertj.core.api.BDDAssertions.then; */ public class ClasspathStubProviderTest { - @Test public void should_return_null_if_stub_mode_is_not_classpath() { - StubDownloader stubDownloader = new ClasspathStubProvider().build(new StubRunnerOptionsBuilder().withStubsMode( - StubRunnerProperties.StubsMode.REMOTE).build()); + @Test + public void should_return_null_if_stub_mode_is_not_classpath() { + StubDownloader stubDownloader = new ClasspathStubProvider() + .build(new StubRunnerOptionsBuilder() + .withStubsMode(StubRunnerProperties.StubsMode.REMOTE).build()); then(stubDownloader).isNull(); } + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/CompositeStubDownloaderBuilderTests.java b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/CompositeStubDownloaderBuilderTests.java index 0ac08cfa1c..244afd435b 100644 --- a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/CompositeStubDownloaderBuilderTests.java +++ b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/CompositeStubDownloaderBuilderTests.java @@ -14,11 +14,14 @@ import org.junit.Test; */ public class CompositeStubDownloaderBuilderTests { - @Test public void should_delegate_work_to_other_stub_downloaders() { + @Test + public void should_delegate_work_to_other_stub_downloaders() { EmptyStubDownloaderBuilder emptyStubDownloaderBuilder = new EmptyStubDownloaderBuilder(); ImpossibleToBuildStubDownloaderBuilder impossible = new ImpossibleToBuildStubDownloaderBuilder(); - List builders = Arrays.asList(emptyStubDownloaderBuilder, impossible, new SomeStubDownloaderBuilder()); - CompositeStubDownloaderBuilder builder = new CompositeStubDownloaderBuilder(builders); + List builders = Arrays.asList(emptyStubDownloaderBuilder, + impossible, new SomeStubDownloaderBuilder()); + CompositeStubDownloaderBuilder builder = new CompositeStubDownloaderBuilder( + builders); StubDownloader downloader = builder.build(new StubRunnerOptionsBuilder().build()); Map.Entry entry = downloader @@ -29,20 +32,23 @@ public class CompositeStubDownloaderBuilderTests { BDDAssertions.then(impossible.called).isTrue(); } - @Test public void should_return_null_if_no_builders_were_passed() { + @Test + public void should_return_null_if_no_builders_were_passed() { CompositeStubDownloaderBuilder builder = new CompositeStubDownloaderBuilder(null); StubDownloader downloader = builder.build(new StubRunnerOptionsBuilder().build()); BDDAssertions.then(downloader).isNull(); } + } class EmptyStubDownloaderBuilder implements StubDownloaderBuilder { EmptyStubDownloader emptyStubDownloader; - @Override public StubDownloader build(StubRunnerOptions stubRunnerOptions) { + @Override + public StubDownloader build(StubRunnerOptions stubRunnerOptions) { this.emptyStubDownloader = new EmptyStubDownloader(); return this.emptyStubDownloader; } @@ -50,13 +56,15 @@ class EmptyStubDownloaderBuilder implements StubDownloaderBuilder { boolean downloaderCalled() { return this.emptyStubDownloader.called; } + } class ImpossibleToBuildStubDownloaderBuilder implements StubDownloaderBuilder { boolean called; - @Override public StubDownloader build(StubRunnerOptions stubRunnerOptions) { + @Override + public StubDownloader build(StubRunnerOptions stubRunnerOptions) { this.called = true; return null; } @@ -64,25 +72,33 @@ class ImpossibleToBuildStubDownloaderBuilder implements StubDownloaderBuilder { } class EmptyStubDownloader implements StubDownloader { + boolean called; - @Override public Map.Entry downloadAndUnpackStubJar( + @Override + public Map.Entry downloadAndUnpackStubJar( StubConfiguration stubConfiguration) { this.called = true; return null; } + } class SomeStubDownloaderBuilder implements StubDownloaderBuilder { - @Override public StubDownloader build(StubRunnerOptions stubRunnerOptions) { + @Override + public StubDownloader build(StubRunnerOptions stubRunnerOptions) { return new SomeStubDownloader(); } + } class SomeStubDownloader implements StubDownloader { - @Override public Map.Entry downloadAndUnpackStubJar( + + @Override + public Map.Entry downloadAndUnpackStubJar( StubConfiguration stubConfiguration) { return new AbstractMap.SimpleEntry<>(stubConfiguration, new File(".")); } + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/ContractProjectUpdaterTest.java b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/ContractProjectUpdaterTest.java index 2392696061..83537fed4b 100644 --- a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/ContractProjectUpdaterTest.java +++ b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/ContractProjectUpdaterTest.java @@ -36,18 +36,25 @@ import static org.assertj.core.api.BDDAssertions.then; * @author Marcin Grzejszczak */ public class ContractProjectUpdaterTest extends AbstractGitTest { + File originalProject; + File project; + ContractProjectUpdater updater; + GitRepo gitRepo; + File origin; - @Rule public OutputCapture outputCapture = new OutputCapture(); + @Rule + public OutputCapture outputCapture = new OutputCapture(); @Before public void setup() throws Exception { GitContractsRepo.CACHED_LOCATIONS.clear(); - this.originalProject = new File(GitRepoTests.class.getResource("/git_samples/contract-git").toURI()); + this.originalProject = new File( + GitRepoTests.class.getResource("/git_samples/contract-git").toURI()); TestUtils.prepareLocalRepo(); this.gitRepo = new GitRepo(this.tmpFolder); this.origin = clonedProject(this.tmp.newFolder(), this.originalProject); @@ -56,31 +63,36 @@ public class ContractProjectUpdaterTest extends AbstractGitTest { setOriginOnProjectToTmp(this.origin, this.project, true); StubRunnerOptions options = new StubRunnerOptionsBuilder() .withStubRepositoryRoot("file://" + this.project.getAbsolutePath() + "/") - .withStubsMode(StubRunnerProperties.StubsMode.REMOTE) - .build(); + .withStubsMode(StubRunnerProperties.StubsMode.REMOTE).build(); this.updater = new ContractProjectUpdater(options); } @Test public void should_push_changes_to_current_branch() throws Exception { - File stubs = new File(GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI()); + File stubs = new File( + GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI()); this.updater.updateContractProject("hello-world", stubs.toPath()); // project, not origin, cause we're making one more clone of the local copy - try(Git git = openGitProject(this.project)) { + try (Git git = openGitProject(this.project)) { RevCommit revCommit = git.log().call().iterator().next(); - then(revCommit.getShortMessage()).isEqualTo("Updating project [hello-world] with stubs"); + then(revCommit.getShortMessage()) + .isEqualTo("Updating project [hello-world] with stubs"); // I have no idea but the file gets deleted after pushing git.reset().setMode(ResetCommand.ResetType.HARD).call(); } - BDDAssertions.then(new File(this.project, "META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json")).exists(); + BDDAssertions.then(new File(this.project, + "META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json")) + .exists(); BDDAssertions.then(gitRepo.gitFactory.provider).isNull(); - BDDAssertions.then(outputCapture.toString()).contains("No custom credentials provider will be set"); + BDDAssertions.then(outputCapture.toString()) + .contains("No custom credentials provider will be set"); } @Test - public void should_push_changes_to_current_branch_using_credentials() throws Exception { + public void should_push_changes_to_current_branch_using_credentials() + throws Exception { StubRunnerOptions options = new StubRunnerOptionsBuilder() .withStubRepositoryRoot("file://" + this.project.getAbsolutePath() + "/") .withStubsMode(StubRunnerProperties.StubsMode.REMOTE) @@ -89,56 +101,68 @@ public class ContractProjectUpdaterTest extends AbstractGitTest { put("git.username", "foo"); put("git.password", "bar"); } - } ) - .build(); + }).build(); ContractProjectUpdater updater = new ContractProjectUpdater(options); - File stubs = new File(GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI()); + File stubs = new File( + GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI()); updater.updateContractProject("hello-world", stubs.toPath()); // project, not origin, cause we're making one more clone of the local copy - try(Git git = openGitProject(this.project)) { + try (Git git = openGitProject(this.project)) { RevCommit revCommit = git.log().call().iterator().next(); - then(revCommit.getShortMessage()).isEqualTo("Updating project [hello-world] with stubs"); + then(revCommit.getShortMessage()) + .isEqualTo("Updating project [hello-world] with stubs"); // I have no idea but the file gets deleted after pushing git.reset().setMode(ResetCommand.ResetType.HARD).call(); } - BDDAssertions.then(new File(this.project, "META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json")).exists(); - BDDAssertions.then(outputCapture.toString()).contains("Passed username and password - will set a custom credentials provider"); + BDDAssertions.then(new File(this.project, + "META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json")) + .exists(); + BDDAssertions.then(outputCapture.toString()).contains( + "Passed username and password - will set a custom credentials provider"); } @Test - public void should_push_changes_to_current_branch_using_root_credentials() throws Exception { + public void should_push_changes_to_current_branch_using_root_credentials() + throws Exception { StubRunnerOptions options = new StubRunnerOptionsBuilder() .withStubRepositoryRoot("file://" + this.project.getAbsolutePath() + "/") - .withStubsMode(StubRunnerProperties.StubsMode.REMOTE) - .withUsername("foo") - .withPassword("bar") - .build(); + .withStubsMode(StubRunnerProperties.StubsMode.REMOTE).withUsername("foo") + .withPassword("bar").build(); ContractProjectUpdater updater = new ContractProjectUpdater(options); - File stubs = new File(GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI()); + File stubs = new File( + GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI()); updater.updateContractProject("hello-world", stubs.toPath()); // project, not origin, cause we're making one more clone of the local copy - try(Git git = openGitProject(this.project)) { + try (Git git = openGitProject(this.project)) { RevCommit revCommit = git.log().call().iterator().next(); - then(revCommit.getShortMessage()).isEqualTo("Updating project [hello-world] with stubs"); + then(revCommit.getShortMessage()) + .isEqualTo("Updating project [hello-world] with stubs"); // I have no idea but the file gets deleted after pushing git.reset().setMode(ResetCommand.ResetType.HARD).call(); } - BDDAssertions.then(new File(this.project, "META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json")).exists(); - BDDAssertions.then(outputCapture.toString()).contains("Passed username and password - will set a custom credentials provider"); + BDDAssertions.then(new File(this.project, + "META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json")) + .exists(); + BDDAssertions.then(outputCapture.toString()).contains( + "Passed username and password - will set a custom credentials provider"); } @Test - public void should_not_push_changes_to_current_branch_when_no_changes_were_made() throws Exception { + public void should_not_push_changes_to_current_branch_when_no_changes_were_made() + throws Exception { this.updater.updateContractProject("hello-world", this.origin.toPath()); - try(Git git = openGitProject(this.project)) { + try (Git git = openGitProject(this.project)) { RevCommit revCommit = git.log().call().iterator().next(); then(revCommit.getShortMessage()).isEqualTo("Initial commit"); } - BDDAssertions.then(new File(this.project, "META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json")).doesNotExist(); + BDDAssertions.then(new File(this.project, + "META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json")) + .doesNotExist(); } + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/GitRepoTests.java b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/GitRepoTests.java index 4896422425..1606ace92c 100644 --- a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/GitRepoTests.java +++ b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/GitRepoTests.java @@ -31,17 +31,19 @@ import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.api.BDDAssertions.thenThrownBy; /** - * @author Marcin Grzejszczak - * taken from: https://github.com/spring-cloud/spring-cloud-release-tools + * @author Marcin Grzejszczak taken from: + * https://github.com/spring-cloud/spring-cloud-release-tools */ public class GitRepoTests extends AbstractGitTest { File project; + GitRepo gitRepo; @Before public void setup() throws IOException, URISyntaxException { - this.project = new File(GitRepoTests.class.getResource("/git_samples/contract-git").toURI()); + this.project = new File( + GitRepoTests.class.getResource("/git_samples/contract-git").toURI()); TestUtils.prepareLocalRepo(); this.gitRepo = new GitRepo(this.tmpFolder); } @@ -54,19 +56,22 @@ public class GitRepoTests extends AbstractGitTest { } @Test - public void should_throw_exception_when_there_is_no_repo() throws IOException, URISyntaxException { + public void should_throw_exception_when_there_is_no_repo() + throws IOException, URISyntaxException { thenThrownBy(() -> this.gitRepo .cloneProject(GitRepoTests.class.getResource("/git_samples/").toURI())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Exception occurred while cloning repo"); + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exception occurred while cloning repo"); } @Test - public void should_throw_an_exception_when_failed_to_initialize_the_repo() throws IOException { - thenThrownBy(() -> new GitRepo(this.tmpFolder, new ExceptionThrowingJGitFactory()).cloneProject(this.project.toURI())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Exception occurred while cloning repo") - .hasCauseInstanceOf(CustomException.class); + public void should_throw_an_exception_when_failed_to_initialize_the_repo() + throws IOException { + thenThrownBy(() -> new GitRepo(this.tmpFolder, new ExceptionThrowingJGitFactory()) + .cloneProject(this.project.toURI())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exception occurred while cloning repo") + .hasCauseInstanceOf(CustomException.class); } @Test @@ -79,12 +84,14 @@ public class GitRepoTests extends AbstractGitTest { } @Test - public void should_throw_an_exception_when_checking_out_nonexisting_branch() throws IOException { + public void should_throw_an_exception_when_checking_out_nonexisting_branch() + throws IOException { File project = this.gitRepo.cloneProject(this.project.toURI()); try { this.gitRepo.checkout(project, "nonExistingBranch"); fail("should throw an exception"); - } catch (IllegalStateException e) { + } + catch (IllegalStateException e) { then(e).hasMessageContaining("Ref nonExistingBranch can not be resolved"); } } @@ -96,7 +103,7 @@ public class GitRepoTests extends AbstractGitTest { this.gitRepo.commit(project, "some message"); - try(Git git = openGitProject(project)) { + try (Git git = openGitProject(project)) { RevCommit revCommit = git.log().call().iterator().next(); then(revCommit.getShortMessage()).isEqualTo("some message"); } @@ -120,7 +127,7 @@ public class GitRepoTests extends AbstractGitTest { this.gitRepo.commit(project, "empty commit"); - try(Git git = openGitProject(project)) { + try (Git git = openGitProject(project)) { RevCommit revCommit = git.log().call().iterator().next(); then(revCommit.getShortMessage()).isNotEqualTo("empty commit"); } @@ -136,7 +143,7 @@ public class GitRepoTests extends AbstractGitTest { this.gitRepo.pushCurrentBranch(project); - try(Git git = openGitProject(origin)) { + try (Git git = openGitProject(origin)) { RevCommit revCommit = git.log().call().iterator().next(); then(revCommit.getShortMessage()).isEqualTo("some message"); } @@ -152,21 +159,27 @@ public class GitRepoTests extends AbstractGitTest { this.gitRepo.pull(project); - try(Git git = openGitProject(project)) { + try (Git git = openGitProject(project)) { RevCommit revCommit = git.log().call().iterator().next(); then(revCommit.getShortMessage()).isEqualTo("some message"); } } + } class ExceptionThrowingJGitFactory extends GitRepo.JGitFactory { - @Override CloneCommand getCloneCommandByCloneRepository() { + + @Override + CloneCommand getCloneCommandByCloneRepository() { throw new CustomException("foo"); } + } class CustomException extends RuntimeException { + public CustomException(String message) { super(message); } + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/GitStubDownloaderTests.java b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/GitStubDownloaderTests.java index 80b1e1033b..277480af1b 100644 --- a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/GitStubDownloaderTests.java +++ b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/GitStubDownloaderTests.java @@ -31,7 +31,9 @@ import static org.assertj.core.api.BDDAssertions.then; public class GitStubDownloaderTests { - @Rule public TemporaryFolder tmp = new TemporaryFolder(); + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + File temporaryFolder; @Before @@ -45,10 +47,10 @@ public class GitStubDownloaderTests { public void should_return_a_null_downloader_for_a_classptath_mode() { StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder(); - StubDownloader stubDownloader = stubDownloaderBuilder.build(new StubRunnerOptionsBuilder() - .withStubsMode(StubRunnerProperties.StubsMode.CLASSPATH) - .withProperties(props()) - .build()); + StubDownloader stubDownloader = stubDownloaderBuilder + .build(new StubRunnerOptionsBuilder() + .withStubsMode(StubRunnerProperties.StubsMode.CLASSPATH) + .withProperties(props()).build()); then(stubDownloader).isNull(); } @@ -57,10 +59,10 @@ public class GitStubDownloaderTests { public void should_return_a_null_downloader_for_a_empty_repo() { StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder(); - StubDownloader stubDownloader = stubDownloaderBuilder.build(new StubRunnerOptionsBuilder() - .withStubsMode(StubRunnerProperties.StubsMode.REMOTE) - .withProperties(props()) - .build()); + StubDownloader stubDownloader = stubDownloaderBuilder + .build(new StubRunnerOptionsBuilder() + .withStubsMode(StubRunnerProperties.StubsMode.REMOTE) + .withProperties(props()).build()); then(stubDownloader).isNull(); } @@ -69,46 +71,54 @@ public class GitStubDownloaderTests { public void should_return_a_null_downloader_for_a_non_git_repo() { StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder(); - StubDownloader stubDownloader = stubDownloaderBuilder.build(new StubRunnerOptionsBuilder() - .withStubsMode(StubRunnerProperties.StubsMode.REMOTE) - .withStubRepositoryRoot("http://foo.com") - .withProperties(props()) - .build()); + StubDownloader stubDownloader = stubDownloaderBuilder + .build(new StubRunnerOptionsBuilder() + .withStubsMode(StubRunnerProperties.StubsMode.REMOTE) + .withStubRepositoryRoot("http://foo.com").withProperties(props()) + .build()); then(stubDownloader).isNull(); } @Test - public void should_pick_stubs_for_group_and_artifact_with_version_from_a_git_repo() throws Exception { + public void should_pick_stubs_for_group_and_artifact_with_version_from_a_git_repo() + throws Exception { StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder(); - StubDownloader stubDownloader = stubDownloaderBuilder.build(new StubRunnerOptionsBuilder() - .withStubsMode(StubRunnerProperties.StubsMode.REMOTE) - .withStubRepositoryRoot("git://" + file("/git_samples/contract-git/").getAbsolutePath() + "/") - .withProperties(props()) - .build()); + StubDownloader stubDownloader = stubDownloaderBuilder + .build(new StubRunnerOptionsBuilder() + .withStubsMode(StubRunnerProperties.StubsMode.REMOTE) + .withStubRepositoryRoot("git://" + + file("/git_samples/contract-git/").getAbsolutePath() + + "/") + .withProperties(props()).build()); Map.Entry entry = stubDownloader - .downloadAndUnpackStubJar(new StubConfiguration("foo.bar:bazService:0.0.1-SNAPSHOT")); + .downloadAndUnpackStubJar( + new StubConfiguration("foo.bar:bazService:0.0.1-SNAPSHOT")); then(entry).isNotNull(); - then(entry.getValue().getAbsolutePath()).contains("foo.bar" + File.separator + "bazService" + File.separator + "0.0.1-SNAPSHOT"); + then(entry.getValue().getAbsolutePath()).contains("foo.bar" + File.separator + + "bazService" + File.separator + "0.0.1-SNAPSHOT"); } @Test public void should_fail_to_fetch_stubs_when_latest_version_was_specified() throws URISyntaxException { StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder(); - StubDownloader stubDownloader = stubDownloaderBuilder.build(new StubRunnerOptionsBuilder() - .withStubsMode(StubRunnerProperties.StubsMode.REMOTE) - .withStubRepositoryRoot("git://" + file("/git_samples/contract-git").getAbsolutePath()) - .withProperties(props()) - .build()); + StubDownloader stubDownloader = stubDownloaderBuilder + .build(new StubRunnerOptionsBuilder() + .withStubsMode(StubRunnerProperties.StubsMode.REMOTE) + .withStubRepositoryRoot("git://" + + file("/git_samples/contract-git").getAbsolutePath()) + .withProperties(props()).build()); try { - stubDownloader - .downloadAndUnpackStubJar(new StubConfiguration("foo.bar:bazService:+")); - } catch (IllegalStateException e) { - then(e).hasMessageContaining("Concrete version wasn't passed for [foo.bar:bazService:+:stubs]"); + stubDownloader.downloadAndUnpackStubJar( + new StubConfiguration("foo.bar:bazService:+")); + } + catch (IllegalStateException e) { + then(e).hasMessageContaining( + "Concrete version wasn't passed for [foo.bar:bazService:+:stubs]"); } } @@ -116,17 +126,20 @@ public class GitStubDownloaderTests { public void should_fail_to_fetch_stubs_when_concrete_version_was_not_specified() throws URISyntaxException { StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder(); - StubDownloader stubDownloader = stubDownloaderBuilder.build(new StubRunnerOptionsBuilder() - .withStubsMode(StubRunnerProperties.StubsMode.REMOTE) - .withStubRepositoryRoot("git://" + file("/git_samples/contract-git").getAbsolutePath()) - .withProperties(props()) - .build()); + StubDownloader stubDownloader = stubDownloaderBuilder + .build(new StubRunnerOptionsBuilder() + .withStubsMode(StubRunnerProperties.StubsMode.REMOTE) + .withStubRepositoryRoot("git://" + + file("/git_samples/contract-git").getAbsolutePath()) + .withProperties(props()).build()); try { - stubDownloader - .downloadAndUnpackStubJar(new StubConfiguration("foo.bar", "bazService", "")); - } catch (IllegalStateException e) { - then(e).hasMessageContaining("Concrete version wasn't passed for [foo.bar:bazService::stubs]"); + stubDownloader.downloadAndUnpackStubJar( + new StubConfiguration("foo.bar", "bazService", "")); + } + catch (IllegalStateException e) { + then(e).hasMessageContaining( + "Concrete version wasn't passed for [foo.bar:bazService::stubs]"); } } @@ -139,4 +152,5 @@ public class GitStubDownloaderTests { private File file(String relativePath) throws URISyntaxException { return new File(GitStubDownloaderTests.class.getResource(relativePath).toURI()); } + } diff --git a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/StubDownloaderBuilderProviderTests.java b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/StubDownloaderBuilderProviderTests.java index 13bad35dec..4e31b1e47c 100644 --- a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/StubDownloaderBuilderProviderTests.java +++ b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/StubDownloaderBuilderProviderTests.java @@ -15,13 +15,21 @@ import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class StubDownloaderBuilderProviderTests { - @Mock StubDownloaderBuilder one; - @Mock StubDownloaderBuilder two; - @Mock StubDownloaderBuilder three; + @Mock + StubDownloaderBuilder one; - @Test public void should_get_providers_from_factories_default_and_additional_ones() { - StubDownloaderBuilderProvider provider = new StubDownloaderBuilderProvider(Collections.singletonList(one)) { - @Override List defaultStubDownloaderBuilders() { + @Mock + StubDownloaderBuilder two; + + @Mock + StubDownloaderBuilder three; + + @Test + public void should_get_providers_from_factories_default_and_additional_ones() { + StubDownloaderBuilderProvider provider = new StubDownloaderBuilderProvider( + Collections.singletonList(one)) { + @Override + List defaultStubDownloaderBuilders() { return Collections.singletonList(two); } }; @@ -34,4 +42,5 @@ public class StubDownloaderBuilderProviderTests { BDDMockito.then(two).should().build(options); BDDMockito.then(three).should().build(options); } + } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/StubRepositoryTest.java b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/StubRepositoryTest.java index a17916b10c..f590702bed 100644 --- a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/StubRepositoryTest.java +++ b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/StubRepositoryTest.java @@ -13,18 +13,22 @@ import static org.junit.Assert.assertEquals; * @author Sven Bayer */ public class StubRepositoryTest { - private static final File YAML_REPOSITORY_LOCATION = new File("src/test/resources/customYamlRepository"); - @Test - public void should_prefer_custom_yaml_converter_over_standard() { - //given: - StubRepository repository = new StubRepository(YAML_REPOSITORY_LOCATION, new ArrayList<>(), new StubRunnerOptionsBuilder().build()); - int expectedDescriptorsSize = 1; + private static final File YAML_REPOSITORY_LOCATION = new File( + "src/test/resources/customYamlRepository"); - //when: - Collection descriptors = repository.getContracts(); + @Test + public void should_prefer_custom_yaml_converter_over_standard() { + // given: + StubRepository repository = new StubRepository(YAML_REPOSITORY_LOCATION, + new ArrayList<>(), new StubRunnerOptionsBuilder().build()); + int expectedDescriptorsSize = 1; + + // when: + Collection descriptors = repository.getContracts(); + + // then: + assertEquals(expectedDescriptorsSize, descriptors.size()); + } - //then: - assertEquals(expectedDescriptorsSize, descriptors.size()); - } } diff --git a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/StubRunnerSliceTests.java b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/StubRunnerSliceTests.java index a250d83608..314972813d 100644 --- a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/StubRunnerSliceTests.java +++ b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/StubRunnerSliceTests.java @@ -32,20 +32,15 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Tests that stub runner specific auto-configuration can be loaded up in combination with * other slice tests - * + * * @author Biju Kunjummen */ @RunWith(SpringRunner.class) @WebMvcTest -@AutoConfigureStubRunner( - ids = { - "org.springframework.cloud.contract.verifier.stubs:loanIssuance:+:stubs", - "org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:+:stubs" - }, - minPort = 10001, - maxPort = 10020, - mappingsOutputFolder = "target/outputmappings/", - properties = {"hello=world", "foo=bar"}) +@AutoConfigureStubRunner(ids = { + "org.springframework.cloud.contract.verifier.stubs:loanIssuance:+:stubs", + "org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:+:stubs" }, minPort = 10001, maxPort = 10020, mappingsOutputFolder = "target/outputmappings/", properties = { + "hello=world", "foo=bar" }) @ActiveProfiles("test") public class StubRunnerSliceTests { @@ -84,13 +79,13 @@ public class StubRunnerSliceTests { assertThat(stubFinder.findStubUrl( "org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")) .isNotNull(); - assertThat(properties.getProperties()) - .containsEntry("hello", "world") + assertThat(properties.getProperties()).containsEntry("hello", "world") .containsEntry("foo", "bar"); } @SpringBootConfiguration static class Config { + } } diff --git a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/TestCustomYamlContractConverter.java b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/TestCustomYamlContractConverter.java index 65ce6e4f38..19d01a3da3 100644 --- a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/TestCustomYamlContractConverter.java +++ b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/TestCustomYamlContractConverter.java @@ -16,27 +16,29 @@ import java.util.Optional; */ public class TestCustomYamlContractConverter implements ContractConverter { - @Override - public boolean isAccepted(File file) { - if (!file.getName().endsWith(".yml") && !file.getName().endsWith(".yaml")) { - return false; - } - Optional line; - try { - line = Files.lines(file.toPath()).findFirst(); - } catch (IOException e) { - throw new IllegalStateException(e); - } - return line.isPresent() && line.get().startsWith("custom_format: 1.0"); - } + @Override + public boolean isAccepted(File file) { + if (!file.getName().endsWith(".yml") && !file.getName().endsWith(".yaml")) { + return false; + } + Optional line; + try { + line = Files.lines(file.toPath()).findFirst(); + } + catch (IOException e) { + throw new IllegalStateException(e); + } + return line.isPresent() && line.get().startsWith("custom_format: 1.0"); + } - @Override - public Collection convertFrom(File file) { - return Collections.singleton(Contract.make(Closure.IDENTITY)); - } + @Override + public Collection convertFrom(File file) { + return Collections.singleton(Contract.make(Closure.IDENTITY)); + } + + @Override + public Object convertTo(Collection contract) { + return new Object(); + } - @Override - public Object convertTo(Collection contract) { - return new Object(); - } } \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/TestUtils.java b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/TestUtils.java index 686769f991..c65c27f7ab 100644 --- a/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/TestUtils.java +++ b/spring-cloud-contract-stub-runner/src/test/java/org/springframework/cloud/contract/stubrunner/TestUtils.java @@ -27,7 +27,8 @@ class TestUtils { prepareLocalRepo("target/test-classes/git_samples/", "contract-git"); } - private static void prepareLocalRepo(String buildDir, String repoPath) throws IOException { + private static void prepareLocalRepo(String buildDir, String repoPath) + throws IOException { File dotGit = new File(buildDir + repoPath + "/.git"); File git = new File(buildDir + repoPath + "/git"); if (git.exists()) { diff --git a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/BaseClassMapping.java b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/BaseClassMapping.java index 8b477ba69c..47d51d8c91 100644 --- a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/BaseClassMapping.java +++ b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/BaseClassMapping.java @@ -1,8 +1,8 @@ package org.springframework.cloud.contract.maven.verifier; /** - * Represents a single mapping of regex on package where contracts reside - * to the FQN of the base test class + * Represents a single mapping of regex on package where contracts reside to the FQN of + * the base test class * * @author Marcin Grzejszczak * @since 1.0.0 @@ -29,30 +29,35 @@ public class BaseClassMapping { this.baseClassFQN = baseClassFQN; } - @Override public boolean equals(Object o) { + @Override + public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BaseClassMapping that = (BaseClassMapping) o; - if (this.contractPackageRegex != null ? - !this.contractPackageRegex.equals(that.contractPackageRegex) : - that.contractPackageRegex != null) + if (this.contractPackageRegex != null + ? !this.contractPackageRegex.equals(that.contractPackageRegex) + : that.contractPackageRegex != null) return false; - return this.baseClassFQN != null ? - this.baseClassFQN.equals(that.baseClassFQN) : - that.baseClassFQN == null; + return this.baseClassFQN != null ? this.baseClassFQN.equals(that.baseClassFQN) + : that.baseClassFQN == null; } - @Override public int hashCode() { - int result = this.contractPackageRegex != null ? this.contractPackageRegex.hashCode() : 0; - result = 31 * result + (this.baseClassFQN != null ? this.baseClassFQN.hashCode() : 0); + @Override + public int hashCode() { + int result = this.contractPackageRegex != null + ? this.contractPackageRegex.hashCode() : 0; + result = 31 * result + + (this.baseClassFQN != null ? this.baseClassFQN.hashCode() : 0); return result; } - @Override public String toString() { + @Override + public String toString() { return "BaseClassMapping{" + "contractPackageRegex='" + this.contractPackageRegex + '\'' + ", baseClassFQN='" + this.baseClassFQN + '\'' + '}'; } + } diff --git a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/ConvertMojo.java b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/ConvertMojo.java index 1328801a79..1c928dcd82 100644 --- a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/ConvertMojo.java +++ b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/ConvertMojo.java @@ -39,11 +39,11 @@ import org.springframework.cloud.contract.verifier.converter.RecursiveFilesConve /** * Convert Spring Cloud Contract Verifier contracts into WireMock stubs mappings. *

      - * This goal allows you to generate `stubs-jar` or execute `spring-cloud-contract:run` with generated WireMock mappings. + * This goal allows you to generate `stubs-jar` or execute `spring-cloud-contract:run` + * with generated WireMock mappings. */ -@Mojo(name = "convert", requiresProject = false, - defaultPhase = LifecyclePhase.PROCESS_TEST_RESOURCES) -public class ConvertMojo extends AbstractMojo { +@Mojo(name = "convert", requiresProject = false, defaultPhase = LifecyclePhase.PROCESS_TEST_RESOURCES) +public class ConvertMojo extends AbstractMojo { static final String DEFAULT_STUBS_DIR = "${project.build.directory}/stubs/"; static final String MAPPINGS_PATH = "/mappings"; @@ -52,15 +52,15 @@ public class ConvertMojo extends AbstractMojo { private RepositorySystemSession repoSession; /** - * Directory containing Spring Cloud Contract Verifier contracts written using the GroovyDSL + * Directory containing Spring Cloud Contract Verifier contracts written using the + * GroovyDSL */ - @Parameter(property = "spring.cloud.contract.verifier.contractsDirectory", - defaultValue = "${project.basedir}/src/test/resources/contracts") + @Parameter(property = "spring.cloud.contract.verifier.contractsDirectory", defaultValue = "${project.basedir}/src/test/resources/contracts") private File contractsDirectory; /** - * Directory where the generated WireMock stubs from Groovy DSL should be placed. - * You can then mention them in your packaging task to create jar with stubs + * Directory where the generated WireMock stubs from Groovy DSL should be placed. You + * can then mention them in your packaging task to create jar with stubs */ @Parameter(defaultValue = DEFAULT_STUBS_DIR) private File stubsDirectory; @@ -82,12 +82,13 @@ public class ConvertMojo extends AbstractMojo { @Parameter(defaultValue = "${session}", readonly = true) private MavenSession mavenSession; - @Parameter(defaultValue = "${project}", readonly = true) private MavenProject project; + @Parameter(defaultValue = "${project}", readonly = true) + private MavenProject project; /** - * The URL from which a JAR containing the contracts should get downloaded. If not provided - * but artifactid / coordinates notation was provided then the current Maven's build repositories will be - * taken into consideration + * The URL from which a JAR containing the contracts should get downloaded. If not + * provided but artifactid / coordinates notation was provided then the current + * Maven's build repositories will be taken into consideration */ @Parameter(property = "contractsRepositoryUrl") private String contractsRepositoryUrl; @@ -96,11 +97,12 @@ public class ConvertMojo extends AbstractMojo { private Dependency contractDependency; /** - * The path in the JAR with all the contracts where contracts for this particular service lay. - * If not provided will be resolved to {@code groupid/artifactid}. Example: + * The path in the JAR with all the contracts where contracts for this particular + * service lay. If not provided will be resolved to {@code groupid/artifactid}. + * Example: *

      - * If {@code groupid} is {@code com.example} and {@code artifactid} is {@code service} then the resolved path will be - * {@code /com/example/artifactid} + * If {@code groupid} is {@code com.example} and {@code artifactid} is {@code service} + * then the resolved path will be {@code /com/example/artifactid} */ @Parameter(property = "contractsPath") private String contractsPath; @@ -112,8 +114,8 @@ public class ConvertMojo extends AbstractMojo { private StubRunnerProperties.StubsMode contractsMode; /** - * If {@code true} then any file laying in a path that contains {@code build} or {@code target} - * will get excluded in further processing. + * If {@code true} then any file laying in a path that contains {@code build} or + * {@code target} will get excluded in further processing. */ @Parameter(property = "excludeBuildFolders", defaultValue = "false") private boolean excludeBuildFolders; @@ -143,25 +145,24 @@ public class ConvertMojo extends AbstractMojo { private Integer contractsRepositoryProxyPort; /** - * If {@code true} then will not assert whether a stub / contract - * JAR was downloaded from local or remote location - * + * If {@code true} then will not assert whether a stub / contract JAR was downloaded + * from local or remote location * @deprecated - with 2.1.0 this option is redundant */ @Parameter(property = "contractsSnapshotCheckSkip", defaultValue = "false") @Deprecated private boolean contractsSnapshotCheckSkip; - /** - * If set to {@code false} will NOT delete stubs from a temporary - * folder after running tests + * If set to {@code false} will NOT delete stubs from a temporary folder after running + * tests */ @Parameter(property = "deleteStubsAfterTest", defaultValue = "true") private boolean deleteStubsAfterTest; /** - * Map of properties that can be passed to custom {@link org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder} + * Map of properties that can be passed to custom + * {@link org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder} */ @Parameter(property = "contractsProperties") private Map contractsProperties = new HashMap<>(); @@ -191,10 +192,11 @@ public class ConvertMojo extends AbstractMojo { ContractVerifierConfigProperties config = new ContractVerifierConfigProperties(); config.setExcludeBuildFolders(this.excludeBuildFolders); File contractsDirectory = locationOfContracts(config); - getLog().info("Directory with contract is present at [" + contractsDirectory + "]"); + getLog().info( + "Directory with contract is present at [" + contractsDirectory + "]"); contractsDirectory = contractSubfolderIfPresent(contractsDirectory); - new CopyContracts(this.project, this.mavenSession, this.mavenResourcesFiltering, config) - .copy(contractsDirectory, this.stubsDirectory, rootPath); + new CopyContracts(this.project, this.mavenSession, this.mavenResourcesFiltering, + config).copy(contractsDirectory, this.stubsDirectory, rootPath); File contractsDslDir = contractsDslDir(contractsDirectory); config.setContractsDslDir(contractsDslDir); config.setStubsOutputDir(stubsOutputDir(rootPath)); @@ -230,20 +232,21 @@ public class ConvertMojo extends AbstractMojo { private File locationOfContracts(ContractVerifierConfigProperties config) { return new MavenContractsDownloader(this.project, this.contractDependency, - this.contractsPath, this.contractsRepositoryUrl, this.contractsMode, getLog(), - this.contractsRepositoryUsername, this.contractsRepositoryPassword, - this.contractsRepositoryProxyHost, this.contractsRepositoryProxyPort, - this.deleteStubsAfterTest, this.contractsProperties) - .downloadAndUnpackContractsIfRequired(config, this.contractsDirectory); + this.contractsPath, this.contractsRepositoryUrl, this.contractsMode, + getLog(), this.contractsRepositoryUsername, + this.contractsRepositoryPassword, this.contractsRepositoryProxyHost, + this.contractsRepositoryProxyPort, this.deleteStubsAfterTest, + this.contractsProperties).downloadAndUnpackContractsIfRequired(config, + this.contractsDirectory); } private File stubsOutputDir(String rootPath) { - return isInsideProject() ? new File(this.stubsDirectory, rootPath + MAPPINGS_PATH) : this.destination; + return isInsideProject() ? new File(this.stubsDirectory, rootPath + MAPPINGS_PATH) + : this.destination; } private File contractsDslDir(File contractsDirectory) { - return isInsideProject() ? - contractsDirectory : this.source; + return isInsideProject() ? contractsDirectory : this.source; } private boolean isInsideProject() { diff --git a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/CopyContracts.java b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/CopyContracts.java index e68be8c7f9..fd1ecc2540 100644 --- a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/CopyContracts.java +++ b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/CopyContracts.java @@ -30,11 +30,17 @@ import org.slf4j.LoggerFactory; import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties; class CopyContracts { + private static final Logger log = LoggerFactory.getLogger(CopyContracts.class); + private static final String CONTRACTS_PATH = "/contracts"; + private final MavenProject project; + private final MavenSession mavenSession; + private final MavenResourcesFiltering mavenResourcesFiltering; + private final ContractVerifierConfigProperties config; CopyContracts(MavenProject project, MavenSession mavenSession, @@ -48,17 +54,19 @@ class CopyContracts { public void copy(File contractsDirectory, File outputDirectory, String rootPath) throws MojoExecutionException { - File outputFolderWithContracts = outputDirectory.getPath().endsWith("contracts") ? - outputDirectory : new File(outputDirectory, rootPath + CONTRACTS_PATH); - log.info("Copying Spring Cloud Contract Verifier contracts to ["+ outputFolderWithContracts + "]" - + ". Only files matching [" + this.config.getIncludedContracts() + "] pattern will end up in " + File outputFolderWithContracts = outputDirectory.getPath().endsWith("contracts") + ? outputDirectory : new File(outputDirectory, rootPath + CONTRACTS_PATH); + log.info("Copying Spring Cloud Contract Verifier contracts to [" + + outputFolderWithContracts + "]" + ". Only files matching [" + + this.config.getIncludedContracts() + "] pattern will end up in " + "the final JAR with stubs."); Resource resource = new Resource(); - String includedRootFolderAntPattern = this.config.getIncludedRootFolderAntPattern() + "*.*"; - String slashSeparatedGroupIdAntPattern = - slashSeparatedGroupIdAntPattern(includedRootFolderAntPattern); - String dotSeparatedGroupIdAntPattern = - dotSeparatedGroupIdAntPattern(includedRootFolderAntPattern); + String includedRootFolderAntPattern = this.config + .getIncludedRootFolderAntPattern() + "*.*"; + String slashSeparatedGroupIdAntPattern = slashSeparatedGroupIdAntPattern( + includedRootFolderAntPattern); + String dotSeparatedGroupIdAntPattern = dotSeparatedGroupIdAntPattern( + includedRootFolderAntPattern); // by default group id is slash separated... resource.addInclude(slashSeparatedGroupIdAntPattern); if (!slashSeparatedGroupIdAntPattern.equals(dotSeparatedGroupIdAntPattern)) { @@ -91,8 +99,10 @@ class CopyContracts { private String slashSeparatedGroupIdAntPattern(String includedRootFolderAntPattern) { if (includedRootFolderAntPattern.contains(slashSeparatedGroupId())) { return includedRootFolderAntPattern; - } else if (includedRootFolderAntPattern.contains(dotSeparatedGroupId())) { - return includedRootFolderAntPattern.replace(dotSeparatedGroupId(), slashSeparatedGroupId()); + } + else if (includedRootFolderAntPattern.contains(dotSeparatedGroupId())) { + return includedRootFolderAntPattern.replace(dotSeparatedGroupId(), + slashSeparatedGroupId()); } return includedRootFolderAntPattern; } @@ -100,8 +110,10 @@ class CopyContracts { private String dotSeparatedGroupIdAntPattern(String includedRootFolderAntPattern) { if (includedRootFolderAntPattern.contains(dotSeparatedGroupId())) { return includedRootFolderAntPattern; - } else if (includedRootFolderAntPattern.contains(slashSeparatedGroupId())) { - return includedRootFolderAntPattern.replace(slashSeparatedGroupId(), dotSeparatedGroupId()); + } + else if (includedRootFolderAntPattern.contains(slashSeparatedGroupId())) { + return includedRootFolderAntPattern.replace(slashSeparatedGroupId(), + dotSeparatedGroupId()); } return includedRootFolderAntPattern; } diff --git a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/GenerateStubsMojo.java b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/GenerateStubsMojo.java index 20a72dfcf5..dfc90c2361 100644 --- a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/GenerateStubsMojo.java +++ b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/GenerateStubsMojo.java @@ -33,18 +33,16 @@ import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.jar.JarArchiver; /** - * Picks the converted .json files and creates a jar. Requires convert to be executed first + * Picks the converted .json files and creates a jar. Requires convert to be executed + * first */ -@Mojo(name = "generateStubs", defaultPhase = LifecyclePhase.PACKAGE, - requiresProject = true) +@Mojo(name = "generateStubs", defaultPhase = LifecyclePhase.PACKAGE, requiresProject = true) public class GenerateStubsMojo extends AbstractMojo { - @Parameter(defaultValue = "${project.build.directory}", readonly = true, - required = true) + @Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true) private File projectBuildDirectory; - @Parameter(property = "stubsDirectory", - defaultValue = "${project.build.directory}/stubs") + @Parameter(property = "stubsDirectory", defaultValue = "${project.build.directory}/stubs") private File outputDirectory; /** @@ -81,22 +79,24 @@ public class GenerateStubsMojo extends AbstractMojo { if (this.skip || this.jarSkip) { getLog().info( "Skipping Spring Cloud Contract Verifier execution: spring.cloud.contract.verifier.skip=" - + this.skip + ", spring.cloud.contract.verifier.jar.skip=" + this.jarSkip); + + this.skip + ", spring.cloud.contract.verifier.jar.skip=" + + this.jarSkip); return; } File stubsJarFile = createStubJar(this.outputDirectory); - this.projectHelper.attachArtifact(this.project, "jar", this.classifier, stubsJarFile); + this.projectHelper.attachArtifact(this.project, "jar", this.classifier, + stubsJarFile); } private File createStubJar(File stubsOutputDir) throws MojoFailureException, MojoExecutionException { if (!stubsOutputDir.exists()) { - throw new MojoExecutionException( - "Stubs could not be found: [" + stubsOutputDir.getAbsolutePath() - + "] .\nPlease make sure that spring-cloud-contract:convert was invoked"); + throw new MojoExecutionException("Stubs could not be found: [" + + stubsOutputDir.getAbsolutePath() + + "] .\nPlease make sure that spring-cloud-contract:convert was invoked"); } - String stubArchiveName = - this.project.getBuild().getFinalName() + "-" + this.classifier + ".jar"; + String stubArchiveName = this.project.getBuild().getFinalName() + "-" + + this.classifier + ".jar"; File stubsJarFile = new File(this.projectBuildDirectory, stubArchiveName); String[] excludes = excludes(); getLog().info("Files matching this pattern will be excluded from " @@ -106,7 +106,8 @@ public class GenerateStubsMojo extends AbstractMojo { excludedFilesEmpty() ? new String[0] : this.excludedFiles); this.archiver.setCompress(true); this.archiver.setDestFile(stubsJarFile); - this.archiver.addConfiguredManifest(ManifestCreator.createManifest(this.project)); + this.archiver + .addConfiguredManifest(ManifestCreator.createManifest(this.project)); this.archiver.createArchive(); } catch (Exception e) { diff --git a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/GenerateTestsMojo.java b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/GenerateTestsMojo.java index 99cd483dbc..674879db2f 100644 --- a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/GenerateTestsMojo.java +++ b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/GenerateTestsMojo.java @@ -44,22 +44,19 @@ import org.springframework.cloud.contract.verifier.config.TestFramework; import org.springframework.cloud.contract.verifier.config.TestMode; /** - * From the provided directory with contracts generates the acceptance - * tests on the producer side + * From the provided directory with contracts generates the acceptance tests on the + * producer side */ -@Mojo(name = "generateTests", defaultPhase = LifecyclePhase.GENERATE_TEST_SOURCES, - requiresDependencyResolution = ResolutionScope.TEST) +@Mojo(name = "generateTests", defaultPhase = LifecyclePhase.GENERATE_TEST_SOURCES, requiresDependencyResolution = ResolutionScope.TEST) public class GenerateTestsMojo extends AbstractMojo { @Parameter(defaultValue = "${repositorySystemSession}", readonly = true) private RepositorySystemSession repoSession; - @Parameter(property = "spring.cloud.contract.verifier.contractsDirectory", - defaultValue = "${project.basedir}/src/test/resources/contracts") + @Parameter(property = "spring.cloud.contract.verifier.contractsDirectory", defaultValue = "${project.basedir}/src/test/resources/contracts") private File contractsDirectory; - @Parameter( - defaultValue = "${project.build.directory}/generated-test-sources/contracts") + @Parameter(defaultValue = "${project.build.directory}/generated-test-sources/contracts") private File generatedTestSourcesDir; @Parameter @@ -108,8 +105,7 @@ public class GenerateTestsMojo extends AbstractMojo { * Incubating feature. You can check the size of JSON arrays. If not turned on * explicitly will be disabled. */ - @Parameter(property = "spring.cloud.contract.verifier.assert.size", - defaultValue = "false") + @Parameter(property = "spring.cloud.contract.verifier.assert.size", defaultValue = "false") private boolean assertJsonSize; /** @@ -127,12 +123,13 @@ public class GenerateTestsMojo extends AbstractMojo { @Parameter(property = "maven.test.skip", defaultValue = "false") private boolean mavenTestSkip; - @Parameter(property = "skipTests", defaultValue = "false") private boolean skipTests; + @Parameter(property = "skipTests", defaultValue = "false") + private boolean skipTests; /** - * The URL from which a contracts should get downloaded. If not provided - * but artifactid / coordinates notation was provided then the current Maven's build repositories will be - * taken into consideration + * The URL from which a contracts should get downloaded. If not provided but + * artifactid / coordinates notation was provided then the current Maven's build + * repositories will be taken into consideration */ @Parameter(property = "contractsRepositoryUrl") private String contractsRepositoryUrl; @@ -141,11 +138,12 @@ public class GenerateTestsMojo extends AbstractMojo { private Dependency contractDependency; /** - * The path in the JAR with all the contracts where contracts for this particular service lay. - * If not provided will be resolved to {@code groupid/artifactid}. Example: + * The path in the JAR with all the contracts where contracts for this particular + * service lay. If not provided will be resolved to {@code groupid/artifactid}. + * Example: *

      - * If {@code groupid} is {@code com.example} and {@code artifactid} is {@code service} then the resolved path will be - * {@code /com/example/artifactid} + * If {@code groupid} is {@code com.example} and {@code artifactid} is {@code service} + * then the resolved path will be {@code /com/example/artifactid} */ @Parameter(property = "contractsPath") private String contractsPath; @@ -157,25 +155,29 @@ public class GenerateTestsMojo extends AbstractMojo { private StubRunnerProperties.StubsMode contractsMode; /** - * A package that contains all the base clases for generated tests. If your contract resides in a location - * {@code src/test/resources/contracts/com/example/v1/} and you provide the {@code packageWithBaseClasses} - * value to {@code com.example.contracts.base} then we will search for a test source file that will - * have the package {@code com.example.contracts.base} and name {@code ExampleV1Base}. As you can see - * it will take the two last folders to and attach {@code Base} to its name. + * A package that contains all the base clases for generated tests. If your contract + * resides in a location {@code src/test/resources/contracts/com/example/v1/} and you + * provide the {@code packageWithBaseClasses} value to + * {@code com.example.contracts.base} then we will search for a test source file that + * will have the package {@code com.example.contracts.base} and name + * {@code ExampleV1Base}. As you can see it will take the two last folders to and + * attach {@code Base} to its name. */ @Parameter(property = "packageWithBaseClasses") private String packageWithBaseClasses; /** - * A way to override any base class mappings. The keys are regular expressions on the package name of the contract - * and the values FQN to a base class for that given expression. + * A way to override any base class mappings. The keys are regular expressions on the + * package name of the contract and the values FQN to a base class for that given + * expression. *

      * Example of a mapping *

      * {@code .*.com.example.v1..*} -> {@code com.example.SomeBaseClass} *

      - * When a contract's package matches the provided regular expression then extending class will be the one - * provided in the map - in this case {@code com.example.SomeBaseClass} + * When a contract's package matches the provided regular expression then extending + * class will be the one provided in the map - in this case + * {@code com.example.SomeBaseClass} */ @Parameter(property = "baseClassMappings") private List baseClassMappings; @@ -205,9 +207,8 @@ public class GenerateTestsMojo extends AbstractMojo { private Integer contractsRepositoryProxyPort; /** - * If {@code true} then will not assert whether a stub / contract - * JAR was downloaded from local or remote location - * + * If {@code true} then will not assert whether a stub / contract JAR was downloaded + * from local or remote location * @deprecated - with 2.1.0 this option is redundant */ @Parameter(property = "contractsSnapshotCheckSkip", defaultValue = "false") @@ -215,14 +216,15 @@ public class GenerateTestsMojo extends AbstractMojo { private boolean contractsSnapshotCheckSkip; /** - * If set to {@code false} will NOT delete stubs from a temporary - * folder after running tests + * If set to {@code false} will NOT delete stubs from a temporary folder after running + * tests */ @Parameter(property = "deleteStubsAfterTest", defaultValue = "true") private boolean deleteStubsAfterTest; /** - * Map of properties that can be passed to custom {@link org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder} + * Map of properties that can be passed to custom + * {@link org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder} */ @Parameter(property = "contractsProperties") private Map contractsProperties = new HashMap<>(); @@ -236,31 +238,45 @@ public class GenerateTestsMojo extends AbstractMojo { public void execute() throws MojoExecutionException, MojoFailureException { if (this.skip || this.mavenTestSkip || this.skipTests) { - if (this.skip) getLog().info("Skipping Spring Cloud Contract Verifier execution: spring.cloud.contract.verifier.skip=" + this.skip); - if (this.mavenTestSkip) getLog().info("Skipping Spring Cloud Contract Verifier execution: maven.test.skip=" + this.mavenTestSkip); - if (this.skipTests) getLog().info("Skipping Spring Cloud Contract Verifier execution: skipTests" + this.skipTests); + if (this.skip) + getLog().info( + "Skipping Spring Cloud Contract Verifier execution: spring.cloud.contract.verifier.skip=" + + this.skip); + if (this.mavenTestSkip) + getLog().info( + "Skipping Spring Cloud Contract Verifier execution: maven.test.skip=" + + this.mavenTestSkip); + if (this.skipTests) + getLog().info( + "Skipping Spring Cloud Contract Verifier execution: skipTests" + + this.skipTests); return; } getLog().info( "Generating server tests source code for Spring Cloud Contract Verifier contract verification"); final ContractVerifierConfigProperties config = new ContractVerifierConfigProperties(); // download contracts, unzip them and pass as output directory - File contractsDirectory = new MavenContractsDownloader(this.project, this.contractDependency, - this.contractsPath, this.contractsRepositoryUrl, this.contractsMode, getLog(), - this.contractsRepositoryUsername, this.contractsRepositoryPassword, - this.contractsRepositoryProxyHost, this.contractsRepositoryProxyPort, - this.deleteStubsAfterTest, this.contractsProperties).downloadAndUnpackContractsIfRequired(config, this.contractsDirectory); - getLog().info("Directory with contract is present at [" + contractsDirectory + "]"); + File contractsDirectory = new MavenContractsDownloader(this.project, + this.contractDependency, this.contractsPath, this.contractsRepositoryUrl, + this.contractsMode, getLog(), this.contractsRepositoryUsername, + this.contractsRepositoryPassword, this.contractsRepositoryProxyHost, + this.contractsRepositoryProxyPort, this.deleteStubsAfterTest, + this.contractsProperties).downloadAndUnpackContractsIfRequired(config, + this.contractsDirectory); + getLog().info( + "Directory with contract is present at [" + contractsDirectory + "]"); setupConfig(config, contractsDirectory); - this.project.addTestCompileSourceRoot(this.generatedTestSourcesDir.getAbsolutePath()); + this.project + .addTestCompileSourceRoot(this.generatedTestSourcesDir.getAbsolutePath()); if (getLog().isInfoEnabled()) { - getLog().info( - "Test Source directory: " + this.generatedTestSourcesDir.getAbsolutePath() - + " added."); + getLog().info("Test Source directory: " + + this.generatedTestSourcesDir.getAbsolutePath() + " added."); getLog().info("Using [" + config.getBaseClassForTests() - + "] as base class for test classes, [" + config.getBasePackageForTests() + "] as base " - + "package for tests, [" + config.getPackageWithBaseClasses() + "] as package with " - + "base classes, base class mappings " + this.baseClassMappings); + + "] as base class for test classes, [" + + config.getBasePackageForTests() + "] as base " + + "package for tests, [" + config.getPackageWithBaseClasses() + + "] as package with " + "base classes, base class mappings " + + this.baseClassMappings); } try { TestGenerator generator = new TestGenerator(config); @@ -270,7 +286,8 @@ public class GenerateTestsMojo extends AbstractMojo { catch (ContractVerifierException e) { throw new MojoExecutionException( String.format("Spring Cloud Contract Verifier Plugin exception: %s", - e.getMessage()), e); + e.getMessage()), + e); } } @@ -299,7 +316,8 @@ public class GenerateTestsMojo extends AbstractMojo { private URL fileToUrl(File contractsDirectory) { try { return contractsDirectory.toURI().toURL(); - } catch (MalformedURLException e) { + } + catch (MalformedURLException e) { throw new IllegalStateException(e); } } @@ -338,4 +356,5 @@ public class GenerateTestsMojo extends AbstractMojo { public void setAssertJsonSize(boolean assertJsonSize) { this.assertJsonSize = assertJsonSize; } + } diff --git a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/ManifestCreator.java b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/ManifestCreator.java index 8b732d0244..d8d92f7d3d 100644 --- a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/ManifestCreator.java +++ b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/ManifestCreator.java @@ -24,19 +24,23 @@ import org.codehaus.plexus.archiver.jar.Manifest; import org.codehaus.plexus.archiver.jar.ManifestException; class ManifestCreator { + public static Manifest createManifest(MavenProject project) throws ManifestException { Manifest manifest = new Manifest(); Plugin verifierMavenPlugin = findMavenPlugin(project.getBuildPlugins()); if (verifierMavenPlugin != null) { - manifest.addConfiguredAttribute(new Manifest.Attribute( - "Spring-Cloud-Contract-Maven-Plugin-Version", verifierMavenPlugin.getVersion())); + manifest.addConfiguredAttribute( + new Manifest.Attribute("Spring-Cloud-Contract-Maven-Plugin-Version", + verifierMavenPlugin.getVersion())); } - if (verifierMavenPlugin != null && !verifierMavenPlugin.getDependencies().isEmpty()) { - Dependency verifierDependency = findVerifierDependency(verifierMavenPlugin.getDependencies()); + if (verifierMavenPlugin != null + && !verifierMavenPlugin.getDependencies().isEmpty()) { + Dependency verifierDependency = findVerifierDependency( + verifierMavenPlugin.getDependencies()); if (verifierDependency != null) { String verifierVersion = verifierDependency.getVersion(); - manifest.addConfiguredAttribute(new Manifest.Attribute("Spring-Cloud-Contract-Verifier-Version", - verifierVersion)); + manifest.addConfiguredAttribute(new Manifest.Attribute( + "Spring-Cloud-Contract-Verifier-Version", verifierVersion)); } } return manifest; diff --git a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/MavenContractsDownloader.java b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/MavenContractsDownloader.java index bd1027495a..c2978af7b8 100644 --- a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/MavenContractsDownloader.java +++ b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/MavenContractsDownloader.java @@ -41,20 +41,33 @@ import org.springframework.util.StringUtils; class MavenContractsDownloader { private static final String LATEST_VERSION = "+"; + private static final String CONTRACTS_DIRECTORY_PROP = "CONTRACTS_DIRECTORY"; private final MavenProject project; + private final Dependency contractDependency; + private final String contractsPath; + private final String contractsRepositoryUrl; + private final StubRunnerProperties.StubsMode stubsMode; + private final Log log; + private final StubDownloaderBuilderProvider stubDownloaderBuilderProvider; + private final String repositoryUsername; + private final String repositoryPassword; + private final String repositoryProxyHost; + private final Integer repositoryProxyPort; + private final boolean deleteStubsAfterTest; + private final Map contractsProperties; MavenContractsDownloader(MavenProject project, Dependency contractDependency, @@ -78,47 +91,56 @@ class MavenContractsDownloader { this.contractsProperties = contractsProperties; } - File downloadAndUnpackContractsIfRequired(ContractVerifierConfigProperties config, File defaultContractsDir) { - String contractsDirFromProp = this.project.getProperties().getProperty(CONTRACTS_DIRECTORY_PROP); - File downloadedContractsDir = StringUtils.hasText(contractsDirFromProp) ? - new File(contractsDirFromProp) : null; + File downloadAndUnpackContractsIfRequired(ContractVerifierConfigProperties config, + File defaultContractsDir) { + String contractsDirFromProp = this.project.getProperties() + .getProperty(CONTRACTS_DIRECTORY_PROP); + File downloadedContractsDir = StringUtils.hasText(contractsDirFromProp) + ? new File(contractsDirFromProp) : null; // reuse downloaded contracts from another mojo if (downloadedContractsDir != null && downloadedContractsDir.exists()) { - this.log.info("Another mojo has downloaded the contracts - will reuse them from [" + downloadedContractsDir + "]"); - contractDownloader().updatePropertiesWithInclusion(downloadedContractsDir, config); + this.log.info( + "Another mojo has downloaded the contracts - will reuse them from [" + + downloadedContractsDir + "]"); + contractDownloader().updatePropertiesWithInclusion(downloadedContractsDir, + config); return downloadedContractsDir; - } else if (shouldDownloadContracts()) { - this.log.info("Download dependency is provided - will retrieve contracts from a remote location"); - File downloadedContracts = contractDownloader().unpackedDownloadedContracts(config); - this.project.getProperties().setProperty(CONTRACTS_DIRECTORY_PROP, downloadedContracts.getAbsolutePath()); + } + else if (shouldDownloadContracts()) { + this.log.info( + "Download dependency is provided - will retrieve contracts from a remote location"); + File downloadedContracts = contractDownloader() + .unpackedDownloadedContracts(config); + this.project.getProperties().setProperty(CONTRACTS_DIRECTORY_PROP, + downloadedContracts.getAbsolutePath()); return downloadedContracts; } - this.log.info("Will use contracts provided in the folder [" + defaultContractsDir + "]"); + this.log.info("Will use contracts provided in the folder [" + defaultContractsDir + + "]"); return defaultContractsDir; } private boolean shouldDownloadContracts() { - return this.contractDependency != null && StringUtils.hasText(this.contractDependency.getArtifactId()) || - StringUtils.hasText(this.contractsRepositoryUrl); + return this.contractDependency != null + && StringUtils.hasText(this.contractDependency.getArtifactId()) + || StringUtils.hasText(this.contractsRepositoryUrl); } private ContractDownloader contractDownloader() { return new ContractDownloader(stubDownloader(), stubConfiguration(), - this.contractsPath, this.project.getGroupId(), this.project.getArtifactId(), - this.project.getVersion()); + this.contractsPath, this.project.getGroupId(), + this.project.getArtifactId(), this.project.getVersion()); } private StubDownloader stubDownloader() { StubRunnerOptions stubRunnerOptions = buildOptions(); - return this.stubDownloaderBuilderProvider. - get(stubRunnerOptions); + return this.stubDownloaderBuilderProvider.get(stubRunnerOptions); } StubRunnerOptions buildOptions() { StubRunnerOptionsBuilder builder = new StubRunnerOptionsBuilder() .withOptions(StubRunnerOptions.fromSystemProps()) - .withStubsMode(this.stubsMode) - .withUsername(this.repositoryUsername) + .withStubsMode(this.stubsMode).withUsername(this.repositoryUsername) .withPassword(this.repositoryPassword) .withDeleteStubsAfterTest(this.deleteStubsAfterTest) .withProperties(this.contractsProperties); @@ -134,9 +156,10 @@ class MavenContractsDownloader { private StubConfiguration stubConfiguration() { String groupId = this.contractDependency.getGroupId(); String artifactId = this.contractDependency.getArtifactId(); - String version = StringUtils.hasText(this.contractDependency.getVersion()) ? - this.contractDependency.getVersion() : LATEST_VERSION; + String version = StringUtils.hasText(this.contractDependency.getVersion()) + ? this.contractDependency.getVersion() : LATEST_VERSION; String classifier = this.contractDependency.getClassifier(); return new StubConfiguration(groupId, artifactId, version, classifier); } + } diff --git a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/PushStubsToScmMojo.java b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/PushStubsToScmMojo.java index bdff73263f..24485b4759 100644 --- a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/PushStubsToScmMojo.java +++ b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/PushStubsToScmMojo.java @@ -37,12 +37,10 @@ import org.springframework.util.StringUtils; @Mojo(name = "pushStubsToScm") public class PushStubsToScmMojo extends AbstractMojo { - @Parameter(defaultValue = "${project.build.directory}", readonly = true, - required = true) + @Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true) private File projectBuildDirectory; - @Parameter(property = "stubsDirectory", - defaultValue = "${project.build.directory}/stubs") + @Parameter(property = "stubsDirectory", defaultValue = "${project.build.directory}/stubs") private File outputDirectory; /** @@ -73,9 +71,9 @@ public class PushStubsToScmMojo extends AbstractMojo { private String contractsRepositoryPassword; /** - * The URL from which a contracts should get downloaded. If not provided - * but artifactid / coordinates notation was provided then the current Maven's build repositories will be - * taken into consideration + * The URL from which a contracts should get downloaded. If not provided but + * artifactid / coordinates notation was provided then the current Maven's build + * repositories will be taken into consideration */ @Parameter(property = "contractsRepositoryUrl") private String contractsRepositoryUrl; @@ -86,16 +84,16 @@ public class PushStubsToScmMojo extends AbstractMojo { @Parameter(property = "contractsMode", defaultValue = "CLASSPATH") private StubRunnerProperties.StubsMode contractsMode; - /** - * If set to {@code false} will NOT delete stubs from a temporary - * folder after running tests + * If set to {@code false} will NOT delete stubs from a temporary folder after running + * tests */ @Parameter(property = "deleteStubsAfterTest", defaultValue = "true") private boolean deleteStubsAfterTest; /** - * Map of properties that can be passed to custom {@link org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder} + * Map of properties that can be passed to custom + * {@link org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder} */ @Parameter(property = "contractsProperties") private Map contractsProperties = new HashMap<>(); @@ -104,17 +102,22 @@ public class PushStubsToScmMojo extends AbstractMojo { if (this.skip || this.taskSkip) { getLog().info( "Skipping Spring Cloud Contract Verifier execution: spring.cloud.contract.verifier.skip=" - + this.skip + ", spring.cloud.contract.verifier.publish-stubs-to-scm.skip=" + this.taskSkip); + + this.skip + + ", spring.cloud.contract.verifier.publish-stubs-to-scm.skip=" + + this.taskSkip); return; } - if (StringUtils.isEmpty(this.contractsRepositoryUrl) || - !ScmStubDownloaderBuilder.isProtocolAccepted(this.contractsRepositoryUrl)) { - getLog().info("Skipping pushing stubs to scm since your [contractsRepositoryUrl] property doesn't match any of the accepted protocols"); + if (StringUtils.isEmpty(this.contractsRepositoryUrl) || !ScmStubDownloaderBuilder + .isProtocolAccepted(this.contractsRepositoryUrl)) { + getLog().info( + "Skipping pushing stubs to scm since your [contractsRepositoryUrl] property doesn't match any of the accepted protocols"); return; } - String projectName = this.project.getGroupId() + ":" + this.project.getArtifactId() + ":" + this.project.getVersion(); + String projectName = this.project.getGroupId() + ":" + + this.project.getArtifactId() + ":" + this.project.getVersion(); getLog().info("Pushing Stubs to SCM for project [" + projectName + "]"); - new ContractProjectUpdater(buildOptions()).updateContractProject(projectName, this.outputDirectory.toPath()); + new ContractProjectUpdater(buildOptions()).updateContractProject(projectName, + this.outputDirectory.toPath()); } StubRunnerOptions buildOptions() { diff --git a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/RunMojo.java b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/RunMojo.java index a9365621ad..67cccc6eef 100644 --- a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/RunMojo.java +++ b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/RunMojo.java @@ -115,7 +115,9 @@ public class RunMojo extends AbstractMojo { public void execute() throws MojoExecutionException, MojoFailureException { if (this.skip || this.skipTestOnly) { - getLog().info("Skipping verifier execution: spring.cloud.contract.verifier.skip=" + this.skip); + getLog().info( + "Skipping verifier execution: spring.cloud.contract.verifier.skip=" + + this.skip); return; } BatchStubRunner batchStubRunner = null; @@ -123,22 +125,22 @@ public class RunMojo extends AbstractMojo { .withStubsClassifier(this.stubsClassifier); if (StringUtils.isEmpty(this.stubs)) { StubRunnerOptions options = optionsBuilder - .withMinMaxPort(this.httpPort, this.httpPort) - .build(); - StubRunner stubRunner = this.localStubRunner.run(resolveStubsDirectory().getAbsolutePath(), options); + .withMinMaxPort(this.httpPort, this.httpPort).build(); + StubRunner stubRunner = this.localStubRunner + .run(resolveStubsDirectory().getAbsolutePath(), options); batchStubRunner = new BatchStubRunner(Collections.singleton(stubRunner)); - } else { - StubRunnerOptions options = optionsBuilder - .withStubs(this.stubs) - .withMinMaxPort(this.minPort, this.maxPort) - .build(); + } + else { + StubRunnerOptions options = optionsBuilder.withStubs(this.stubs) + .withMinMaxPort(this.minPort, this.maxPort).build(); batchStubRunner = this.remoteStubRunner.run(options, this.repoSession); } pressAnyKeyToContinue(); if (batchStubRunner != null) { try { batchStubRunner.close(); - } catch (IOException e) { + } + catch (IOException e) { throw new MojoExecutionException("Fail to close batch stub runner", e); } } @@ -147,7 +149,8 @@ public class RunMojo extends AbstractMojo { private File resolveStubsDirectory() { if (isInsideProject()) { return this.stubsDirectory; - } else { + } + else { return this.destination; } } @@ -159,7 +162,8 @@ public class RunMojo extends AbstractMojo { getLog().info("Press ENTER to continue..."); try { System.in.read(); - } catch (Exception ignored) { + } + catch (Exception ignored) { } } diff --git a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/stubrunner/AetherStubDownloaderFactory.java b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/stubrunner/AetherStubDownloaderFactory.java index bb44d1c2ba..219d4c05df 100644 --- a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/stubrunner/AetherStubDownloaderFactory.java +++ b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/stubrunner/AetherStubDownloaderFactory.java @@ -34,9 +34,11 @@ import org.springframework.core.io.ResourceLoader; @Named @Singleton public class AetherStubDownloaderFactory { + private static final Log log = LogFactory.getLog(AetherStubDownloaderFactory.class); private final MavenProject project; + private final RepositorySystem repoSystem; @Inject @@ -48,10 +50,15 @@ public class AetherStubDownloaderFactory { public StubDownloaderBuilder build(final RepositorySystemSession repoSession) { return new StubDownloaderBuilder() { - @Override public StubDownloader build(StubRunnerOptions stubRunnerOptions) { - log.info("Will download contracts using current build's Maven repository setup"); - return new AetherStubDownloader(AetherStubDownloaderFactory.this.repoSystem, - AetherStubDownloaderFactory.this.project.getRemoteProjectRepositories(), repoSession); + @Override + public StubDownloader build(StubRunnerOptions stubRunnerOptions) { + log.info( + "Will download contracts using current build's Maven repository setup"); + return new AetherStubDownloader( + AetherStubDownloaderFactory.this.repoSystem, + AetherStubDownloaderFactory.this.project + .getRemoteProjectRepositories(), + repoSession); } @Override @@ -60,4 +67,5 @@ public class AetherStubDownloaderFactory { } }; } + } diff --git a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/stubrunner/LocalStubRunner.java b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/stubrunner/LocalStubRunner.java index 313dd02241..8d38cdac9d 100644 --- a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/stubrunner/LocalStubRunner.java +++ b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/stubrunner/LocalStubRunner.java @@ -25,6 +25,7 @@ import org.springframework.cloud.contract.stubrunner.StubRunnerOptions; @Named public class LocalStubRunner { + private static final Log log = LogFactory.getLog(LocalStubRunner.class); public StubRunner run(final String contractsDir, StubRunnerOptions options) { @@ -34,4 +35,5 @@ public class LocalStubRunner { stubRunner.runStubs(); return stubRunner; } + } diff --git a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/stubrunner/RemoteStubRunner.java b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/stubrunner/RemoteStubRunner.java index 6c0a13a671..b620bcfac9 100644 --- a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/stubrunner/RemoteStubRunner.java +++ b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/main/java/org/springframework/cloud/contract/maven/verifier/stubrunner/RemoteStubRunner.java @@ -29,6 +29,7 @@ import org.springframework.cloud.contract.stubrunner.StubRunnerOptions; @Named public class RemoteStubRunner { + private static final Log log = LogFactory.getLog(RemoteStubRunner.class); private final AetherStubDownloaderFactory aetherStubDownloaderFactory; @@ -38,8 +39,10 @@ public class RemoteStubRunner { this.aetherStubDownloaderFactory = aetherStubDownloaderFactory; } - public BatchStubRunner run(StubRunnerOptions options, RepositorySystemSession repositorySystemSession) { - StubDownloader stubDownloader = this.aetherStubDownloaderFactory.build(repositorySystemSession).build(options); + public BatchStubRunner run(StubRunnerOptions options, + RepositorySystemSession repositorySystemSession) { + StubDownloader stubDownloader = this.aetherStubDownloaderFactory + .build(repositorySystemSession).build(options); try { if (log.isDebugEnabled()) { log.debug("Launching StubRunner with args: " + options); @@ -51,9 +54,11 @@ public class RemoteStubRunner { return stubRunner; } catch (Exception e) { - log.error("An exception occurred while trying to execute the stubs: " + e.getMessage()); + log.error("An exception occurred while trying to execute the stubs: " + + e.getMessage()); throw e; } } + } diff --git a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/test/java/org/springframework/cloud/contract/maven/verifier/PluginIT.java b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/test/java/org/springframework/cloud/contract/maven/verifier/PluginIT.java index e75b90a2e5..06135a6d2e 100644 --- a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/test/java/org/springframework/cloud/contract/maven/verifier/PluginIT.java +++ b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/test/java/org/springframework/cloud/contract/maven/verifier/PluginIT.java @@ -58,56 +58,53 @@ public class PluginIT { @Test public void should_build_project_Spring_Boot_Groovy_with_Accurest() throws Exception { File basedir = this.resources.getBasedir("spring-boot-groovy"); - this.maven.forProject(basedir) - .execute("package") - .assertErrorFreeLog() - .assertLogText("Generating server tests source code for Spring Cloud Contract Verifier contract verification") + this.maven.forProject(basedir).execute("package").assertErrorFreeLog() + .assertLogText( + "Generating server tests source code for Spring Cloud Contract Verifier contract verification") .assertLogText("Generated 1 test classes.") - .assertLogText("Converting from Spring Cloud Contract Verifier contracts to WireMock stubs mappings") + .assertLogText( + "Converting from Spring Cloud Contract Verifier contracts to WireMock stubs mappings") .assertLogText("Creating new stub") - .assertLogText("Running hello.ContractVerifierSpec") - .assertErrorFreeLog(); + .assertLogText("Running hello.ContractVerifierSpec").assertErrorFreeLog(); } @Test public void should_build_project_Spring_Boot_Java_with_Accurest() throws Exception { File basedir = this.resources.getBasedir("spring-boot-java"); - this.maven.forProject(basedir) - .execute("package") - .assertErrorFreeLog() - .assertLogText("Generating server tests source code for Spring Cloud Contract Verifier contract verification") + this.maven.forProject(basedir).execute("package").assertErrorFreeLog() + .assertLogText( + "Generating server tests source code for Spring Cloud Contract Verifier contract verification") .assertLogText("Generated 1 test classes.") - .assertLogText("Converting from Spring Cloud Contract Verifier contracts to WireMock stubs mappings") + .assertLogText( + "Converting from Spring Cloud Contract Verifier contracts to WireMock stubs mappings") .assertLogText("Creating new stub") - .assertLogText("Running hello.ContractVerifierTest") - .assertErrorFreeLog(); + .assertLogText("Running hello.ContractVerifierTest").assertErrorFreeLog(); } @Test public void should_build_project_with_plugin_extension() throws Exception { File basedir = this.resources.getBasedir("plugin-extension"); - this.maven.forProject(basedir) - .execute("package") - .assertErrorFreeLog() - .assertLogText("Generating server tests source code for Spring Cloud Contract Verifier contract verification") + this.maven.forProject(basedir).execute("package").assertErrorFreeLog() + .assertLogText( + "Generating server tests source code for Spring Cloud Contract Verifier contract verification") .assertLogText("Generated 1 test classes.") - .assertLogText("Converting from Spring Cloud Contract Verifier contracts to WireMock stubs mappings") + .assertLogText( + "Converting from Spring Cloud Contract Verifier contracts to WireMock stubs mappings") .assertLogText("Creating new stub") - .assertLogText("Running hello.ContractVerifierTest") - .assertErrorFreeLog(); + .assertLogText("Running hello.ContractVerifierTest").assertErrorFreeLog(); } @Test - public void should_convert_Accurest_Contracts_to_WireMock_Stubs_mappings() throws Exception { + public void should_convert_Accurest_Contracts_to_WireMock_Stubs_mappings() + throws Exception { File basedir = this.resources.getBasedir("pomless"); this.properties.getPluginVersion(); - this.maven.forProject(basedir) - .withCliOption("-X") - .execute(String.format("org.springframework.cloud:spring-cloud-contract-maven-plugin:%s:convert", - this.properties.getPluginVersion())) - .assertLogText("Converting from Spring Cloud Contract Verifier contracts to WireMock stubs mappings") - .assertLogText("Creating new stub") - .assertErrorFreeLog(); + this.maven.forProject(basedir).withCliOption("-X").execute(String.format( + "org.springframework.cloud:spring-cloud-contract-maven-plugin:%s:convert", + this.properties.getPluginVersion())) + .assertLogText( + "Converting from Spring Cloud Contract Verifier contracts to WireMock stubs mappings") + .assertLogText("Creating new stub").assertErrorFreeLog(); } @Test @@ -115,13 +112,17 @@ public class PluginIT { int availableTcpPort = SocketUtils.findAvailableTcpPort(); File basedir = this.resources.getBasedir("generatedStubsOnly"); this.properties.getPluginVersion(); - this.maven.forProject(basedir) - .withCliOption("-X") - .withCliOption("-Dspring.cloud.contract.verifier.http.port=" + availableTcpPort) - .withCliOption("-Dspring.cloud.contract.verifier.wait-for-key-pressed=false") - .execute(String.format("org.springframework.cloud:spring-cloud-contract-maven-plugin:%s:run", + this.maven.forProject(basedir).withCliOption("-X") + .withCliOption( + "-Dspring.cloud.contract.verifier.http.port=" + availableTcpPort) + .withCliOption( + "-Dspring.cloud.contract.verifier.wait-for-key-pressed=false") + .execute(String.format( + "org.springframework.cloud:spring-cloud-contract-maven-plugin:%s:run", this.properties.getPluginVersion())) - .assertLogText("All stubs are now running RunningStubs [namesAndPorts={=" + availableTcpPort + "}]") + .assertLogText("All stubs are now running RunningStubs [namesAndPorts={=" + + availableTcpPort + "}]") .assertErrorFreeLog(); } + } \ No newline at end of file diff --git a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/test/java/org/springframework/cloud/contract/maven/verifier/PluginUnitTest.java b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/test/java/org/springframework/cloud/contract/maven/verifier/PluginUnitTest.java index 70fa7c69bc..5e0711ebf6 100644 --- a/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/test/java/org/springframework/cloud/contract/maven/verifier/PluginUnitTest.java +++ b/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/test/java/org/springframework/cloud/contract/maven/verifier/PluginUnitTest.java @@ -47,40 +47,55 @@ public class PluginUnitTest { public void shouldGenerateWireMockStubsInDefaultLocation() throws Exception { File basedir = this.resources.getBasedir("basic"); this.maven.executeMojo(basedir, "convert", defaultPackageForTests()); - assertFilesPresent(basedir, "target/stubs/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/Sample.json".replace("/", File.separator)); - assertFilesNotPresent(basedir, "target/stubs/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/Messaging.json".replace("/", File.separator)); + assertFilesPresent(basedir, + "target/stubs/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/Sample.json" + .replace("/", File.separator)); + assertFilesNotPresent(basedir, + "target/stubs/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/Messaging.json" + .replace("/", File.separator)); } private Xpp3Dom defaultPackageForTests() { - return newParameter("basePackageForTests", "org.springframework.cloud.contract.verifier.tests"); + return newParameter("basePackageForTests", + "org.springframework.cloud.contract.verifier.tests"); } @Test public void shouldGenerateWireMockFromStubsDirectory() throws Exception { File basedir = this.resources.getBasedir("withStubs"); - this.maven.executeMojo(basedir, "convert", defaultPackageForTests(), newParameter("contractsDirectory", "src/test/resources/stubs")); - assertFilesPresent(basedir, "target/stubs/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/Sample.json".replace("/", File.separator)); + this.maven.executeMojo(basedir, "convert", defaultPackageForTests(), + newParameter("contractsDirectory", "src/test/resources/stubs")); + assertFilesPresent(basedir, + "target/stubs/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/Sample.json" + .replace("/", File.separator)); } @Test public void shouldCopyContracts() throws Exception { File basedir = this.resources.getBasedir("basic"); this.maven.executeMojo(basedir, "convert", defaultPackageForTests()); - assertFilesPresent(basedir, "target/stubs/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/contracts/Sample.groovy".replace("/", File.separator)); - assertFilesPresent(basedir, "target/stubs/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/contracts/Messaging.groovy".replace("/", File.separator)); + assertFilesPresent(basedir, + "target/stubs/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/contracts/Sample.groovy" + .replace("/", File.separator)); + assertFilesPresent(basedir, + "target/stubs/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/contracts/Messaging.groovy" + .replace("/", File.separator)); } @Test public void shouldGenerateWireMockStubsInSelectedLocation() throws Exception { File basedir = this.resources.getBasedir("basic"); - this.maven.executeMojo(basedir, "convert", defaultPackageForTests(), newParameter("stubsDirectory", "target/foo")); - assertFilesPresent(basedir, "target/foo/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/Sample.json"); + this.maven.executeMojo(basedir, "convert", defaultPackageForTests(), + newParameter("stubsDirectory", "target/foo")); + assertFilesPresent(basedir, + "target/foo/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/Sample.json"); } @Test public void shouldGenerateContractSpecificationInDefaultLocation() throws Exception { File basedir = this.resources.getBasedir("basic"); - this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("testFramework", "SPOCK")); + this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), + newParameter("testFramework", "SPOCK")); String path = "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierSpec.groovy"; assertFilesPresent(basedir, path); File test = new File(basedir, path); @@ -98,7 +113,8 @@ public class PluginUnitTest { @Test public void shouldGenerateContractTestsWithCustomImports() throws Exception { File basedir = this.resources.getBasedir("basic"); - this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("imports", "")); + this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), + newParameter("imports", "")); assertFilesPresent(basedir, "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java"); } @@ -109,17 +125,20 @@ public class PluginUnitTest { this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests()); assertFilesPresent(basedir, "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java"); - File test = new File(basedir, "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java"); + File test = new File(basedir, + "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java"); then(FileUtils.readFileToString(test)).doesNotContain("hasSize(4)"); } @Test public void shouldGenerateContractTestsWithArraySize() throws Exception { File basedir = this.resources.getBasedir("basic"); - this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("assertJsonSize", "true")); + this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), + newParameter("assertJsonSize", "true")); assertFilesPresent(basedir, "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java"); - File test = new File(basedir, "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java"); + File test = new File(basedir, + "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java"); then(FileUtils.readFileToString(test)).contains("hasSize(4)"); } @@ -133,7 +152,8 @@ public class PluginUnitTest { @Test public void shouldGenerateStubsWithMappingsOnly() throws Exception { File basedir = this.resources.getBasedir("generatedStubs"); - this.maven.executeMojo(basedir, "generateStubs", defaultPackageForTests(), newParameter("attachContracts", "false")); + this.maven.executeMojo(basedir, "generateStubs", defaultPackageForTests(), + newParameter("attachContracts", "false")); assertFilesPresent(basedir, "target/sample-project-0.1-stubs.jar"); // FIXME: add assertion for jar content } @@ -141,109 +161,153 @@ public class PluginUnitTest { @Test public void shouldGenerateStubsWithCustomClassifier() throws Exception { File basedir = this.resources.getBasedir("generatedStubs"); - this.maven.executeMojo(basedir, "generateStubs", defaultPackageForTests(), newParameter("classifier", "foo")); + this.maven.executeMojo(basedir, "generateStubs", defaultPackageForTests(), + newParameter("classifier", "foo")); assertFilesPresent(basedir, "target/sample-project-0.1-foo.jar"); } @Test public void shouldGenerateStubsByDownloadingContractsFromARepo() throws Exception { File basedir = this.resources.getBasedir("basic-remote-contracts"); - this.maven.executeMojo(basedir, "convert", defaultPackageForTests(), newParameter("contractsRepositoryUrl", "file://" + PluginUnitTest.class.getClassLoader().getResource("m2repo/repository").getFile().replace("/", File.separator))); - assertFilesPresent(basedir, "target/stubs/META-INF/com.example/server/0.1.BUILD-SNAPSHOT/mappings/com/example/server/client1/contracts/shouldMarkClientAsFraud.json"); + this.maven.executeMojo(basedir, "convert", defaultPackageForTests(), + newParameter("contractsRepositoryUrl", + "file://" + PluginUnitTest.class.getClassLoader() + .getResource("m2repo/repository").getFile() + .replace("/", File.separator))); + assertFilesPresent(basedir, + "target/stubs/META-INF/com.example/server/0.1.BUILD-SNAPSHOT/mappings/com/example/server/client1/contracts/shouldMarkClientAsFraud.json"); } @Test - public void shouldGenerateStubsByDownloadingContractsFromARepoWhenCustomPathIsProvided() throws Exception { + public void shouldGenerateStubsByDownloadingContractsFromARepoWhenCustomPathIsProvided() + throws Exception { File basedir = this.resources.getBasedir("complex-remote-contracts"); - this.maven.executeMojo(basedir, "convert", defaultPackageForTests(), newParameter("contractsRepositoryUrl", "file://" + PluginUnitTest.class.getClassLoader().getResource("m2repo/repository").getFile().replace("/", File.separator))); - assertFilesPresent(basedir, "target/stubs/META-INF/com.example.foo.bar.baz/someartifact/0.1.BUILD-SNAPSHOT/mappings/com/example/server/client1/contracts/shouldMarkClientAsFraud.json"); - assertFilesNotPresent(basedir, "target/stubs/META-INF/com.example.foo.bar.baz/someartifact/0.1.BUILD-SNAPSHOT/mappings/com/foo/bar/baz/shouldBeIgnoredByPlugin.json"); - assertFilesNotPresent(basedir, "target/stubs/META-INF/com.example.foo.bar.baz/someartifact/0.1.BUILD-SNAPSHOT/contracts/com/foo/bar/baz/shouldBeIgnoredByPlugin.groovy"); + this.maven.executeMojo(basedir, "convert", defaultPackageForTests(), + newParameter("contractsRepositoryUrl", + "file://" + PluginUnitTest.class.getClassLoader() + .getResource("m2repo/repository").getFile() + .replace("/", File.separator))); + assertFilesPresent(basedir, + "target/stubs/META-INF/com.example.foo.bar.baz/someartifact/0.1.BUILD-SNAPSHOT/mappings/com/example/server/client1/contracts/shouldMarkClientAsFraud.json"); + assertFilesNotPresent(basedir, + "target/stubs/META-INF/com.example.foo.bar.baz/someartifact/0.1.BUILD-SNAPSHOT/mappings/com/foo/bar/baz/shouldBeIgnoredByPlugin.json"); + assertFilesNotPresent(basedir, + "target/stubs/META-INF/com.example.foo.bar.baz/someartifact/0.1.BUILD-SNAPSHOT/contracts/com/foo/bar/baz/shouldBeIgnoredByPlugin.groovy"); } @Test public void shouldGenerateOutputWhenCalledConvertFromRootProject() throws Exception { File basedir = this.resources.getBasedir("different-module-configuration"); this.maven.executeMojo(basedir, "convert", defaultPackageForTests()); - assertFilesPresent(basedir, "target/stubs/META-INF/com.blogspot.toomuchcoding.frauddetection/frauddetection-parent/0.1.0/mappings/shouldMarkClientAsFraud.json"); + assertFilesPresent(basedir, + "target/stubs/META-INF/com.blogspot.toomuchcoding.frauddetection/frauddetection-parent/0.1.0/mappings/shouldMarkClientAsFraud.json"); } @Test - public void shouldGenerateOutputWhenCalledGenerateTestsFromRootProject() throws Exception { + public void shouldGenerateOutputWhenCalledGenerateTestsFromRootProject() + throws Exception { File basedir = this.resources.getBasedir("different-module-configuration"); this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests()); - assertFilesPresent(basedir, "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java"); + assertFilesPresent(basedir, + "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java"); } @Test public void shouldGenerateTestsByDownloadingContractsFromARepo() throws Exception { File basedir = this.resources.getBasedir("basic-remote-contracts"); - this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("contractsRepositoryUrl", "file://" + PluginUnitTest.class.getClassLoader().getResource("m2repo/repository").getFile().replace("/", File.separator))); - assertFilesPresent(basedir, "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/com/example/server/client1/ContractsTest.java"); + this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), + newParameter("contractsRepositoryUrl", + "file://" + PluginUnitTest.class.getClassLoader() + .getResource("m2repo/repository").getFile() + .replace("/", File.separator))); + assertFilesPresent(basedir, + "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/com/example/server/client1/ContractsTest.java"); } @Test - public void shouldGenerateTestsByDownloadingContractsFromARepoWhenCustomPathIsProvided() throws Exception { + public void shouldGenerateTestsByDownloadingContractsFromARepoWhenCustomPathIsProvided() + throws Exception { File basedir = this.resources.getBasedir("complex-remote-contracts"); - this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("contractsRepositoryUrl", "file://" + PluginUnitTest.class.getClassLoader().getResource("m2repo/repository").getFile().replace("/", File.separator))); - assertFilesPresent(basedir, "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/com/example/server/client1/ContractsTest.java"); - assertFilesNotPresent(basedir, "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/com/foo/bar/BazTest.java"); - assertFilesNotPresent(basedir, "target/stubs/contracts/com/foo/bar/baz/shouldBeIgnoredByPlugin.groovy"); + this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), + newParameter("contractsRepositoryUrl", + "file://" + PluginUnitTest.class.getClassLoader() + .getResource("m2repo/repository").getFile() + .replace("/", File.separator))); + assertFilesPresent(basedir, + "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/com/example/server/client1/ContractsTest.java"); + assertFilesNotPresent(basedir, + "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/com/foo/bar/BazTest.java"); + assertFilesNotPresent(basedir, + "target/stubs/contracts/com/foo/bar/baz/shouldBeIgnoredByPlugin.groovy"); } @Test - public void shouldGenerateContractTestsWithBaseClassResolvedFromConvention() throws Exception { + public void shouldGenerateContractTestsWithBaseClassResolvedFromConvention() + throws Exception { File basedir = this.resources.getBasedir("basic-generated-baseclass"); - this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("testFramework", "JUNIT")); + this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), + newParameter("testFramework", "JUNIT")); String path = "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/hello/V1Test.java"; assertFilesPresent(basedir, path); File test = new File(basedir, path); - then(FileUtils.readFileToString(test)).contains("extends HelloV1Base").contains("import hello.HelloV1Base"); + then(FileUtils.readFileToString(test)).contains("extends HelloV1Base") + .contains("import hello.HelloV1Base"); } @Test - public void shouldGenerateContractTestsWithBaseClassResolvedFromConventionForSpock() throws Exception { + public void shouldGenerateContractTestsWithBaseClassResolvedFromConventionForSpock() + throws Exception { File basedir = this.resources.getBasedir("basic-generated-baseclass"); - this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("testFramework", "SPOCK")); + this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), + newParameter("testFramework", "SPOCK")); String path = "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/hello/V1Spec.groovy"; assertFilesPresent(basedir, path); File test = new File(basedir, path); - then(FileUtils.readFileToString(test)).contains("extends HelloV1Base").contains("import hello.HelloV1Base"); + then(FileUtils.readFileToString(test)).contains("extends HelloV1Base") + .contains("import hello.HelloV1Base"); } @Test - public void shouldGenerateContractTestsWithBaseClassResolvedFromMapping() throws Exception { + public void shouldGenerateContractTestsWithBaseClassResolvedFromMapping() + throws Exception { File basedir = this.resources.getBasedir("basic-baseclass-from-mappings"); - this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("testFramework", "JUNIT")); + this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), + newParameter("testFramework", "JUNIT")); String path = "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/com/hello/V1Test.java"; assertFilesPresent(basedir, path); File test = new File(basedir, path); - then(FileUtils.readFileToString(test)).contains("extends TestBase").contains("import com.example.TestBase"); + then(FileUtils.readFileToString(test)).contains("extends TestBase") + .contains("import com.example.TestBase"); } @Test - public void shouldGenerateContractTestsWithBaseClassResolvedFromMappingNameForSpock() throws Exception { + public void shouldGenerateContractTestsWithBaseClassResolvedFromMappingNameForSpock() + throws Exception { File basedir = this.resources.getBasedir("basic-baseclass-from-mappings"); - this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("testFramework", "SPOCK")); + this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), + newParameter("testFramework", "SPOCK")); String path = "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/com/hello/V1Spec.groovy"; assertFilesPresent(basedir, path); File test = new File(basedir, path); - then(FileUtils.readFileToString(test)).contains("extends TestBase").contains("import com.example.TestBase"); + then(FileUtils.readFileToString(test)).contains("extends TestBase") + .contains("import com.example.TestBase"); } @Test - public void shouldGenerateContractTestsWithAFileContainingAListOfContracts() throws Exception { + public void shouldGenerateContractTestsWithAFileContainingAListOfContracts() + throws Exception { File basedir = this.resources.getBasedir("multiple-contracts"); - this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("testFramework", "JUNIT")); + this.maven.executeMojo(basedir, "generateTests", defaultPackageForTests(), + newParameter("testFramework", "JUNIT")); String path = "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/com/hello/V1Test.java"; assertFilesPresent(basedir, path); @@ -254,18 +318,22 @@ public class PluginUnitTest { } @Test - public void shouldGenerateStubsWithAFileContainingAListOfContracts() throws Exception { + public void shouldGenerateStubsWithAFileContainingAListOfContracts() + throws Exception { File basedir = this.resources.getBasedir("multiple-contracts"); - this.maven.executeMojo(basedir, "convert", defaultPackageForTests(), newParameter("stubsDirectory", "target/foo")); + this.maven.executeMojo(basedir, "convert", defaultPackageForTests(), + newParameter("stubsDirectory", "target/foo")); String firstFile = "target/foo/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/com/hello/v1/should post a user.json"; File test = new File(basedir, firstFile); - assertFilesPresent(basedir, "target/foo/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/com/hello/v1/1_WithList.json"); + assertFilesPresent(basedir, + "target/foo/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/com/hello/v1/1_WithList.json"); then(FileUtils.readFileToString(test)).contains("/users/1"); String secondFile = "target/foo/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/com/hello/v1/1_WithList.json"; File test2 = new File(basedir, secondFile); - assertFilesPresent(basedir, "target/foo/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/com/hello/v1/should post a user.json"); + assertFilesPresent(basedir, + "target/foo/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/com/hello/v1/should post a user.json"); then(FileUtils.readFileToString(test2)).contains("/users/2"); } @@ -277,9 +345,12 @@ public class PluginUnitTest { assertFilesNotPresent(basedir, "target/generated-test-sources/contracts/"); // there will be no stubs cause all files are copied to `target` folder - assertFilesNotPresent(basedir, "target/stubs/META-INF/org.springframework.cloud.verifier.sample/common-repo/0.1/mappings/"); - assertFilesPresent(basedir, "target/stubs/META-INF/org.springframework.cloud.verifier.sample/common-repo/0.1/contracts/consumer1/Messaging.groovy"); - assertFilesPresent(basedir, "target/stubs/META-INF/org.springframework.cloud.verifier.sample/common-repo/0.1/contracts/pom.xml"); + assertFilesNotPresent(basedir, + "target/stubs/META-INF/org.springframework.cloud.verifier.sample/common-repo/0.1/mappings/"); + assertFilesPresent(basedir, + "target/stubs/META-INF/org.springframework.cloud.verifier.sample/common-repo/0.1/contracts/consumer1/Messaging.groovy"); + assertFilesPresent(basedir, + "target/stubs/META-INF/org.springframework.cloud.verifier.sample/common-repo/0.1/contracts/pom.xml"); } @Test @@ -290,10 +361,11 @@ public class PluginUnitTest { assertFilesPresent(basedir, "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java"); - File test = new File(basedir, "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java"); + File test = new File(basedir, + "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java"); String testContents = FileUtils.readFileToString(test); - int countOccurrencesOf = StringUtils - .countOccurrencesOf(testContents, "\t\tMockMvcRequestSpecification"); + int countOccurrencesOf = StringUtils.countOccurrencesOf(testContents, + "\t\tMockMvcRequestSpecification"); then(countOccurrencesOf).isEqualTo(4); } @@ -303,7 +375,8 @@ public class PluginUnitTest { this.maven.executeMojo(basedir, "pushStubsToScm", defaultPackageForTests()); - then(this.capture.toString()).contains("Skipping pushing stubs to scm since your"); + then(this.capture.toString()) + .contains("Skipping pushing stubs to scm since your"); } @Test @@ -320,4 +393,5 @@ public class PluginUnitTest { assertFilesPresent(basedir, "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/common_repo_with_inclusion/reward_rules/src/main/resources/contracts/reward_rules/rest/admin/V1Test.java"); } + } diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/assertion/CollectionAssert.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/assertion/CollectionAssert.java index 648af6cf01..243637387c 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/assertion/CollectionAssert.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/assertion/CollectionAssert.java @@ -13,6 +13,7 @@ import org.assertj.core.api.IterableAssert; * @since 1.1.0 */ public class CollectionAssert extends IterableAssert { + public CollectionAssert(Iterable actual) { super(actual); } @@ -46,44 +47,53 @@ public class CollectionAssert extends IterableAssert { } /** - * Flattens the collection and checks whether size is greater than or equal to the provided value - * @param size - the flattened collection should have size greater than or equal to this value + * Flattens the collection and checks whether size is greater than or equal to the + * provided value + * @param size - the flattened collection should have size greater than or equal to + * this value * @return this */ public CollectionAssert hasFlattenedSizeGreaterThanOrEqualTo(int size) { isNotNull(); int flattenedSize = flattenedSize(0, this.actual); if (!(flattenedSize >= size)) { - failWithMessage("The flattened size <%s> is not greater or equal to <%s>", flattenedSize, size); + failWithMessage("The flattened size <%s> is not greater or equal to <%s>", + flattenedSize, size); } return this; } /** - * Flattens the collection and checks whether size is less than or equal to the provided value - * @param size - the flattened collection should have size less than or equal to this value + * Flattens the collection and checks whether size is less than or equal to the + * provided value + * @param size - the flattened collection should have size less than or equal to this + * value * @return this */ public CollectionAssert hasFlattenedSizeLessThanOrEqualTo(int size) { isNotNull(); int flattenedSize = flattenedSize(0, this.actual); if (!(flattenedSize <= size)) { - failWithMessage("The flattened size <%s> is not less or equal to <%s>", flattenedSize, size); + failWithMessage("The flattened size <%s> is not less or equal to <%s>", + flattenedSize, size); } return this; } /** * Flattens the collection and checks whether size is between the provided value - * @param lowerBound - the flattened collection should have size greater than or equal to this value - * @param higherBound - the flattened collection should have size less than or equal to this value + * @param lowerBound - the flattened collection should have size greater than or equal + * to this value + * @param higherBound - the flattened collection should have size less than or equal + * to this value * @return this */ public CollectionAssert hasFlattenedSizeBetween(int lowerBound, int higherBound) { isNotNull(); int flattenedSize = flattenedSize(0, this.actual); if (!(flattenedSize >= lowerBound && flattenedSize <= higherBound)) { - failWithMessage("The flattened size <%s> is not between <%s> and <%s>", flattenedSize, lowerBound, higherBound); + failWithMessage("The flattened size <%s> is not between <%s> and <%s>", + flattenedSize, lowerBound, higherBound); } return this; } @@ -97,7 +107,8 @@ public class CollectionAssert extends IterableAssert { isNotNull(); int actualSize = size(this.actual); if (!(actualSize >= size)) { - failWithMessage("The size <%s> is not greater or equal to <%s>", actualSize, size); + failWithMessage("The size <%s> is not greater or equal to <%s>", actualSize, + size); } return this; } @@ -111,41 +122,48 @@ public class CollectionAssert extends IterableAssert { isNotNull(); int actualSize = size(this.actual); if (!(actualSize <= size)) { - failWithMessage("The size <%s> is not less or equal to <%s>", actualSize, size); + failWithMessage("The size <%s> is not less or equal to <%s>", actualSize, + size); } return this; } /** * Checks whether size is between the provided value - * @param lowerBound - the collection should have size greater than or equal to this value - * @param higherBound - the collection should have size less than or equal to this value + * @param lowerBound - the collection should have size greater than or equal to this + * value + * @param higherBound - the collection should have size less than or equal to this + * value * @return this */ public CollectionAssert hasSizeBetween(int lowerBound, int higherBound) { isNotNull(); int size = size(this.actual); if (!(size >= lowerBound && size <= higherBound)) { - failWithMessage("The size <%s> is not between <%s> and <%s>", size, lowerBound, higherBound); + failWithMessage("The size <%s> is not between <%s> and <%s>", size, + lowerBound, higherBound); } return this; } - @Override public CollectionAssert as(String description, Object... args) { + @Override + public CollectionAssert as(String description, Object... args) { return (CollectionAssert) super.as(description, args); } private int flattenedSize(int counter, Object object) { if (object instanceof Map) { return counter + ((Map) object).size(); - } else if (object instanceof Iterator) { + } + else if (object instanceof Iterator) { Iterator iterator = ((Iterator) object); while (iterator.hasNext()) { Object next = iterator.next(); counter = flattenedSize(counter, next); } return counter; - } else if (object instanceof Collection) { + } + else if (object instanceof Collection) { return flattenedSize(counter, ((Collection) object).iterator()); } return counter; @@ -158,4 +176,5 @@ public class CollectionAssert extends IterableAssert { } return size; } + } diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/assertion/SpringCloudContractAssertions.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/assertion/SpringCloudContractAssertions.java index 69dd8acbf5..823eab9c55 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/assertion/SpringCloudContractAssertions.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/assertion/SpringCloudContractAssertions.java @@ -12,11 +12,12 @@ public class SpringCloudContractAssertions extends Assertions { /** * Creates a new instance of {@link CollectionAssert}. - * * @param actual the actual value. * @return the created assertion object. */ - public static CollectionAssert assertThat(Iterable actual) { + public static CollectionAssert assertThat( + Iterable actual) { return new CollectionAssert<>(actual); } + } diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/MessageVerifier.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/MessageVerifier.java index 9a1fe37fd3..39522d9646 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/MessageVerifier.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/MessageVerifier.java @@ -22,13 +22,14 @@ import java.util.concurrent.TimeUnit; /** * Core interface that allows you to build, send and receive messages. * - * Destination is relevant to the underlying implementation. Might be a channel, queue, topic etc. + * Destination is relevant to the underlying implementation. Might be a channel, queue, + * topic etc. * * @author Marcin Grzejszczak - * * @since 1.0.0 */ public interface MessageVerifier { + /** * Sends the message to the given destination. */ @@ -40,8 +41,8 @@ public interface MessageVerifier { void send(T payload, Map headers, String destination); /** - * Receives the message from the given destination. You can provide the timeout - * for receiving that message. + * Receives the message from the given destination. You can provide the timeout for + * receiving that message. */ M receive(String destination, long timeout, TimeUnit timeUnit); @@ -49,4 +50,5 @@ public interface MessageVerifier { * Receives the message from the given destination. A default timeout will be applied. */ M receive(String destination); + } diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/amqp/ContractVerifierAmqpAutoConfiguration.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/amqp/ContractVerifierAmqpAutoConfiguration.java index 0679af8ab9..04e780f039 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/amqp/ContractVerifierAmqpAutoConfiguration.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/amqp/ContractVerifierAmqpAutoConfiguration.java @@ -44,14 +44,15 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * Configuration setting up {@link MessageVerifier} for use with plain spring-rabbit/spring-amqp + * Configuration setting up {@link MessageVerifier} for use with plain + * spring-rabbit/spring-amqp * * @author Mathias Düsterhöft * @since 1.0.2 */ @Configuration @ConditionalOnClass(RabbitTemplate.class) -@ConditionalOnProperty(name="stubrunner.amqp.enabled", havingValue="true") +@ConditionalOnProperty(name = "stubrunner.amqp.enabled", havingValue = "true") @AutoConfigureBefore(ContractVerifierIntegrationConfiguration.class) @AutoConfigureAfter(ContractVerifierStreamAutoConfiguration.class) public class ContractVerifierAmqpAutoConfiguration { @@ -72,31 +73,38 @@ public class ContractVerifierAmqpAutoConfiguration { @ConditionalOnMissingBean public MessageVerifier contractVerifierMessageExchange() { return new SpringAmqpStubMessages(this.rabbitTemplate, - new MessageListenerAccessor(this.rabbitListenerEndpointRegistry, this.simpleMessageListenerContainers, this.bindings)); + new MessageListenerAccessor(this.rabbitListenerEndpointRegistry, + this.simpleMessageListenerContainers, this.bindings)); } @Bean @ConditionalOnMissingBean public ContractVerifierMessaging contractVerifierMessaging( MessageVerifier exchange) { - return new ContractVerifierHelper(exchange, this.rabbitTemplate.getMessageConverter()); + return new ContractVerifierHelper(exchange, + this.rabbitTemplate.getMessageConverter()); } + } class ContractVerifierHelper extends ContractVerifierMessaging { private final MessageConverter messageConverter; - public ContractVerifierHelper(MessageVerifier exchange, MessageConverter messageConverter) { + public ContractVerifierHelper(MessageVerifier exchange, + MessageConverter messageConverter) { super(exchange); this.messageConverter = messageConverter; } @Override protected ContractVerifierMessage convert(Message message) { - MessagingMessageConverter messageConverter = new MessagingMessageConverter(this.messageConverter, new SimpleAmqpHeaderMapper()); - org.springframework.messaging.Message messagingMessage = (org.springframework.messaging.Message) messageConverter.fromMessage(message); - return new ContractVerifierMessage(messagingMessage.getPayload(), messagingMessage.getHeaders()); + MessagingMessageConverter messageConverter = new MessagingMessageConverter( + this.messageConverter, new SimpleAmqpHeaderMapper()); + org.springframework.messaging.Message messagingMessage = (org.springframework.messaging.Message) messageConverter + .fromMessage(message); + return new ContractVerifierMessage(messagingMessage.getPayload(), + messagingMessage.getHeaders()); } -} +} diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/amqp/MessageListenerAccessor.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/amqp/MessageListenerAccessor.java index 181161a0b3..928cfa8653 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/amqp/MessageListenerAccessor.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/amqp/MessageListenerAccessor.java @@ -14,9 +14,11 @@ import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; /** * Abstraction hiding details of the different sources of message listeners * - * Needed because {@link org.springframework.amqp.rabbit.annotation.RabbitListenerAnnotationBeanPostProcessor} adds the listeners to the - * {@link RabbitListenerEndpointRegistry} so that the registry is empty when wired into an auto configuration class - * so we wrap it in the accessor to access the listeners late at runtime + * Needed because + * {@link org.springframework.amqp.rabbit.annotation.RabbitListenerAnnotationBeanPostProcessor} + * adds the listeners to the {@link RabbitListenerEndpointRegistry} so that the registry + * is empty when wired into an auto configuration class so we wrap it in the accessor to + * access the listeners late at runtime * * @author Mathias Düsterhöft * @since 1.0.2 @@ -24,28 +26,35 @@ import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; class MessageListenerAccessor { private final RabbitListenerEndpointRegistry rabbitListenerEndpointRegistry; + private final List simpleMessageListenerContainers; + private final List bindings; MessageListenerAccessor(RabbitListenerEndpointRegistry rabbitListenerEndpointRegistry, - List simpleMessageListenerContainers, List bindings) { + List simpleMessageListenerContainers, + List bindings) { this.rabbitListenerEndpointRegistry = rabbitListenerEndpointRegistry; this.simpleMessageListenerContainers = simpleMessageListenerContainers; this.bindings = bindings; } - List getListenerContainersForDestination(String destination, String routingKey) { + List getListenerContainersForDestination( + String destination, String routingKey) { List listenerContainers = collectListenerContainers(); - //we interpret the destination as exchange name and collect all the queues bound to this exchange + // we interpret the destination as exchange name and collect all the queues bound + // to this exchange Set queueNames = collectQueuesBoundToDestination(destination, routingKey); return getListenersByBoundQueues(listenerContainers, queueNames); } - private List getListenersByBoundQueues(List listenerContainers, Set queueNames) { + private List getListenersByBoundQueues( + List listenerContainers, + Set queueNames) { List matchingContainers = new ArrayList<>(); for (SimpleMessageListenerContainer listenerContainer : listenerContainers) { if (listenerContainer.getQueueNames() != null) { - for (String queueName : listenerContainer.getQueueNames()) { + for (String queueName : listenerContainer.getQueueNames()) { if (queueNames.contains(queueName)) { matchingContainers.add(listenerContainer); break; @@ -56,9 +65,10 @@ class MessageListenerAccessor { return matchingContainers; } - private Set collectQueuesBoundToDestination(String destination, String routingKey) { + private Set collectQueuesBoundToDestination(String destination, + String routingKey) { Set queueNames = new HashSet<>(); - for (Binding binding: this.bindings) { + for (Binding binding : this.bindings) { if (destination.equals(binding.getExchange()) && (routingKey == null || routingKey.equals(binding.getRoutingKey())) && DestinationType.QUEUE.equals(binding.getDestinationType())) { @@ -74,12 +84,15 @@ class MessageListenerAccessor { listenerContainers.addAll(this.simpleMessageListenerContainers); } if (this.rabbitListenerEndpointRegistry != null) { - for (MessageListenerContainer listenerContainer : this.rabbitListenerEndpointRegistry.getListenerContainers()) { + for (MessageListenerContainer listenerContainer : this.rabbitListenerEndpointRegistry + .getListenerContainers()) { if (listenerContainer instanceof SimpleMessageListenerContainer) { - listenerContainers.add((SimpleMessageListenerContainer) listenerContainer); + listenerContainers + .add((SimpleMessageListenerContainer) listenerContainer); } } } return listenerContainers; } + } diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/amqp/RabbitMockConnectionFactoryAutoConfiguration.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/amqp/RabbitMockConnectionFactoryAutoConfiguration.java index e7ef0691fc..f788b799ad 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/amqp/RabbitMockConnectionFactoryAutoConfiguration.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/amqp/RabbitMockConnectionFactoryAutoConfiguration.java @@ -18,7 +18,8 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** - * Spring rabbit test utility that provides a mock ConnectionFactory to avoid having to connect against a running broker. + * Spring rabbit test utility that provides a mock ConnectionFactory to avoid having to + * connect against a running broker. * * Set verifier.amqp.mockConnection=true to enable the mocked ConnectionFactory * @@ -34,16 +35,19 @@ public class RabbitMockConnectionFactoryAutoConfiguration { public ConnectionFactory connectionFactory() { final Connection mockConnection = mock(Connection.class); final AMQP.Queue.DeclareOk mockDeclareOk = mock(AMQP.Queue.DeclareOk.class); - com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(com.rabbitmq.client.ConnectionFactory.class, new Answer() { - @Override public Object answer(InvocationOnMock invocationOnMock) - throws Throwable { - // hack for keeping backward compatibility with #303 - if ("newConnection".equals(invocationOnMock.getMethod().getName())) { - return mockConnection; - } - return Mockito.RETURNS_DEFAULTS.answer(invocationOnMock); - } - }); + com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock( + com.rabbitmq.client.ConnectionFactory.class, new Answer() { + @Override + public Object answer(InvocationOnMock invocationOnMock) + throws Throwable { + // hack for keeping backward compatibility with #303 + if ("newConnection" + .equals(invocationOnMock.getMethod().getName())) { + return mockConnection; + } + return Mockito.RETURNS_DEFAULTS.answer(invocationOnMock); + } + }); try { final Channel mockChannel = mock(Channel.class, invocationOnMock -> { if ("queueDeclare".equals(invocationOnMock.getMethod().getName())) { @@ -54,11 +58,13 @@ public class RabbitMockConnectionFactoryAutoConfiguration { when(mockConnection.isOpen()).thenReturn(true); when(mockConnection.createChannel()).thenReturn(mockChannel); when(mockConnection.createChannel(Mockito.anyInt())).thenReturn(mockChannel); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } return new CachingConnectionFactory(mockConnectionFactory) { }; } + } diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/amqp/SpringAmqpStubMessages.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/amqp/SpringAmqpStubMessages.java index 4c684dcb25..6e61e39a09 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/amqp/SpringAmqpStubMessages.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/amqp/SpringAmqpStubMessages.java @@ -42,19 +42,20 @@ import static org.mockito.Mockito.verify; import static org.springframework.amqp.support.converter.DefaultClassMapper.DEFAULT_CLASSID_FIELD_NAME; /** - * {@link MessageVerifier} implementation to integrate with plain spring-amqp/spring-rabbit. - * It is meant to be used without interacting with a running bus. + * {@link MessageVerifier} implementation to integrate with plain + * spring-amqp/spring-rabbit. It is meant to be used without interacting with a running + * bus. * * It relies on the RabbitTemplate to be a spy to be able to capture send messages. * - * Messages are not sent to the bus - but are handed over to a {@link SimpleMessageListenerContainer} which - * allows us to test the full deserialization and listener invocation. + * Messages are not sent to the bus - but are handed over to a + * {@link SimpleMessageListenerContainer} which allows us to test the full deserialization + * and listener invocation. * * @author Mathias Düsterhöft * @since 1.0.2 */ -public class SpringAmqpStubMessages implements - MessageVerifier { +public class SpringAmqpStubMessages implements MessageVerifier { private static final Log log = LogFactory.getLog(SpringAmqpStubMessages.class); @@ -63,10 +64,20 @@ public class SpringAmqpStubMessages implements private final MessageListenerAccessor messageListenerAccessor; @Autowired - public SpringAmqpStubMessages(RabbitTemplate rabbitTemplate, MessageListenerAccessor messageListenerAccessor) { + public SpringAmqpStubMessages(RabbitTemplate rabbitTemplate, + MessageListenerAccessor messageListenerAccessor) { Assert.notNull(rabbitTemplate, "RabbitTemplate must be set"); - Assert.isTrue(mockingDetails(rabbitTemplate).isSpy() || mockingDetails(rabbitTemplate).isMock(), - "StubRunner AMQP will work only if RabbiTemplate is a spy"); //we get send messages by capturing arguments on the spy + Assert.isTrue( + mockingDetails(rabbitTemplate).isSpy() + || mockingDetails(rabbitTemplate).isMock(), + "StubRunner AMQP will work only if RabbiTemplate is a spy"); // we get + // send + // messages + // by + // capturing + // arguments + // on the + // spy this.rabbitTemplate = rabbitTemplate; this.messageListenerAccessor = messageListenerAccessor; } @@ -75,17 +86,17 @@ public class SpringAmqpStubMessages implements public void send(T payload, Map headers, String destination) { Message message = org.springframework.amqp.core.MessageBuilder .withBody(((String) payload).getBytes()) - .andProperties( - MessagePropertiesBuilder.newInstance() - .setContentType((String) headers.get("contentType")) - .copyHeaders(headers).build()) + .andProperties(MessagePropertiesBuilder.newInstance() + .setContentType((String) headers.get("contentType")) + .copyHeaders(headers).build()) .build(); if (headers != null && headers.containsKey(DEFAULT_CLASSID_FIELD_NAME)) { - message.getMessageProperties().setHeader(DEFAULT_CLASSID_FIELD_NAME, headers.get(DEFAULT_CLASSID_FIELD_NAME)); + message.getMessageProperties().setHeader(DEFAULT_CLASSID_FIELD_NAME, + headers.get(DEFAULT_CLASSID_FIELD_NAME)); } if (headers != null && headers.containsKey(AmqpHeaders.RECEIVED_ROUTING_KEY)) { - message.getMessageProperties() - .setReceivedRoutingKey((String) headers.get(AmqpHeaders.RECEIVED_ROUTING_KEY)); + message.getMessageProperties().setReceivedRoutingKey( + (String) headers.get(AmqpHeaders.RECEIVED_ROUTING_KEY)); } send(message, destination); } @@ -93,21 +104,26 @@ public class SpringAmqpStubMessages implements @Override public void send(Message message, String destination) { final String routingKey = message.getMessageProperties().getReceivedRoutingKey(); - List listenerContainers = this.messageListenerAccessor.getListenerContainersForDestination(destination, routingKey); + List listenerContainers = this.messageListenerAccessor + .getListenerContainersForDestination(destination, routingKey); if (listenerContainers.isEmpty()) { - throw new IllegalStateException("no listeners found for destination " + destination); + throw new IllegalStateException( + "no listeners found for destination " + destination); } for (SimpleMessageListenerContainer listenerContainer : listenerContainers) { Object messageListener = listenerContainer.getMessageListener(); - if (messageListener instanceof ChannelAwareMessageListener && listenerContainer.getConnectionFactory() != null) { + if (messageListener instanceof ChannelAwareMessageListener + && listenerContainer.getConnectionFactory() != null) { try { ((ChannelAwareMessageListener) messageListener).onMessage(message, - listenerContainer.getConnectionFactory().createConnection().createChannel(true)); + listenerContainer.getConnectionFactory().createConnection() + .createChannel(true)); } catch (Exception e) { throw new RuntimeException(e); } - } else { + } + else { ((MessageListener) messageListener).onMessage(message); } } @@ -117,13 +133,16 @@ public class SpringAmqpStubMessages implements public Message receive(String destination, long timeout, TimeUnit timeUnit) { ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(Message.class); ArgumentCaptor routingKeyCaptor = ArgumentCaptor.forClass(String.class); - verify(this.rabbitTemplate, atLeastOnce()).send(eq(destination), routingKeyCaptor.capture(), - messageCaptor.capture(), ArgumentMatchers.any()); + verify(this.rabbitTemplate, atLeastOnce()).send(eq(destination), + routingKeyCaptor.capture(), messageCaptor.capture(), + ArgumentMatchers.any()); if (messageCaptor.getAllValues().isEmpty()) { log.info("no messages found on destination [" + destination + "]"); return null; - } else if (messageCaptor.getAllValues().size() > 1) { - log.info("multiple messages found on destination [" + destination + "] returning last one"); + } + else if (messageCaptor.getAllValues().size() > 1) { + log.info("multiple messages found on destination [" + destination + + "] returning last one"); return messageCaptor.getValue(); } Message message = messageCaptor.getValue(); diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/integration/ContractVerifierIntegrationConfiguration.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/integration/ContractVerifierIntegrationConfiguration.java index fbbeae8b68..52310e9b3e 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/integration/ContractVerifierIntegrationConfiguration.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/integration/ContractVerifierIntegrationConfiguration.java @@ -52,6 +52,7 @@ public class ContractVerifierIntegrationConfiguration { MessageVerifier> exchange) { return new ContractVerifierHelper(exchange); } + } class ContractVerifierHelper extends ContractVerifierMessaging> { @@ -64,4 +65,5 @@ class ContractVerifierHelper extends ContractVerifierMessaging> { protected ContractVerifierMessage convert(Message receive) { return new ContractVerifierMessage(receive.getPayload(), receive.getHeaders()); } + } diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/integration/SpringIntegrationStubMessages.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/integration/SpringIntegrationStubMessages.java index 879182d120..bff40043b7 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/integration/SpringIntegrationStubMessages.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/integration/SpringIntegrationStubMessages.java @@ -31,12 +31,12 @@ import org.springframework.messaging.PollableChannel; /** * @author Marcin Grzejszczak */ -public class SpringIntegrationStubMessages implements - MessageVerifier> { +public class SpringIntegrationStubMessages implements MessageVerifier> { private static final Log log = LogFactory.getLog(SpringIntegrationStubMessages.class); private final ApplicationContext context; + private final ContractVerifierIntegrationMessageBuilder builder = new ContractVerifierIntegrationMessageBuilder(); @Autowired @@ -52,11 +52,13 @@ public class SpringIntegrationStubMessages implements @Override public void send(Message message, String destination) { try { - MessageChannel messageChannel = this.context.getBean(destination, MessageChannel.class); + MessageChannel messageChannel = this.context.getBean(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); + } + catch (Exception e) { + log.error("Exception occurred while trying to send a message [" + message + + "] " + "to a channel with name [" + destination + "]", e); throw e; } } @@ -64,11 +66,13 @@ public class SpringIntegrationStubMessages implements @Override public Message receive(String destination, long timeout, TimeUnit timeUnit) { try { - PollableChannel messageChannel = this.context.getBean(destination, PollableChannel.class); + PollableChannel messageChannel = this.context.getBean(destination, + PollableChannel.class); return messageChannel.receive(timeUnit.toMillis(timeout)); - } catch (Exception e) { - log.error("Exception occurred while trying to read a message from " + - " a channel with name [" + destination + "]", e); + } + catch (Exception e) { + log.error("Exception occurred while trying to read a message from " + + " a channel with name [" + destination + "]", e); throw new IllegalStateException(e); } } diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/internal/ContractVerifierMessage.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/internal/ContractVerifierMessage.java index b164325cd6..d475a255f0 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/internal/ContractVerifierMessage.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/internal/ContractVerifierMessage.java @@ -22,7 +22,7 @@ import java.util.Map; /** * Yet another message abstraction. Provides generated tests with a layer that is * independent of the message provider. - * + * * @author Dave Syer * */ @@ -53,7 +53,7 @@ public class ContractVerifierMessage { public Map getHeaders() { return this.headers; } - + public Object getHeader(String name) { return this.headers.get(name); } diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/internal/ContractVerifierMessaging.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/internal/ContractVerifierMessaging.java index 88af11aa7f..6d842e5080 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/internal/ContractVerifierMessaging.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/internal/ContractVerifierMessaging.java @@ -25,9 +25,9 @@ import org.springframework.cloud.contract.verifier.messaging.MessageVerifier; * */ public class ContractVerifierMessaging { - + private final MessageVerifier exchange; - + public ContractVerifierMessaging(MessageVerifier exchange) { this.exchange = exchange; } @@ -35,7 +35,7 @@ public class ContractVerifierMessaging { public void send(ContractVerifierMessage message, String destination) { this.exchange.send(message.getPayload(), message.getHeaders(), destination); } - + public ContractVerifierMessage receive(String destination) { return convert(this.exchange.receive(destination)); } diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/internal/ContractVerifierObjectMapper.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/internal/ContractVerifierObjectMapper.java index d804f48aeb..291af46791 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/internal/ContractVerifierObjectMapper.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/internal/ContractVerifierObjectMapper.java @@ -20,8 +20,8 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; /** - * Wrapper over {@link ObjectMapper} that won't try to parse - * String but will directly return it. + * Wrapper over {@link ObjectMapper} that won't try to parse String but will directly + * return it. * * @author Marcin Grzejszczak */ @@ -40,9 +40,11 @@ public class ContractVerifierObjectMapper { public String writeValueAsString(Object payload) throws JsonProcessingException { if (payload instanceof String) { return payload.toString(); - } else if (payload instanceof byte[]) { + } + else if (payload instanceof byte[]) { return new String((byte[]) payload); } return this.objectMapper.writeValueAsString(payload); } + } diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/noop/NoOpContractVerifierAutoConfiguration.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/noop/NoOpContractVerifierAutoConfiguration.java index 7851a20673..5423cf0c22 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/noop/NoOpContractVerifierAutoConfiguration.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/noop/NoOpContractVerifierAutoConfiguration.java @@ -37,7 +37,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; @AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) public class NoOpContractVerifierAutoConfiguration { - @Autowired(required = false) ObjectMapper objectMapper; + @Autowired(required = false) + ObjectMapper objectMapper; @Bean @ConditionalOnMissingBean diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/noop/NoOpStubMessages.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/noop/NoOpStubMessages.java index 0004638c34..b0edef7a6b 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/noop/NoOpStubMessages.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/noop/NoOpStubMessages.java @@ -25,12 +25,13 @@ import org.springframework.cloud.contract.verifier.messaging.MessageVerifier; * @author Marcin Grzejszczak */ public class NoOpStubMessages implements MessageVerifier { + @Override public void send(Object message, String destination) { } @Override - public void send(T payload, Map headers, String destination) { + public void send(T payload, Map headers, String destination) { } @Override diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/stream/ContractVerifierStreamAutoConfiguration.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/stream/ContractVerifierStreamAutoConfiguration.java index 10306bac66..bf9f1af783 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/stream/ContractVerifierStreamAutoConfiguration.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/stream/ContractVerifierStreamAutoConfiguration.java @@ -36,8 +36,8 @@ import org.springframework.util.Assert; * @author Marcin Grzejszczak */ @Configuration -@ConditionalOnClass({EnableBinding.class, MessageCollector.class}) -@ConditionalOnProperty(name="stubrunner.stream.enabled", havingValue="true", matchIfMissing=true) +@ConditionalOnClass({ EnableBinding.class, MessageCollector.class }) +@ConditionalOnProperty(name = "stubrunner.stream.enabled", havingValue = "true", matchIfMissing = true) @AutoConfigureBefore(NoOpContractVerifierAutoConfiguration.class) public class ContractVerifierStreamAutoConfiguration { @@ -54,12 +54,12 @@ public class ContractVerifierStreamAutoConfiguration { MessageVerifier> exchange) { return new ContractVerifierHelper(exchange); } + } class ContractVerifierHelper extends ContractVerifierMessaging> { - public ContractVerifierHelper( - MessageVerifier> exchange) { + public ContractVerifierHelper(MessageVerifier> exchange) { super(exchange); } @@ -68,5 +68,5 @@ class ContractVerifierHelper extends ContractVerifierMessaging> { Assert.notNull(receive, "Message must not be null!"); return new ContractVerifierMessage(receive.getPayload(), receive.getHeaders()); } -} +} diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/stream/StreamStubMessages.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/stream/StreamStubMessages.java index e90acdd274..4a572af217 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/stream/StreamStubMessages.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/stream/StreamStubMessages.java @@ -39,7 +39,9 @@ public class StreamStubMessages implements MessageVerifier> { private static final Log log = LogFactory.getLog(StreamStubMessages.class); private final ApplicationContext context; + private final MessageCollector messageCollector; + private final ContractVerifierStreamMessageBuilder builder = new ContractVerifierStreamMessageBuilder(); public StreamStubMessages(ApplicationContext context) { @@ -55,8 +57,9 @@ public class StreamStubMessages implements MessageVerifier> { @Override public void send(Message message, String destination) { try { - MessageChannel messageChannel = this.context - .getBean(resolvedDestination(destination, DefaultChannels.OUTPUT), MessageChannel.class); + MessageChannel messageChannel = this.context.getBean( + resolvedDestination(destination, DefaultChannels.OUTPUT), + MessageChannel.class); messageChannel.send(message); } catch (Exception e) { @@ -69,9 +72,11 @@ public class StreamStubMessages implements MessageVerifier> { @Override public Message receive(String destination, long timeout, TimeUnit timeUnit) { try { - MessageChannel messageChannel = this.context - .getBean(resolvedDestination(destination, DefaultChannels.INPUT), MessageChannel.class); - return this.messageCollector.forChannel(messageChannel).poll(timeout, timeUnit); + MessageChannel messageChannel = this.context.getBean( + resolvedDestination(destination, DefaultChannels.INPUT), + MessageChannel.class); + return this.messageCollector.forChannel(messageChannel).poll(timeout, + timeUnit); } catch (Exception e) { log.error("Exception occurred while trying to read a message from " @@ -80,7 +85,8 @@ public class StreamStubMessages implements MessageVerifier> { } } - private String resolvedDestination(String destination, DefaultChannels defaultChannel) { + private String resolvedDestination(String destination, + DefaultChannels defaultChannel) { try { BindingServiceProperties channelBindingServiceProperties = this.context .getBean(BindingServiceProperties.class); @@ -89,32 +95,41 @@ public class StreamStubMessages implements MessageVerifier> { .getBindings().entrySet()) { if (destination.equals(entry.getValue().getDestination())) { if (log.isDebugEnabled()) { - log.debug("Found a channel named [" + - entry.getKey() + "] with destination [" + destination + "]"); + log.debug("Found a channel named [" + entry.getKey() + + "] with destination [" + destination + "]"); } channels.put(entry.getKey().toLowerCase(), destination); } } if (channels.size() == 1) { return channels.keySet().iterator().next(); - } else if (channels.size() > 0) { + } + else if (channels.size() > 0) { if (log.isDebugEnabled()) { - log.debug("Found following channels [" + channels + "] for destination [" + destination + "]. " - + "Will pick the one that matches the default channel name or the first one if none is matching"); + log.debug("Found following channels [" + channels + + "] for destination [" + destination + "]. " + + "Will pick the one that matches the default channel name or the first one if none is matching"); } - String defaultChannelName = channels.get(defaultChannel.name().toLowerCase()); - String matchingChannelName = StringUtils.hasText(defaultChannelName) ? defaultChannel.name().toLowerCase() : channels.keySet().iterator().next(); + String defaultChannelName = channels + .get(defaultChannel.name().toLowerCase()); + String matchingChannelName = StringUtils.hasText(defaultChannelName) + ? defaultChannel.name().toLowerCase() + : channels.keySet().iterator().next(); if (log.isDebugEnabled()) { log.debug("Picked channel name is [" + matchingChannelName + "]"); } return matchingChannelName; } - } catch (Exception e) { - log.error("Exception took place while trying to resolve the destination. Will assume the name [" + destination + "]", e); + } + 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"); + log.debug("No destination named [" + destination + + "] was found. Assuming that the destination equals the channel name"); } return destination; } @@ -126,7 +141,8 @@ public class StreamStubMessages implements MessageVerifier> { } - enum DefaultChannels { + INPUT, OUTPUT + } \ No newline at end of file diff --git a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/util/ContractVerifierMessagingUtil.java b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/util/ContractVerifierMessagingUtil.java index bd48714025..292104613f 100644 --- a/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/util/ContractVerifierMessagingUtil.java +++ b/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/messaging/util/ContractVerifierMessagingUtil.java @@ -110,5 +110,7 @@ public class ContractVerifierMessagingUtil { public int hashCode() { return this.delegate.hashCode(); } + } + } diff --git a/spring-cloud-contract-verifier/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGeneratorSpec.groovy b/spring-cloud-contract-verifier/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGeneratorSpec.groovy index 0d52269987..7c819ab612 100644 --- a/spring-cloud-contract-verifier/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGeneratorSpec.groovy +++ b/spring-cloud-contract-verifier/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGeneratorSpec.groovy @@ -223,7 +223,7 @@ class SingleTestGeneratorSpec extends Specification { SPOCK | TestMode.EXPLICIT | GROOVY_ASSERTER | 'ContractsSpec.groovy' } - def 'should build test class for #testFramework with Rest Assured 2.x'() { + def 'should build test class for #testFramework with Rest Assured 2x'() { given: ContractVerifierConfigProperties properties = new ContractVerifierConfigProperties() properties.targetFramework = testFramework diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/AutoConfigureHttpClient.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/AutoConfigureHttpClient.java index 48f3e9d60b..d921b3cae2 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/AutoConfigureHttpClient.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/AutoConfigureHttpClient.java @@ -28,7 +28,7 @@ import org.springframework.context.annotation.Import; /** * Annotation for test classes that want to install a RestTemplateCustomizer that sets up * a Spring Boot app to ignore SSL errors. Use only in tests! - * + * * @author Dave Syer * */ @@ -38,4 +38,5 @@ import org.springframework.context.annotation.Import; @Import(WireMockRestTemplateConfiguration.class) @PropertyMapping("wiremock.server") public @interface AutoConfigureHttpClient { + } diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMock.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMock.java index b1337ba0c3..747c8d95d5 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMock.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMock.java @@ -29,8 +29,9 @@ import org.springframework.context.annotation.Import; * Annotation for test classes that want to start a WireMock server as part of the Spring * Application Context. The port, https port and stub locations (if any) can all be * controlled directly here. For more fine-grained control of the server instance add a - * bean of type {@link com.github.tomakehurst.wiremock.core.Options} to the application context. - * + * bean of type {@link com.github.tomakehurst.wiremock.core.Options} to the application + * context. + * * @author Dave Syer * */ @@ -46,8 +47,8 @@ public @interface AutoConfigureWireMock { int httpsPort() default -1; - String[] stubs() default {""}; + String[] stubs() default { "" }; - String[] files() default {""}; + String[] files() default { "" }; } diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockApplicationListener.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockApplicationListener.java index ce6f5cf9b7..fcf0385de8 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockApplicationListener.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockApplicationListener.java @@ -32,7 +32,7 @@ import org.springframework.util.SocketUtils; /** * Listener that prepares the environment so that WireMock will work when it is * initialized. For example, by finding free ports for the server to listen on. - * + * * @author Dave Syer * */ @@ -69,7 +69,8 @@ public class WireMockApplicationListener if (!propertySources.contains("wiremock")) { propertySources.addFirst( new MapPropertySource("wiremock", new HashMap())); - } else { + } + else { // Move it up into first place PropertySource wiremock = propertySources.remove("wiremock"); propertySources.addFirst(wiremock); diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockConfiguration.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockConfiguration.java index b75f391fee..67bc1423ed 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockConfiguration.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockConfiguration.java @@ -50,7 +50,7 @@ import org.springframework.web.client.RestTemplate; * configure the properties of the wiremock server you can use the AutoConfigureWireMock * annotation, or add a bean of type {@link Options} (via * {@link WireMockSpring#options()}) to your test context. - * + * * @author Dave Syer * */ @@ -84,7 +84,8 @@ public class WireMockConfiguration implements SmartLifecycle { @PostConstruct public void init() throws IOException { if (this.options == null) { - com.github.tomakehurst.wiremock.core.WireMockConfiguration factory = WireMockSpring.options(); + com.github.tomakehurst.wiremock.core.WireMockConfiguration factory = WireMockSpring + .options(); if (this.wireMock.getServer().getPort() != 8080) { factory.port(this.wireMock.getServer().getPort()); } @@ -103,7 +104,8 @@ public class WireMockConfiguration implements SmartLifecycle { } registerStubs(); if (log.isDebugEnabled()) { - log.debug("WireMock server has [" + this.server.getStubMappings().size() + "] registered"); + log.debug("WireMock server has [" + this.server.getStubMappings().size() + + "] registered"); } if (!this.beanFactory.containsBean(WIREMOCK_SERVER_BEAN_NAME)) { this.beanFactory.registerSingleton(WIREMOCK_SERVER_BEAN_NAME, this.server); @@ -124,7 +126,8 @@ public class WireMockConfiguration implements SmartLifecycle { } for (Resource resource : resolver.getResources(pattern)) { this.server.addStubMapping(WireMockStubMapping - .buildFrom(StreamUtils.copyToString(resource.getInputStream(), Charset.forName("UTF-8")))); + .buildFrom(StreamUtils.copyToString(resource.getInputStream(), + Charset.forName("UTF-8")))); } } } @@ -134,7 +137,9 @@ public class WireMockConfiguration implements SmartLifecycle { this.server.resetAll(); } - private void registerFiles(com.github.tomakehurst.wiremock.core.WireMockConfiguration factory) throws IOException { + private void registerFiles( + com.github.tomakehurst.wiremock.core.WireMockConfiguration factory) + throws IOException { List resources = new ArrayList<>(); for (String files : this.wireMock.getServer().getFiles()) { if (StringUtils.hasText(files)) { @@ -148,7 +153,8 @@ public class WireMockConfiguration implements SmartLifecycle { } } if (!resources.isEmpty()) { - ResourcesFileSource fileSource = new ResourcesFileSource(resources.toArray(new Resource[0])); + ResourcesFileSource fileSource = new ResourcesFileSource( + resources.toArray(new Resource[0])); factory.fileSource(fileSource); } } @@ -159,18 +165,25 @@ public class WireMockConfiguration implements SmartLifecycle { WireMock.configureFor("localhost", this.server.port()); this.running = true; if (log.isDebugEnabled()) { - log.debug("Started WireMock at port [" + this.server.port() + "]. It has [" + this.server.getStubMappings().size() + "] mappings registered"); + log.debug("Started WireMock at port [" + this.server.port() + "]. It has [" + + this.server.getStubMappings().size() + "] mappings registered"); } /* - Thanks to Tom Akehurst: - I looked at tcpdump while running the failing test. HttpUrlConnection is doing something weird - it's creating a connection in a - previous test case, which works fine, then the usual fin -> fin ack etc. etc. ending handshake happens. But it seems it - isn't discarded, but reused after that. Because the server thinks (rightly) that the connection is closed, it just sends a RST packet. - Calling the admin endpoint just happened to remove the dead connection from the pool. - This also fixes the problem (which using the Java HTTP client): System.setProperty("http.keepAlive", "false"); + * Thanks to Tom Akehurst: I looked at tcpdump while running the failing test. + * HttpUrlConnection is doing something weird - it's creating a connection in a + * previous test case, which works fine, then the usual fin -> fin ack etc. etc. + * ending handshake happens. But it seems it isn't discarded, but reused after + * that. Because the server thinks (rightly) that the connection is closed, it + * just sends a RST packet. Calling the admin endpoint just happened to remove the + * dead connection from the pool. This also fixes the problem (which using the + * Java HTTP client): System.setProperty("http.keepAlive", "false"); */ - Assert.isTrue(new RestTemplate().getForEntity("http://localhost:" + this.server.port() + "/__admin/mappings", String.class) - .getStatusCode().is2xxSuccessful(), "__admin/mappings endpoint wasn't accessible"); + Assert.isTrue( + new RestTemplate() + .getForEntity("http://localhost:" + this.server.port() + + "/__admin/mappings", String.class) + .getStatusCode().is2xxSuccessful(), + "__admin/mappings endpoint wasn't accessible"); } @Override @@ -271,6 +284,7 @@ class WireMockProperties { public void setFiles(String[] files) { this.files = files; } + } } \ No newline at end of file diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockConfigurationCustomizer.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockConfigurationCustomizer.java index 709e0405d8..c0f0958368 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockConfigurationCustomizer.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockConfigurationCustomizer.java @@ -1,7 +1,8 @@ package org.springframework.cloud.contract.wiremock; /** - * Allows customization of {@link com.github.tomakehurst.wiremock.core.WireMockConfiguration} + * Allows customization of + * {@link com.github.tomakehurst.wiremock.core.WireMockConfiguration} * * @author Marcin Grzejszczak * @since 1.2.2 @@ -9,4 +10,5 @@ package org.springframework.cloud.contract.wiremock; public interface WireMockConfigurationCustomizer { void customize(com.github.tomakehurst.wiremock.core.WireMockConfiguration config); + } diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockRestServiceServer.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockRestServiceServer.java index 97f9821835..0fd9dc51e5 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockRestServiceServer.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockRestServiceServer.java @@ -67,7 +67,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat * Convenience class for loading WireMock stubs into a {@link MockRestServiceServer}. In * this way using a {@link RestTemplate} can mock the responses from a server using * WireMock JSON DSL instead of the native Java DSL. - * + * * @author Dave Syer * */ @@ -93,7 +93,6 @@ public class WireMockRestServiceServer { /** * Public factory method for wrapping a rest template into a MockRestServiceServer. - * * @param restTemplate the rest template to wrap * @return a WireMockRestServiceServer */ @@ -105,7 +104,6 @@ public class WireMockRestServiceServer { * Flag to tell the MockRestServiceServer to ignore the order of calls when matching * requests. The default is true because there is an implied ordering in the stubs (by * url path and with more specific request matchers first). - * * @param ignoreExpectOrder flag value (default true) * @return this */ @@ -117,7 +115,6 @@ public class WireMockRestServiceServer { /** * If stub locations are given as a directory, then we search recursively in that * directory for files with this suffix. Default is ".json". - * * @param suffix the suffix to use when creating a resource pattern * @return this */ @@ -130,7 +127,6 @@ public class WireMockRestServiceServer { * Add a base url to all requests. Most WireMock JSON stubs have a path, but no * protocol or host in the request matcher, so this is useful when your rest template * is calling to a specific host. - * * @param baseUrl a base url to apply * @return this */ @@ -145,14 +141,13 @@ public class WireMockRestServiceServer { * match, or a plain directory name (which will have * **/*.json appended, where ".json" is the value of the * {@link #suffix(String) suffix}). Examples: - * + * *
       	 * classpath:/mappings/foo.json
       	 * classpath:/mappings/*.json
       	 * classpath:META-INF/com.example/stubs/1.0.0/mappings/**/*.json
       	 * file:src/test/resources/stubs
       	 * 
      - * * @param locations a set of resource locations * @return this */ @@ -164,7 +159,6 @@ public class WireMockRestServiceServer { /** * Add some resource locations for files that represent response bodies. Wiremock * defaults to "file:src/test/resources/__files". - * * @param locations * @return this */ @@ -176,7 +170,6 @@ public class WireMockRestServiceServer { /** * Build a MockRestServiceServer from the configured stubs. The server can later be * verified (optionally), if you need to check that all expected requests were made. - * * @return a MockRestServiceServer */ public MockRestServiceServer build() { @@ -193,15 +186,18 @@ public class WireMockRestServiceServer { } } catch (IOException e) { - throw new IllegalStateException("Cannot load resources for: " + location, e); + throw new IllegalStateException("Cannot load resources for: " + location, + e); } } if (this.ignoreExpectOrder) { Collections.sort(mappings, new StubMappingComparator()); } for (StubMapping mapping : mappings) { - ResponseActions expect = server.expect(requestTo(request(mapping.getRequest()))); - expect.andExpect(method(HttpMethod.valueOf(mapping.getRequest().getMethod().getName()))); + ResponseActions expect = server + .expect(requestTo(request(mapping.getRequest()))); + expect.andExpect(method( + HttpMethod.valueOf(mapping.getRequest().getMethod().getName()))); mapping.getRequest().getBodyPatterns(); bodyPatterns(expect, mapping.getRequest()); requestHeaders(expect, mapping.getRequest()); @@ -216,8 +212,11 @@ public class WireMockRestServiceServer { } for (final ContentPattern pattern : request.getBodyPatterns()) { if (pattern instanceof MatchesJsonPathPattern) { - expect.andExpect(MockRestRequestMatchers.jsonPath(((MatchesJsonPathPattern) pattern).getMatchesJsonPath()).exists()); - } else if (pattern instanceof MatchesXPathPattern) { + expect.andExpect(MockRestRequestMatchers + .jsonPath(((MatchesJsonPathPattern) pattern).getMatchesJsonPath()) + .exists()); + } + else if (pattern instanceof MatchesXPathPattern) { expect.andExpect(xpath((MatchesXPathPattern) pattern)); } expect.andExpect(matchContents(pattern)); @@ -226,11 +225,15 @@ public class WireMockRestServiceServer { private RequestMatcher matchContents(final ContentPattern pattern) { return new RequestMatcher() { - @Override public void match(ClientHttpRequest request) + @Override + public void match(ClientHttpRequest request) throws IOException, AssertionError { - MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;; + MockClientHttpRequest mockRequest = (MockClientHttpRequest) request; + ; MatchResult result = pattern.match(mockRequest.getBodyAsString()); - MatcherAssert.assertThat("Request as string [" + mockRequest.getBodyAsString() + "]", result.isExactMatch()); + MatcherAssert.assertThat( + "Request as string [" + mockRequest.getBodyAsString() + "]", + result.isExactMatch()); } }; } @@ -238,13 +241,15 @@ public class WireMockRestServiceServer { private RequestMatcher xpath(MatchesXPathPattern pattern) { try { return MockRestRequestMatchers.xpath(pattern.getMatchesXPath()).exists(); - } catch (XPathExpressionException e) { + } + catch (XPathExpressionException e) { throw new IllegalStateException(e); } } private String request(RequestPattern request) { - return this.baseUrl + (request.getUrlPath() == null ? (request.getUrl() == null ? "/" : request.getUrl()) + return this.baseUrl + (request.getUrlPath() == null + ? (request.getUrl() == null ? "/" : request.getUrl()) : request.getUrlPath()); } @@ -259,8 +264,8 @@ public class WireMockRestServiceServer { } private StubMapping mapping(Resource resource) throws IOException { - return Json.read(StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset()), - StubMapping.class); + return Json.read(StreamUtils.copyToString(resource.getInputStream(), + Charset.defaultCharset()), StubMapping.class); } private DefaultResponseCreator response(ResponseDefinition response) { @@ -274,7 +279,8 @@ public class WireMockRestServiceServer { } String file = response.getBodyFileName(); if (file != null) { - List locations = this.files.isEmpty() ? Arrays.asList("classpath:/__files/") : this.files; + List locations = this.files.isEmpty() + ? Arrays.asList("classpath:/__files/") : this.files; for (String location : locations) { try { if (!location.endsWith("/")) { @@ -285,12 +291,14 @@ public class WireMockRestServiceServer { try { Resource resource = files.createRelative(file); if (resource.exists()) { - return StreamUtils.copyToString(resource.getInputStream(), + return StreamUtils.copyToString( + resource.getInputStream(), Charset.forName("UTF-8")); } } catch (IOException e) { - throw new IllegalStateException("Cannot locate body file: " + file, e); + throw new IllegalStateException( + "Cannot locate body file: " + file, e); } } } @@ -311,12 +319,15 @@ public class WireMockRestServiceServer { @Override public boolean matches(Object item) { - return pattern.match(new MultiValue(header, Arrays.asList((String) item))).isExactMatch(); + return pattern.match( + new MultiValue(header, Arrays.asList((String) item))) + .isExactMatch(); } @Override public void describeTo(Description description) { - description.appendText("should match header: " + header + " with ") + description + .appendText("should match header: " + header + " with ") .appendText(pattern.getExpected()); } })); @@ -384,7 +395,8 @@ public class WireMockRestServiceServer { if (value == 0) { // Same number of header matchers if (two.getPriority() != null) { - return one.getPriority() != null ? one.getPriority() - two.getPriority() : 1; + return one.getPriority() != null + ? one.getPriority() - two.getPriority() : 1; } value = (int) (one.getInsertionIndex() - two.getInsertionIndex()); } @@ -393,7 +405,8 @@ public class WireMockRestServiceServer { } private String request(RequestPattern request) { - return (request.getUrlPath() == null ? (request.getUrl() == null ? "/" : request.getUrl()) + return (request.getUrlPath() == null + ? (request.getUrl() == null ? "/" : request.getUrl()) : request.getUrlPath()); } diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockRestTemplateConfiguration.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockRestTemplateConfiguration.java index ae99fd40c4..0c9db6cdc7 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockRestTemplateConfiguration.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockRestTemplateConfiguration.java @@ -45,7 +45,8 @@ public class WireMockRestTemplateConfiguration { return new RestTemplateCustomizer() { @Override public void customize(RestTemplate restTemplate) { - if (restTemplate.getRequestFactory() instanceof HttpComponentsClientHttpRequestFactory) { + if (restTemplate + .getRequestFactory() instanceof HttpComponentsClientHttpRequestFactory) { HttpComponentsClientHttpRequestFactory factory = (HttpComponentsClientHttpRequestFactory) restTemplate .getRequestFactory(); factory.setHttpClient(createSslHttpClient()); @@ -68,5 +69,5 @@ public class WireMockRestTemplateConfiguration { } }; } - + } diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockSpring.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockSpring.java index bb60a18369..a870790857 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockSpring.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockSpring.java @@ -30,15 +30,16 @@ import org.springframework.util.ClassUtils; /** * Convenience factory class for a {@link WireMockConfiguration} that knows how to use * Spring Boot to create a stub server. Use, for example, in a JUnit rule: - * + * *
        * @ClassRule
        * public static WireMockClassRule wiremock = new WireMockClassRule(
        * 		WireMockSpring.config());
        * 
      - * - * and then use {@link com.github.tomakehurst.wiremock.client.WireMock} as normal in your test methods. - * + * + * and then use {@link com.github.tomakehurst.wiremock.client.WireMock} as normal in your + * test methods. + * * @author Dave Syer * */ @@ -53,11 +54,9 @@ public abstract class WireMockSpring { HttpsURLConnection .setDefaultHostnameVerifier(NoopHostnameVerifier.INSTANCE); try { - HttpsURLConnection - .setDefaultSSLSocketFactory(SSLContexts.custom() - .loadTrustMaterial(null, - TrustSelfSignedStrategy.INSTANCE) - .build().getSocketFactory()); + HttpsURLConnection.setDefaultSSLSocketFactory(SSLContexts.custom() + .loadTrustMaterial(null, TrustSelfSignedStrategy.INSTANCE) + .build().getSocketFactory()); } catch (Exception e) { Assert.fail("Cannot install custom socket factory: [" + e.getMessage() diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockStubMapping.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockStubMapping.java index 5d582c035e..2859d3a008 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockStubMapping.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockStubMapping.java @@ -6,7 +6,9 @@ import com.github.tomakehurst.wiremock.stubbing.StubMapping; * @author Marcin Grzejszczak */ public class WireMockStubMapping { + public static StubMapping buildFrom(String mappingDefinition) { return StubMapping.buildFrom(mappingDefinition); } + } \ No newline at end of file diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockTestExecutionListener.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockTestExecutionListener.java index 77947f65bf..771121dc75 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockTestExecutionListener.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/WireMockTestExecutionListener.java @@ -15,44 +15,55 @@ public final class WireMockTestExecutionListener extends AbstractTestExecutionLi private static final Log log = LogFactory.getLog(WireMockTestExecutionListener.class); - @Override public void beforeTestClass(TestContext testContext) { + @Override + public void beforeTestClass(TestContext testContext) { try { if (wireMockConfigMissing(testContext)) { return; } - WireMockConfiguration wireMockConfiguration = wireMockConfiguration(testContext); + WireMockConfiguration wireMockConfiguration = wireMockConfiguration( + testContext); if (log.isDebugEnabled()) { - log.debug("WireMock configuration is running [" + wireMockConfiguration.isRunning() + "]"); + log.debug("WireMock configuration is running [" + + wireMockConfiguration.isRunning() + "]"); } if (!wireMockConfiguration.isRunning()) { wireMockConfiguration.reset(); wireMockConfiguration.init(); wireMockConfiguration.start(); } - } catch (Exception e) { + } + catch (Exception e) { if (log.isDebugEnabled()) { - log.debug("Exception occurred while trying to init WireMock configuration", e); + log.debug( + "Exception occurred while trying to init WireMock configuration", + e); } } } private boolean wireMockConfigMissing(TestContext testContext) { - boolean missing = !testContext.getApplicationContext().containsBean(WireMockConfiguration.class.getName()); + boolean missing = !testContext.getApplicationContext() + .containsBean(WireMockConfiguration.class.getName()); if (log.isDebugEnabled()) { log.debug("WireMockConfig is missing [" + missing + "]"); } return missing; } - @Override public void afterTestClass(TestContext testContext) { + @Override + public void afterTestClass(TestContext testContext) { try { if (wireMockConfigMissing(testContext)) { return; } stopWireMockConfiguration(testContext); - } catch (Exception e) { + } + catch (Exception e) { if (log.isDebugEnabled()) { - log.debug("Exception occurred while trying to init WireMock configuration", e); + log.debug( + "Exception occurred while trying to init WireMock configuration", + e); } } } @@ -70,4 +81,5 @@ public final class WireMockTestExecutionListener extends AbstractTestExecutionLi private WireMockConfiguration wireMockConfiguration(TestContext testContext) { return testContext.getApplicationContext().getBean(WireMockConfiguration.class); } + } diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/file/ResourcesFileSource.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/file/ResourcesFileSource.java index 64228f8d04..42ce9fee36 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/file/ResourcesFileSource.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/file/ResourcesFileSource.java @@ -67,7 +67,9 @@ public class ResourcesFileSource implements FileSource { sources[i] = fileOrFallbackToClasspath(resource); } else { - throw new IllegalArgumentException("Unsupported resource type for file source: " + resource.getClass()); + throw new IllegalArgumentException( + "Unsupported resource type for file source: " + + resource.getClass()); } } return sources; @@ -81,8 +83,9 @@ public class ResourcesFileSource implements FileSource { return new ClasspathFileSource(pathFromCompressed(uri)); } return new SingleRootFileSource(getFile(file)); - } catch (IOException e) { - throw new IllegalStateException(e); + } + catch (IOException e) { + throw new IllegalStateException(e); } } @@ -120,13 +123,15 @@ public class ResourcesFileSource implements FileSource { throw new IllegalStateException("Cannot create file for " + name); } - @Override public TextFile getTextFileNamed(String name) { + @Override + public TextFile getTextFileNamed(String name) { for (FileSource resource : this.sources) { TextFile file = resource.getTextFileNamed(name); try { file.readContentsAsString(); return file; - } catch (RuntimeException e) { + } + catch (RuntimeException e) { // Ignore } } @@ -143,7 +148,8 @@ public class ResourcesFileSource implements FileSource { List childSources = new ArrayList<>(); for (FileSource resource : this.sources) { try { - UrlResource uri = new UrlResource(resource.child(subDirectoryName).getUri()); + UrlResource uri = new UrlResource( + resource.child(subDirectoryName).getUri()); if (uri.createRelative(subDirectoryName).exists()) { childSources.add(resource.child(subDirectoryName)); } @@ -219,7 +225,8 @@ public class ResourcesFileSource implements FileSource { return false; } - @Override public void deleteFile(String name) { + @Override + public void deleteFile(String name) { } diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/BasicMappingBuilder.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/BasicMappingBuilder.java index 92ced4f27a..0a33819ecf 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/BasicMappingBuilder.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/BasicMappingBuilder.java @@ -26,14 +26,23 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; class BasicMappingBuilder implements ScenarioMappingBuilder { private RequestPatternBuilder requestPatternBuilder; + private ResponseDefinitionBuilder responseDefBuilder; + private Integer priority; + private String scenarioName; + private String requiredScenarioState; + private String newScenarioState; + private UUID id = UUID.randomUUID(); + private String name; + private boolean isPersistent = false; + private Map postServeActions = new LinkedHashMap<>(); BasicMappingBuilder(RequestMethod method, UrlPattern urlPattern) { @@ -55,7 +64,8 @@ class BasicMappingBuilder implements ScenarioMappingBuilder { return this; } - @Override public BasicMappingBuilder atPriority(Integer priority) { + @Override + public BasicMappingBuilder atPriority(Integer priority) { this.priority = priority; return this; } @@ -66,19 +76,22 @@ class BasicMappingBuilder implements ScenarioMappingBuilder { return this; } - @Override public BasicMappingBuilder withCookie(String name, + @Override + public BasicMappingBuilder withCookie(String name, StringValuePattern cookieValuePattern) { this.requestPatternBuilder.withCookie(name, cookieValuePattern); return this; } - @Override public BasicMappingBuilder withQueryParam(String key, + @Override + public BasicMappingBuilder withQueryParam(String key, StringValuePattern queryParamPattern) { this.requestPatternBuilder.withQueryParam(key, queryParamPattern); return this; } - @Override public ScenarioMappingBuilder withQueryParams( + @Override + public ScenarioMappingBuilder withQueryParams( Map queryParams) { for (Map.Entry entry : queryParams.entrySet()) { this.requestPatternBuilder.withQueryParam(entry.getKey(), entry.getValue()); @@ -86,85 +99,96 @@ class BasicMappingBuilder implements ScenarioMappingBuilder { return this; } - @Override public ScenarioMappingBuilder withRequestBody( - ContentPattern bodyPattern) { + @Override + public ScenarioMappingBuilder withRequestBody(ContentPattern bodyPattern) { this.requestPatternBuilder.withRequestBody(bodyPattern); return this; } - @Override public ScenarioMappingBuilder withMultipartRequestBody( + @Override + public ScenarioMappingBuilder withMultipartRequestBody( MultipartValuePatternBuilder multipartPatternBuilder) { this.requestPatternBuilder.withRequestBodyPart(multipartPatternBuilder.build()); return this; } - @Override public BasicMappingBuilder inScenario(String scenarioName) { + @Override + public BasicMappingBuilder inScenario(String scenarioName) { this.scenarioName = scenarioName; return this; } - @Override public BasicMappingBuilder whenScenarioStateIs(String stateName) { + @Override + public BasicMappingBuilder whenScenarioStateIs(String stateName) { this.requiredScenarioState = stateName; return this; } - @Override public BasicMappingBuilder willSetStateTo(String stateName) { + @Override + public BasicMappingBuilder willSetStateTo(String stateName) { this.newScenarioState = stateName; return this; } - @Override public BasicMappingBuilder withId(UUID id) { + @Override + public BasicMappingBuilder withId(UUID id) { this.id = id; return this; } - @Override public BasicMappingBuilder withName(String name) { + @Override + public BasicMappingBuilder withName(String name) { this.name = name; return this; } - @Override public ScenarioMappingBuilder persistent() { + @Override + public ScenarioMappingBuilder persistent() { this.isPersistent = true; return this; } - @Override public BasicMappingBuilder withBasicAuth(String username, String password) { + @Override + public BasicMappingBuilder withBasicAuth(String username, String password) { this.requestPatternBuilder .withBasicAuth(new BasicCredentials(username, password)); return this; } - @Override public

      BasicMappingBuilder withPostServeAction(String extensionName, + @Override + public

      BasicMappingBuilder withPostServeAction(String extensionName, P parameters) { - Parameters params = parameters instanceof Parameters ? - (Parameters) parameters : - Parameters.of(parameters); + Parameters params = parameters instanceof Parameters ? (Parameters) parameters + : Parameters.of(parameters); this.postServeActions.put(extensionName, params); return this; } - @Override public ScenarioMappingBuilder withMetadata(Map map) { + @Override + public ScenarioMappingBuilder withMetadata(Map map) { throw new UnsupportedOperationException("Metadata not supported"); } - @Override public ScenarioMappingBuilder withMetadata(Metadata metadata) { + @Override + public ScenarioMappingBuilder withMetadata(Metadata metadata) { throw new UnsupportedOperationException("Metadata not supported"); } - @Override public ScenarioMappingBuilder withMetadata(Metadata.Builder builder) { + @Override + public ScenarioMappingBuilder withMetadata(Metadata.Builder builder) { throw new UnsupportedOperationException("Metadata not supported"); } - @Override public StubMapping build() { + @Override + public StubMapping build() { if (this.scenarioName == null && (this.requiredScenarioState != null || this.newScenarioState != null)) { throw new IllegalStateException( "Scenario name must be specified to require or set a new scenario state"); } RequestPattern requestPattern = this.requestPatternBuilder.build(); - ResponseDefinition response = (this.responseDefBuilder != null ? - this.responseDefBuilder : - aResponse()).build(); + ResponseDefinition response = (this.responseDefBuilder != null + ? this.responseDefBuilder : aResponse()).build(); StubMapping mapping = new StubMapping(requestPattern, response); mapping.setPriority(this.priority); mapping.setScenarioName(this.scenarioName); diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/ContractDslSnippet.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/ContractDslSnippet.java index a69fdbacc4..6bb7317988 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/ContractDslSnippet.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/ContractDslSnippet.java @@ -24,7 +24,8 @@ import org.springframework.util.PropertyPlaceholderHelper; import org.springframework.util.StringUtils; /** - * A {@link org.springframework.restdocs.snippet.Snippet} that documents the Spring Cloud Contract Groovy DSL. + * A {@link org.springframework.restdocs.snippet.Snippet} that documents the Spring Cloud + * Contract Groovy DSL. * * @author Marcin Grzejszczak * @since 1.0.4 @@ -32,11 +33,14 @@ import org.springframework.util.StringUtils; public class ContractDslSnippet extends TemplatedSnippet { private static final String CONTRACTS_FOLDER = "contracts"; + private static final String SNIPPET_NAME = "dsl-contract"; private Map model = new HashMap<>(); - private static final Set IGNORED_HEADERS = - new HashSet<>(Arrays.asList(HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH)); + + private static final Set IGNORED_HEADERS = new HashSet<>( + Arrays.asList(HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH)); + private final PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper( "{", "}"); @@ -50,7 +54,6 @@ public class ContractDslSnippet extends TemplatedSnippet { /** * Creates a new {@code ContractDslSnippet} with the given additional * {@code attributes} that will be included in the model during template rendering. - * * @param attributes The additional attributes */ protected ContractDslSnippet(Map attributes) { @@ -64,8 +67,10 @@ public class ContractDslSnippet extends TemplatedSnippet { @Override public void document(Operation operation) throws IOException { - TemplateEngine templateEngine = (TemplateEngine) operation.getAttributes().get(TemplateEngine.class.getName()); - String renderedContract = templateEngine.compileTemplate("default-dsl-contract-only") + TemplateEngine templateEngine = (TemplateEngine) operation.getAttributes() + .get(TemplateEngine.class.getName()); + String renderedContract = templateEngine + .compileTemplate("default-dsl-contract-only") .render(createModelForContract(operation)); this.model.put("contract", renderedContract); storeDslContract(operation, renderedContract); @@ -104,9 +109,11 @@ public class ContractDslSnippet extends TemplatedSnippet { filterHeaders(headers); model.put("request_headers_present", !headers.isEmpty()); model.put("request_headers", headers.entrySet()); - @SuppressWarnings("unchecked") Set jsonPaths = (Set) operation.getAttributes() + @SuppressWarnings("unchecked") + Set jsonPaths = (Set) operation.getAttributes() .get("contract.jsonPaths"); - model.put("request_json_paths_present", jsonPaths != null && !jsonPaths.isEmpty()); + model.put("request_json_paths_present", + jsonPaths != null && !jsonPaths.isEmpty()); model.put("request_json_paths", jsonPaths(jsonPaths)); } @@ -138,23 +145,27 @@ public class ContractDslSnippet extends TemplatedSnippet { throws IOException { RestDocumentationContext context = (RestDocumentationContext) operation .getAttributes().get(RestDocumentationContext.class.getName()); - RestDocumentationContextPlaceholderResolver resolver = new - RestDocumentationContextPlaceholderResolver(context); + RestDocumentationContextPlaceholderResolver resolver = new RestDocumentationContextPlaceholderResolver( + context); String resolvedName = replacePlaceholders(resolver, operation.getName()); File output = new File(context.getOutputDirectory(), CONTRACTS_FOLDER + "/" + resolvedName + ".groovy"); output.getParentFile().mkdirs(); - try (Writer writer = new OutputStreamWriter(Files.newOutputStream(output.toPath()))) { + try (Writer writer = new OutputStreamWriter( + Files.newOutputStream(output.toPath()))) { writer.append(content); } } - private String replacePlaceholders(PropertyPlaceholderHelper.PlaceholderResolver resolver, String input) { + private String replacePlaceholders( + PropertyPlaceholderHelper.PlaceholderResolver resolver, String input) { return this.propertyPlaceholderHelper.replacePlaceholders(input, resolver); } + } class JsonPaths { + private final String jsonPath; JsonPaths(String jsonPath) { @@ -164,4 +175,5 @@ class JsonPaths { public String getJsonPath() { return this.jsonPath; } + } \ No newline at end of file diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/ContractExchangeHandler.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/ContractExchangeHandler.java index 669f8b66f2..6274cd5edb 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/ContractExchangeHandler.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/ContractExchangeHandler.java @@ -54,8 +54,8 @@ import wiremock.org.eclipse.jetty.server.handler.ContextHandler; * @author Dave Syer * */ -public class ContractExchangeHandler extends - WireMockVerifyHelper, ContractExchangeHandler> +public class ContractExchangeHandler + extends WireMockVerifyHelper, ContractExchangeHandler> implements Consumer> { @Override @@ -119,47 +119,56 @@ class WireMockHttpRequestAdapter implements Request { this.result = result; } - @Override public String getUrl() { + @Override + public String getUrl() { return this.result.getUrl().getRawPath(); } - @Override public String getAbsoluteUrl() { + @Override + public String getAbsoluteUrl() { return this.result.getUrl().toString(); } - @Override public RequestMethod getMethod() { + @Override + public RequestMethod getMethod() { return new RequestMethod(this.result.getMethod().name()); } - @Override public String getScheme() { + @Override + public String getScheme() { return this.result.getUrl().getScheme(); } - @Override public String getHost() { + @Override + public String getHost() { return this.result.getUrl().getHost(); } - @Override public int getPort() { + @Override + public int getPort() { return this.result.getUrl().getPort(); } - @Override public String getClientIp() { + @Override + public String getClientIp() { return "127.0.0.1"; } - @Override public String getHeader(String key) { + @Override + public String getHeader(String key) { HttpHeaders headers = this.result.getRequestHeaders(); return headers.containsKey(key) ? headers.getFirst(key) : null; } - @Override public HttpHeader header(String key) { + @Override + public HttpHeader header(String key) { HttpHeaders headers = this.result.getRequestHeaders(); - return headers.containsKey(key) ? - new HttpHeader(key, headers.getValuesAsList(key)) : - null; + return headers.containsKey(key) + ? new HttpHeader(key, headers.getValuesAsList(key)) : null; } - @Override public ContentTypeHeader contentTypeHeader() { + @Override + public ContentTypeHeader contentTypeHeader() { MediaType contentType = this.result.getRequestHeaders().getContentType(); if (contentType == null) { return null; @@ -167,7 +176,8 @@ class WireMockHttpRequestAdapter implements Request { return new ContentTypeHeader(contentType.toString()); } - @Override public com.github.tomakehurst.wiremock.http.HttpHeaders getHeaders() { + @Override + public com.github.tomakehurst.wiremock.http.HttpHeaders getHeaders() { com.github.tomakehurst.wiremock.http.HttpHeaders target = new com.github.tomakehurst.wiremock.http.HttpHeaders(); HttpHeaders headers = this.result.getRequestHeaders(); for (String key : headers.keySet()) { @@ -176,19 +186,23 @@ class WireMockHttpRequestAdapter implements Request { return target; } - @Override public boolean containsHeader(String key) { + @Override + public boolean containsHeader(String key) { return this.result.getRequestHeaders().containsKey(key); } - @Override public Set getAllHeaderKeys() { + @Override + public Set getAllHeaderKeys() { return this.result.getRequestHeaders().keySet(); } - @Override public Map getCookies() { + @Override + public Map getCookies() { return new LinkedHashMap<>(); } - @Override public QueryParameter queryParameter(String key) { + @Override + public QueryParameter queryParameter(String key) { String query = this.result.getUrl().getRawQuery(); if (query == null) { return null; @@ -212,24 +226,29 @@ class WireMockHttpRequestAdapter implements Request { return new QueryParameter(key, values); } - @Override public byte[] getBody() { + @Override + public byte[] getBody() { return this.result.getRequestBodyContent(); } - @Override public String getBodyAsString() { + @Override + public String getBodyAsString() { return new String(this.result.getRequestBodyContent(), Charset.forName("UTF-8")); } - @Override public String getBodyAsBase64() { + @Override + public String getBodyAsBase64() { return Base64.encodeBase64String(this.result.getRequestBodyContent()); } - @Override public boolean isMultipart() { + @Override + public boolean isMultipart() { return MediaType.MULTIPART_FORM_DATA .isCompatibleWith(this.result.getRequestHeaders().getContentType()); } - @Override public Collection getParts() { + @Override + public Collection getParts() { try { return getWireMockParts(); } @@ -257,15 +276,18 @@ class WireMockHttpRequestAdapter implements Request { private Part partFromServletPart(javax.servlet.http.Part part) { return new Part() { - @Override public String getName() { + @Override + public String getName() { return part.getName(); } - @Override public HttpHeader getHeader(String name) { + @Override + public HttpHeader getHeader(String name) { return new HttpHeader(name, part.getHeader(name)); } - @Override public com.github.tomakehurst.wiremock.http.HttpHeaders getHeaders() { + @Override + public com.github.tomakehurst.wiremock.http.HttpHeaders getHeaders() { com.github.tomakehurst.wiremock.http.HttpHeaders headers = new com.github.tomakehurst.wiremock.http.HttpHeaders(); for (String s : part.getHeaderNames()) { headers.plus(new HttpHeader(s, part.getHeader(s))); @@ -273,7 +295,8 @@ class WireMockHttpRequestAdapter implements Request { return headers; } - @Override public Body getBody() { + @Override + public Body getBody() { try { byte[] targetArray = new byte[part.getInputStream().available()]; return new Body(targetArray); @@ -286,17 +309,19 @@ class WireMockHttpRequestAdapter implements Request { } // TODO: Consider caching this - @Override public Part getPart(String name) { - return getWireMockParts().stream() - .filter(part -> name.equals(part.getName())) + @Override + public Part getPart(String name) { + return getWireMockParts().stream().filter(part -> name.equals(part.getName())) .findFirst().get(); } - @Override public boolean isBrowserProxyRequest() { + @Override + public boolean isBrowserProxyRequest() { return false; } - @Override public Optional getOriginalRequest() { + @Override + public Optional getOriginalRequest() { return Optional.absent(); } diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/ContractResultHandler.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/ContractResultHandler.java index 2c35665f58..1f5a21f379 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/ContractResultHandler.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/ContractResultHandler.java @@ -69,19 +69,19 @@ import static wiremock.com.google.common.collect.FluentIterable.from; import static wiremock.com.google.common.collect.Lists.newArrayList; import static wiremock.com.google.common.io.ByteStreams.toByteArray; -public class ContractResultHandler - extends WireMockVerifyHelper - implements ResultHandler { +public class ContractResultHandler extends + WireMockVerifyHelper implements ResultHandler { static final String ATTRIBUTE_NAME_CONFIGURATION = "org.springframework.restdocs.configuration"; - @Override public void handle(MvcResult result) throws Exception { + @Override + public void handle(MvcResult result) throws Exception { configure(result); MockMvcRestDocumentation.document(getName()).handle(result); } - @Override protected ResponseDefinitionBuilder getResponseDefinition( - MvcResult result) { + @Override + protected ResponseDefinitionBuilder getResponseDefinition(MvcResult result) { MockHttpServletResponse response = result.getResponse(); ResponseDefinitionBuilder definition; try { @@ -103,9 +103,11 @@ public class ContractResultHandler } } - @Override protected Map getConfiguration(MvcResult result) { - @SuppressWarnings("unchecked") Map map = (Map) result - .getRequest().getAttribute(ATTRIBUTE_NAME_CONFIGURATION); + @Override + protected Map getConfiguration(MvcResult result) { + @SuppressWarnings("unchecked") + Map map = (Map) result.getRequest() + .getAttribute(ATTRIBUTE_NAME_CONFIGURATION); if (map == null) { map = new HashMap<>(); result.getRequest().setAttribute(ATTRIBUTE_NAME_CONFIGURATION, map); @@ -113,15 +115,18 @@ public class ContractResultHandler return map; } - @Override protected Request getWireMockRequest(MvcResult result) { + @Override + protected Request getWireMockRequest(MvcResult result) { return new WireMockHttpServletRequestAdapter(result.getRequest()); } - @Override protected MediaType getContentType(MvcResult result) { + @Override + protected MediaType getContentType(MvcResult result) { return MediaType.valueOf(result.getRequest().getContentType()); } - @Override protected byte[] getRequestBodyContent(MvcResult result) { + @Override + protected byte[] getRequestBodyContent(MvcResult result) { return new WireMockHttpServletRequestAdapter(result.getRequest()).getBody(); } @@ -133,14 +138,17 @@ class WireMockHttpServletRequestAdapter implements Request { private static final String ORIGINAL_REQUEST_KEY = "wiremock.ORIGINAL_REQUEST"; private final HttpServletRequest request; + private byte[] cachedBody; + private Collection cachedMultiparts; WireMockHttpServletRequestAdapter(HttpServletRequest request) { this.request = request; } - @Override public String getUrl() { + @Override + public String getUrl() { String url = this.request.getRequestURI(); String contextPath = this.request.getContextPath(); if (!isNullOrEmpty(contextPath) && url.startsWith(contextPath)) { @@ -149,33 +157,38 @@ class WireMockHttpServletRequestAdapter implements Request { return withQueryStringIfPresent(url); } - @Override public String getAbsoluteUrl() { + @Override + public String getAbsoluteUrl() { return withQueryStringIfPresent(this.request.getRequestURL().toString()); } private String withQueryStringIfPresent(String url) { - return url + (isNullOrEmpty(this.request.getQueryString()) ? - "" : - "?" + this.request.getQueryString()); + return url + (isNullOrEmpty(this.request.getQueryString()) ? "" + : "?" + this.request.getQueryString()); } - @Override public RequestMethod getMethod() { + @Override + public RequestMethod getMethod() { return RequestMethod.fromString(this.request.getMethod().toUpperCase()); } - @Override public String getScheme() { + @Override + public String getScheme() { return this.request.getScheme(); } - @Override public String getHost() { + @Override + public String getHost() { return this.request.getServerName(); } - @Override public int getPort() { + @Override + public int getPort() { return this.request.getServerPort(); } - @Override public String getClientIp() { + @Override + public String getClientIp() { String forwardedForHeader = this.getHeader("X-Forwarded-For"); if (forwardedForHeader != null && forwardedForHeader.length() > 0) { @@ -186,11 +199,13 @@ class WireMockHttpServletRequestAdapter implements Request { } // Something's wrong with reading the body from request - @Override public byte[] getBody() { + @Override + public byte[] getBody() { if (this.cachedBody == null || this.cachedBody.length == 0) { try { if (this.request instanceof MockHttpServletRequest) { - this.cachedBody = ((MockHttpServletRequest) this.request).getContentAsByteArray(); + this.cachedBody = ((MockHttpServletRequest) this.request) + .getContentAsByteArray(); return this.cachedBody; } byte[] body = toByteArray(this.request.getInputStream()); @@ -217,15 +232,19 @@ class WireMockHttpServletRequestAdapter implements Request { return encodingHeader != null && encodingHeader.contains("gzip"); } - @Override public String getBodyAsString() { + @Override + public String getBodyAsString() { return stringFromBytes(getBody(), encodingFromContentTypeHeaderOrUtf8()); } - @Override public String getBodyAsBase64() { + @Override + public String getBodyAsBase64() { return encodeBase64(getBody()); } - @SuppressWarnings("unchecked") @Override public String getHeader(String key) { + @SuppressWarnings("unchecked") + @Override + public String getHeader(String key) { List headerNames = list(this.request.getHeaderNames()); for (String currentKey : headerNames) { if (currentKey.toLowerCase().equals(key.toLowerCase())) { @@ -235,7 +254,9 @@ class WireMockHttpServletRequestAdapter implements Request { return null; } - @Override @SuppressWarnings("unchecked") public HttpHeader header(String key) { + @Override + @SuppressWarnings("unchecked") + public HttpHeader header(String key) { List headerNames = list(this.request.getHeaderNames()); for (String currentKey : headerNames) { if (currentKey.toLowerCase().equals(key.toLowerCase())) { @@ -250,15 +271,18 @@ class WireMockHttpServletRequestAdapter implements Request { return HttpHeader.absent(key); } - @Override public ContentTypeHeader contentTypeHeader() { + @Override + public ContentTypeHeader contentTypeHeader() { return getHeaders().getContentTypeHeader(); } - @Override public boolean containsHeader(String key) { + @Override + public boolean containsHeader(String key) { return header(key).isPresent(); } - @Override public HttpHeaders getHeaders() { + @Override + public HttpHeaders getHeaders() { List headerList = newArrayList(); for (String key : getAllHeaderKeys()) { headerList.add(header(key)); @@ -267,17 +291,20 @@ class WireMockHttpServletRequestAdapter implements Request { return new HttpHeaders(headerList); } - @SuppressWarnings("unchecked") @Override public Set getAllHeaderKeys() { + @SuppressWarnings("unchecked") + @Override + public Set getAllHeaderKeys() { LinkedHashSet headerKeys = new LinkedHashSet<>(); for (Enumeration headerNames = this.request.getHeaderNames(); headerNames - .hasMoreElements(); ) { + .hasMoreElements();) { headerKeys.add(headerNames.nextElement()); } return headerKeys; } - @Override public Map getCookies() { + @Override + public Map getCookies() { ImmutableMultimap.Builder builder = ImmutableMultimap.builder(); javax.servlet.http.Cookie[] cookies = firstNonNull(this.request.getCookies(), new javax.servlet.http.Cookie[0]); @@ -288,19 +315,23 @@ class WireMockHttpServletRequestAdapter implements Request { input -> new Cookie(null, ImmutableList.copyOf(input))); } - @Override public QueryParameter queryParameter(String key) { + @Override + public QueryParameter queryParameter(String key) { return firstNonNull((splitQuery(this.request.getQueryString()).get(key)), QueryParameter.absent(key)); } - @Override public boolean isBrowserProxyRequest() { + @Override + public boolean isBrowserProxyRequest() { if (!isJetty()) { return false; } return false; } - @Override @SuppressWarnings("unchecked") public Collection getParts() { + @Override + @SuppressWarnings("unchecked") + public Collection getParts() { if (!isMultipart()) { return null; } @@ -311,9 +342,9 @@ class WireMockHttpServletRequestAdapter implements Request { InputStream inputStream = new ByteArrayInputStream(getBody()); MultiPartInputStreamParser inputStreamParser = new MultiPartInputStreamParser( inputStream, contentTypeHeaderValue, null, null); - this.cachedMultiparts = from(safelyGetRequestParts()) - .transform( - (Function) WireMockHttpServletMultipartAdapter::from).toList(); + this.cachedMultiparts = from(safelyGetRequestParts()).transform( + (Function) WireMockHttpServletMultipartAdapter::from) + .toList(); } catch (IOException | ServletException exception) { return throwUnchecked(exception, Collection.class); @@ -336,12 +367,14 @@ class WireMockHttpServletRequestAdapter implements Request { } } - @Override public boolean isMultipart() { + @Override + public boolean isMultipart() { String header = getHeader("Content-Type"); return (header != null && header.contains("multipart")); } - @Override public Part getPart(final String name) { + @Override + public Part getPart(final String name) { if (name == null || name.length() == 0) { return null; } @@ -350,12 +383,14 @@ class WireMockHttpServletRequestAdapter implements Request { return null; } } - return from(this.cachedMultiparts).firstMatch( - input -> name.equals(input.getName())).get(); + return from(this.cachedMultiparts) + .firstMatch(input -> name.equals(input.getName())).get(); } - @Override public Optional getOriginalRequest() { - Request originalRequest = (Request) this.request.getAttribute(ORIGINAL_REQUEST_KEY); + @Override + public Optional getOriginalRequest() { + Request originalRequest = (Request) this.request + .getAttribute(ORIGINAL_REQUEST_KEY); return Optional.fromNullable(originalRequest); } @@ -371,14 +406,16 @@ class WireMockHttpServletRequestAdapter implements Request { private void getClass(String type) throws ClassNotFoundException { ClassLoader contextCL = Thread.currentThread().getContextClassLoader(); - ClassLoader loader = contextCL == null ? - com.github.tomakehurst.wiremock.servlet.WireMockHttpServletRequestAdapter.class - .getClassLoader() : - contextCL; + ClassLoader loader = contextCL == null + ? com.github.tomakehurst.wiremock.servlet.WireMockHttpServletRequestAdapter.class + .getClassLoader() + : contextCL; Class.forName(type, false, loader); } - @Override public String toString() { + @Override + public String toString() { return this.request.toString() + getBodyAsString(); } + } diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/JsonPathValue.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/JsonPathValue.java index 8bab373c5f..4bd8f2f29a 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/JsonPathValue.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/JsonPathValue.java @@ -23,7 +23,9 @@ import org.springframework.util.StringUtils; class JsonPathValue { private final JsonPath jsonPath; + private final String expression; + private final CharSequence actual; JsonPathValue(JsonPath jsonPath, CharSequence actual) { diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/SpringCloudContractRestDocs.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/SpringCloudContractRestDocs.java index d638e6d74f..df675e6a46 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/SpringCloudContractRestDocs.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/SpringCloudContractRestDocs.java @@ -21,8 +21,9 @@ import java.util.Map; import org.springframework.restdocs.snippet.Snippet; /** - * Convenience class for setting up RestDocs to generate a {@link org.springframework.restdocs.snippet.Snippet} - * with Spring Cloud Contract DSL. Example usage: + * Convenience class for setting up RestDocs to generate a + * {@link org.springframework.restdocs.snippet.Snippet} with Spring Cloud Contract DSL. + * Example usage: * *

        * @RunWith(SpringRunner.class)
      @@ -52,10 +53,10 @@ import org.springframework.restdocs.snippet.Snippet;
        *     .andDo(document("index", SpringCloudContractRestDocs.dslContract()));
        * 	}
        * 
      - * - * which creates a file "target/snippets/contracts/index.groovy" and a - * standard documentation entitled `dsl-contract.adoc` containing that contract. - * + * + * which creates a file "target/snippets/contracts/index.groovy" and a standard + * documentation entitled `dsl-contract.adoc` containing that contract. + * * @author Marcin Grzejszczak * @since 1.0.4 */ @@ -66,9 +67,8 @@ public class SpringCloudContractRestDocs { } /** - * Returns a new {@code Snippet} that will document Spring Cloud Contract DSL for the API - * operation. - * + * Returns a new {@code Snippet} that will document Spring Cloud Contract DSL for the + * API operation. * @return the snippet that will document the Spring Cloud Contract DSL */ public static Snippet dslContract() { @@ -76,10 +76,9 @@ public class SpringCloudContractRestDocs { } /** - * Returns a new {@code Snippet} that will document the Spring Cloud Contract DSL for the API - * operation. The given {@code attributes} will be available during snippet + * Returns a new {@code Snippet} that will document the Spring Cloud Contract DSL for + * the API operation. The given {@code attributes} will be available during snippet * generation. - * * @param attributes the attributes * @return the snippet that will document the Spring Cloud Contract DSL */ diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockRestAssuredConfiguration.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockRestAssuredConfiguration.java index 4e78eade35..a0befbecda 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockRestAssuredConfiguration.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockRestAssuredConfiguration.java @@ -8,17 +8,18 @@ import org.springframework.restdocs.restassured3.RestAssuredRestDocumentationCon /** * Custom configuration for Spring RestDocs that adds a WireMock snippet (for generating * JSON stubs). Applied automatically if you use - * {@link org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs @AutoConfigureRestDocs} in your test case and this class - * is available. JSON stubs are generated and added to the restdocs path under "stubs". + * {@link org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs @AutoConfigureRestDocs} + * in your test case and this class is available. JSON stubs are generated and added to + * the restdocs path under "stubs". * * @see WireMockRestDocs for a convenient entry point for customizing and asserting the * stub behaviour - * * @author Eddú Meléndez */ @Configuration @ConditionalOnClass(RestAssuredRestDocumentationConfigurer.class) -public class WireMockRestAssuredConfiguration implements RestDocsRestAssuredConfigurationCustomizer { +public class WireMockRestAssuredConfiguration + implements RestDocsRestAssuredConfigurationCustomizer { @Override public void customize(RestAssuredRestDocumentationConfigurer configurer) { diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockRestDocsConfiguration.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockRestDocsConfiguration.java index df5fc11bac..95d94dec4e 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockRestDocsConfiguration.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockRestDocsConfiguration.java @@ -24,12 +24,12 @@ import org.springframework.restdocs.mockmvc.MockMvcRestDocumentationConfigurer; /** * Custom configuration for Spring RestDocs that adds a WireMock snippet (for generating * JSON stubs). Applied automatically if you use - * {@link org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs @AutoConfigureRestDocs} in your test case and this class - * is available. JSON stubs are generated and added to the restdocs path under "stubs". - * + * {@link org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs @AutoConfigureRestDocs} + * in your test case and this class is available. JSON stubs are generated and added to + * the restdocs path under "stubs". + * * @see WireMockRestDocs for a convenient entry point for customizing and asserting the * stub behaviour - * * @author Dave Syer * */ diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockSnippet.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockSnippet.java index 94ef5e72d8..4903ce73cc 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockSnippet.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockSnippet.java @@ -73,6 +73,7 @@ public class WireMockSnippet implements Snippet { private StubMapping stubMapping; private boolean hasJsonBodyRequestToMatch = false; + private boolean hasXmlBodyRequestToMatch = false; private static final TemplateFormat TEMPLATE_FORMAT = new TemplateFormat() { @@ -133,9 +134,8 @@ public class WireMockSnippet implements Snippet { } private boolean hasContentType(Operation operation, MediaType mediaType) { - return operation.getRequest().getHeaders().getContentType() != null - && (operation.getRequest().getHeaders().getContentType() - .isCompatibleWith(mediaType)); + return operation.getRequest().getHeaders().getContentType() != null && (operation + .getRequest().getHeaders().getContentType().isCompatibleWith(mediaType)); } private ResponseDefinitionBuilder response(Operation operation) { @@ -145,9 +145,8 @@ public class WireMockSnippet implements Snippet { } private MappingBuilder request(Operation operation) { - return queryParams( - requestHeaders(requestBuilder(operation), operation) - , operation); + return queryParams(requestHeaders(requestBuilder(operation), operation), + operation); } private MappingBuilder queryParams(MappingBuilder request, Operation operation) { @@ -157,7 +156,8 @@ public class WireMockSnippet implements Snippet { } for (String queryPair : rawQuery.split("&")) { String[] splitQueryPair = queryPair.split("="); - request = request.withQueryParam(splitQueryPair[0], WireMock.equalTo(splitQueryPair[1])); + request = request.withQueryParam(splitQueryPair[0], + WireMock.equalTo(splitQueryPair[1])); } return request; } diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockVerifyHelper.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockVerifyHelper.java index 1e39534f70..6561c3ef9b 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockVerifyHelper.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockVerifyHelper.java @@ -37,7 +37,9 @@ import static org.assertj.core.api.Assertions.assertThat; public abstract class WireMockVerifyHelper> { private Map jsonPaths = new LinkedHashMap<>(); + private MediaType contentType; + private String name; private MappingBuilder builder; diff --git a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockWebTestClientConfiguration.java b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockWebTestClientConfiguration.java index 685e9a9b7a..f8a19bb454 100644 --- a/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockWebTestClientConfiguration.java +++ b/spring-cloud-contract-wiremock/src/main/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockWebTestClientConfiguration.java @@ -27,10 +27,9 @@ import org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation * {@link org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs @AutoConfigureRestDocs} * in your test case and this class is available. JSON stubs are generated and added to * the restdocs path under "stubs". - * + * * @see WireMockRestDocs for a convenient entry point for customizing and asserting the * stub behaviour - * * @author Dave Syer * */ diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockApplicationTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockApplicationTests.java index 762f7f43f7..4031eaeccc 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockApplicationTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockApplicationTests.java @@ -16,7 +16,7 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) -@SpringBootTest(classes=WiremockTestsApplication.class, properties="app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment=WebEnvironment.NONE) +@SpringBootTest(classes = WiremockTestsApplication.class, properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE) @AutoConfigureWireMock(port = 12345) public class AutoConfigureWireMockApplicationTests { @@ -25,8 +25,8 @@ public class AutoConfigureWireMockApplicationTests { @Test public void contextLoads() throws Exception { - stubFor(get(urlEqualTo("/test")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + stubFor(get(urlEqualTo("/test")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); assertThat(this.service.go()).isEqualTo("Hello World!"); } diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockAutoStubsApplicationTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockAutoStubsApplicationTests.java index 879c93a7b5..cedf5aaaa8 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockAutoStubsApplicationTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockAutoStubsApplicationTests.java @@ -10,8 +10,8 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@SpringBootTest(classes=WiremockTestsApplication.class, properties="app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment=WebEnvironment.NONE) -@AutoConfigureWireMock(port=0) +@SpringBootTest(classes = WiremockTestsApplication.class, properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE) +@AutoConfigureWireMock(port = 0) // Default stubs work at classpath:/mappings public class AutoConfigureWireMockAutoStubsApplicationTests { diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java index 5cb2e2b58e..194541f5fa 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java @@ -13,15 +13,14 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes={WiremockTestsApplication.class, - AutoConfigureWireMockConfigurationCustomizerTests.Config.class}, - properties="app.baseUrl=http://localhost:${wiremock.server.port}", - webEnvironment=WebEnvironment.NONE) -@AutoConfigureWireMock(port=0, stubs="file:src/test/resources/io.stubs/mappings") +@SpringBootTest(classes = { WiremockTestsApplication.class, + AutoConfigureWireMockConfigurationCustomizerTests.Config.class }, properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE) +@AutoConfigureWireMock(port = 0, stubs = "file:src/test/resources/io.stubs/mappings") public class AutoConfigureWireMockConfigurationCustomizerTests { @Autowired private Service service; + @Autowired private Config config; @@ -37,9 +36,11 @@ public class AutoConfigureWireMockConfigurationCustomizerTests { boolean executed = false; // tag::customizer_1[] - @Bean WireMockConfigurationCustomizer optionsCustomizer() { + @Bean + WireMockConfigurationCustomizer optionsCustomizer() { return new WireMockConfigurationCustomizer() { - @Override public void customize(WireMockConfiguration options) { + @Override + public void customize(WireMockConfiguration options) { // end::customizer_1[] assertThat(options.portNumber()).isGreaterThan(0); Config.this.executed = true; @@ -52,5 +53,7 @@ public class AutoConfigureWireMockConfigurationCustomizerTests { public boolean isExecuted() { return executed; } + } + } diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationTests.java index 8f5f4a07a9..0c43f82dbb 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationTests.java @@ -10,8 +10,8 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@SpringBootTest(classes=WiremockTestsApplication.class, properties="app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment=WebEnvironment.NONE) -@AutoConfigureWireMock(port=0, files="classpath:/root/") +@SpringBootTest(classes = WiremockTestsApplication.class, properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE) +@AutoConfigureWireMock(port = 0, files = "classpath:/root/") public class AutoConfigureWireMockFilesApplicationTests { @Autowired diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationWithoutSlashTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationWithoutSlashTests.java index 78e4edb01e..69bfd3a969 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationWithoutSlashTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationWithoutSlashTests.java @@ -10,8 +10,8 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes=WiremockTestsApplication.class, properties="app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment=WebEnvironment.NONE) -@AutoConfigureWireMock(port=0, files="classpath:root") +@SpringBootTest(classes = WiremockTestsApplication.class, properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE) +@AutoConfigureWireMock(port = 0, files = "classpath:root") public class AutoConfigureWireMockFilesApplicationWithoutSlashTests { @Autowired diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockHttpsPortApplicationTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockHttpsPortApplicationTests.java index eecc74ec66..4c140e9bdd 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockHttpsPortApplicationTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockHttpsPortApplicationTests.java @@ -15,7 +15,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = WiremockTestsApplication.class, properties = "app.baseUrl=https://localhost:${wiremock.server.https-port}", webEnvironment = WebEnvironment.NONE) -@AutoConfigureWireMock(httpsPort = 9999, port=0) +@AutoConfigureWireMock(httpsPort = 9999, port = 0) public class AutoConfigureWireMockHttpsPortApplicationTests { @Autowired diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockRandomPortApplicationTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockRandomPortApplicationTests.java index dd45cc315f..f2dba629a0 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockRandomPortApplicationTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockRandomPortApplicationTests.java @@ -14,8 +14,8 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes=WiremockTestsApplication.class, properties="app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment=WebEnvironment.NONE) -@AutoConfigureWireMock(port=0) +@SpringBootTest(classes = WiremockTestsApplication.class, properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE) +@AutoConfigureWireMock(port = 0) public class AutoConfigureWireMockRandomPortApplicationTests { @Autowired @@ -23,8 +23,8 @@ public class AutoConfigureWireMockRandomPortApplicationTests { @Test public void contextLoads() throws Exception { - stubFor(get(urlEqualTo("/test")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + stubFor(get(urlEqualTo("/test")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); assertThat(this.service.go()).isEqualTo("Hello World!"); } diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockRandomPortHttpsApplicationTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockRandomPortHttpsApplicationTests.java index e4dc0bae8e..29b505dcdd 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockRandomPortHttpsApplicationTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockRandomPortHttpsApplicationTests.java @@ -14,8 +14,8 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@SpringBootTest(classes=WiremockTestsApplication.class, properties="app.baseUrl=https://localhost:${wiremock.server.https-port}", webEnvironment=WebEnvironment.NONE) -@AutoConfigureWireMock(port=0, httpsPort=0) +@SpringBootTest(classes = WiremockTestsApplication.class, properties = "app.baseUrl=https://localhost:${wiremock.server.https-port}", webEnvironment = WebEnvironment.NONE) +@AutoConfigureWireMock(port = 0, httpsPort = 0) public class AutoConfigureWireMockRandomPortHttpsApplicationTests { @Autowired @@ -23,8 +23,8 @@ public class AutoConfigureWireMockRandomPortHttpsApplicationTests { @Test public void contextLoads() throws Exception { - stubFor(get(urlEqualTo("/test")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + stubFor(get(urlEqualTo("/test")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); assertThat(this.service.go()).isEqualTo("Hello World!"); } diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockStubsAndFilesApplicationTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockStubsAndFilesApplicationTests.java index 01ac819f7b..7d69fb4d92 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockStubsAndFilesApplicationTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockStubsAndFilesApplicationTests.java @@ -10,8 +10,8 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@SpringBootTest(classes=WiremockTestsApplication.class, properties="app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment=WebEnvironment.NONE) -@AutoConfigureWireMock(port=0, files="classpath:/root/", stubs="file:src/test/resources/io.stubs/mappings") +@SpringBootTest(classes = WiremockTestsApplication.class, properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE) +@AutoConfigureWireMock(port = 0, files = "classpath:/root/", stubs = "file:src/test/resources/io.stubs/mappings") public class AutoConfigureWireMockStubsAndFilesApplicationTests { @Autowired diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockStubsAndMultipleFilesApplicationTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockStubsAndMultipleFilesApplicationTests.java index 022347237e..a64101d463 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockStubsAndMultipleFilesApplicationTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockStubsAndMultipleFilesApplicationTests.java @@ -10,8 +10,9 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@SpringBootTest(classes=WiremockTestsApplication.class, properties="app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment=WebEnvironment.NONE) -@AutoConfigureWireMock(port=0, files={"classpath:/", "classpath:/root/", "classpath:/nonexistent/"}, stubs="file:src/test/resources/io.stubs/mappings") +@SpringBootTest(classes = WiremockTestsApplication.class, properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE) +@AutoConfigureWireMock(port = 0, files = { "classpath:/", "classpath:/root/", + "classpath:/nonexistent/" }, stubs = "file:src/test/resources/io.stubs/mappings") public class AutoConfigureWireMockStubsAndMultipleFilesApplicationTests { @Autowired diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockStubsApplicationTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockStubsApplicationTests.java index f522cdd078..ce6f2cee25 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockStubsApplicationTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockStubsApplicationTests.java @@ -10,8 +10,8 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@SpringBootTest(classes=WiremockTestsApplication.class, properties="app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment=WebEnvironment.NONE) -@AutoConfigureWireMock(port=0, stubs="file:src/test/resources/io.stubs/mappings") +@SpringBootTest(classes = WiremockTestsApplication.class, properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE) +@AutoConfigureWireMock(port = 0, stubs = "file:src/test/resources/io.stubs/mappings") public class AutoConfigureWireMockStubsApplicationTests { @Autowired diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockStubsApplicationWithSlashTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockStubsApplicationWithSlashTests.java index 07034419a5..b09ef4a367 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockStubsApplicationWithSlashTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockStubsApplicationWithSlashTests.java @@ -10,8 +10,8 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes=WiremockTestsApplication.class, properties="app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment=WebEnvironment.NONE) -@AutoConfigureWireMock(port=0, stubs="file:src/test/resources/io.stubs/mappings/") +@SpringBootTest(classes = WiremockTestsApplication.class, properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE) +@AutoConfigureWireMock(port = 0, stubs = "file:src/test/resources/io.stubs/mappings/") public class AutoConfigureWireMockStubsApplicationWithSlashTests { @Autowired diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WireMockStubMappingTest.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WireMockStubMappingTest.java index 03f9cb4b1b..1d0019535e 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WireMockStubMappingTest.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WireMockStubMappingTest.java @@ -7,7 +7,9 @@ import org.junit.Test; * @author Marcin Grzejszczak */ public class WireMockStubMappingTest { + private static final String stub_2_1_7 = "{\"request\" : { \"method\" : \"GET\" }, \"response\" : { \"status\" : 200 }}"; + private static final String stub_2_5_1 = "{\"id\" : \"77514bd4-a102-4478-a3c0-0fda8b905591\", \"request\" : { \"method\" : \"GET\" }, \"response\" : { \"status\" : 200 }, \"uuid\" : \"77514bd4-a102-4478-a3c0-0fda8b905591\"}"; @Test @@ -21,4 +23,5 @@ public class WireMockStubMappingTest { // when: WireMockStubMapping.buildFrom(stub_2_5_1); } + } \ No newline at end of file diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockHttpsServerApplicationTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockHttpsServerApplicationTests.java index 74077d8527..a8357c696a 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockHttpsServerApplicationTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockHttpsServerApplicationTests.java @@ -16,22 +16,20 @@ import org.springframework.test.context.junit4.SpringRunner; import com.github.tomakehurst.wiremock.junit.WireMockClassRule; @RunWith(SpringRunner.class) -@SpringBootTest(classes=WiremockTestsApplication.class, properties="app.baseUrl=https://localhost:8443") +@SpringBootTest(classes = WiremockTestsApplication.class, properties = "app.baseUrl=https://localhost:8443") public class WiremockHttpsServerApplicationTests { @ClassRule public static WireMockClassRule wiremock = new WireMockClassRule( - WireMockSpring.options() - .port(5433) - .httpsPort(8443)); + WireMockSpring.options().port(5433).httpsPort(8443)); @Autowired private Service service; @Test public void contextLoads() throws Exception { - stubFor(get(urlEqualTo("/test")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + stubFor(get(urlEqualTo("/test")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); assertThat(this.service.go()).isEqualTo("Hello World!"); } diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockMockServerApplicationTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockMockServerApplicationTests.java index 8f57a61452..72487d3728 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockMockServerApplicationTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockMockServerApplicationTests.java @@ -34,19 +34,20 @@ public class WiremockMockServerApplicationTests { public void simplePutShouldFail() throws Exception { MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) // .baseUrl("http://example.org") // - .stubs("classpath:/mappings/resource.json") - .build(); - RequestEntity postRequest = RequestEntity.post(URI.create("http://example.org/resource")) - .accept(MediaType.TEXT_PLAIN) - .build(); + .stubs("classpath:/mappings/resource.json").build(); + RequestEntity postRequest = RequestEntity + .post(URI.create("http://example.org/resource")) + .accept(MediaType.TEXT_PLAIN).build(); ResponseEntity response; try { response = this.restTemplate.exchange(postRequest, String.class); - } catch (AssertionError e) { + } + catch (AssertionError e) { response = null; } if (null != response) { - fail("There was a response for POST request: " + postRequest + "\n\tresponse: " + response); + fail("There was a response for POST request: " + postRequest + + "\n\tresponse: " + response); } } @@ -171,11 +172,14 @@ public class WiremockMockServerApplicationTests { .stubs("classpath:/mappings/header-matches.json", "classpath:/mappings/header-matches-precise.json") .build(); - assertThat(this.restTemplate - .exchange(RequestEntity.post(new URI("http://example.org/poster")) - .accept(MediaType.valueOf("application/v.bar")) - .header("X-Precise", "true").build(), String.class) - .getBody()).isEqualTo("Precise World"); + assertThat( + this.restTemplate + .exchange( + RequestEntity.post(new URI("http://example.org/poster")) + .accept(MediaType.valueOf("application/v.bar")) + .header("X-Precise", "true").build(), + String.class) + .getBody()).isEqualTo("Precise World"); } @Test @@ -185,11 +189,14 @@ public class WiremockMockServerApplicationTests { .stubs("classpath:/mappings/header-matches.json", "classpath:/mappings/header-matches-precise.json") .ignoreExpectOrder(false).build(); - assertThat(this.restTemplate - .exchange(RequestEntity.post(new URI("http://example.org/poster")) - .accept(MediaType.valueOf("application/v.bar")) - .header("X-Precise", "true").build(), String.class) - .getBody()).isEqualTo("Bar World"); + assertThat( + this.restTemplate + .exchange( + RequestEntity.post(new URI("http://example.org/poster")) + .accept(MediaType.valueOf("application/v.bar")) + .header("X-Precise", "true").build(), + String.class) + .getBody()).isEqualTo("Bar World"); // The first one matches, not the most precise! } @@ -198,7 +205,8 @@ public class WiremockMockServerApplicationTests { WireMockRestServiceServer.with(this.restTemplate) // .baseUrl("http://example.org") // .stubs("classpath:/mappings/resource-with-low-priority.json", - "classpath:/mappings/resource-with-high-priority.json").build(); + "classpath:/mappings/resource-with-high-priority.json") + .build(); assertThat(this.restTemplate.getForObject("http://example.org/resource", String.class)).isEqualTo("Hello High"); } @@ -229,8 +237,8 @@ public class WiremockMockServerApplicationTests { .stubs("classpath:/mappings/body-matches-jsonpath.json").build(); assertThat(this.restTemplate.postForObject("http://example.org/body", - new Things(Collections.singletonList(new Thing("RequiredThing"))), String.class)) - .isEqualTo("Hello Body"); + new Things(Collections.singletonList(new Thing("RequiredThing"))), + String.class)).isEqualTo("Hello Body"); } @Test @@ -242,12 +250,15 @@ public class WiremockMockServerApplicationTests { String response; try { response = this.restTemplate.postForObject("http://example.org/body", - new Things(Collections.singletonList(new Thing("AbsentThing"))), String.class); - } catch (AssertionError e) { + new Things(Collections.singletonList(new Thing("AbsentThing"))), + String.class); + } + catch (AssertionError e) { response = null; } if (null != response) { - fail("There was a response for a request that shouldn't be matched : " + response); + fail("There was a response for a request that shouldn't be matched : " + + response); } } @@ -257,10 +268,10 @@ public class WiremockMockServerApplicationTests { .baseUrl("http://example.org") // .stubs("classpath:/mappings/body-matches-xpath.json").build(); - assertThat(this.restTemplate.exchange( - RequestEntity.post(URI.create("http://example.org/body")) - .contentType(MediaType.APPLICATION_XML) - .body("RequiredThing"), + assertThat(this.restTemplate.exchange(RequestEntity + .post(URI.create("http://example.org/body")) + .contentType(MediaType.APPLICATION_XML) + .body("RequiredThing"), String.class).getBody()).isEqualTo("Hello Body"); } @@ -274,14 +285,15 @@ public class WiremockMockServerApplicationTests { try { response = this.restTemplate.exchange( RequestEntity.post(URI.create("http://example.org/body")) - .contentType(MediaType.APPLICATION_XML) - .body(""), + .contentType(MediaType.APPLICATION_XML).body(""), String.class); - } catch (AssertionError e) { + } + catch (AssertionError e) { response = null; } if (null != response) { - fail("There was a response for a request that shouldn't be matched : " + response); + fail("There was a response for a request that shouldn't be matched : " + + response); } } @@ -292,8 +304,8 @@ public class WiremockMockServerApplicationTests { .stubs("classpath:/mappings/body-matches-equaltojson.json").build(); assertThat(this.restTemplate.postForObject("http://example.org/body", - new Things(Collections.singletonList(new Thing("RequiredThing"))), String.class)) - .isEqualTo("Hello Body"); + new Things(Collections.singletonList(new Thing("RequiredThing"))), + String.class)).isEqualTo("Hello Body"); } @Test @@ -305,12 +317,15 @@ public class WiremockMockServerApplicationTests { String response; try { response = this.restTemplate.postForObject("http://example.org/body", - new Things(Collections.singletonList(new Thing("AbsentThing"))), String.class); - } catch (AssertionError e) { + new Things(Collections.singletonList(new Thing("AbsentThing"))), + String.class); + } + catch (AssertionError e) { response = null; } if (null != response) { - fail("There was a response for a request that shouldn't be matched : " + response); + fail("There was a response for a request that shouldn't be matched : " + + response); } } @@ -320,10 +335,10 @@ public class WiremockMockServerApplicationTests { .baseUrl("http://example.org") // .stubs("classpath:/mappings/body-matches-equaltoxml.json").build(); - assertThat(this.restTemplate.exchange( - RequestEntity.post(URI.create("http://example.org/body")) - .contentType(MediaType.APPLICATION_XML) - .body("RequiredThing"), + assertThat(this.restTemplate.exchange(RequestEntity + .post(URI.create("http://example.org/body")) + .contentType(MediaType.APPLICATION_XML) + .body("RequiredThing"), String.class).getBody()).isEqualTo("Hello Body"); } @@ -335,16 +350,18 @@ public class WiremockMockServerApplicationTests { ResponseEntity response; try { - response = this.restTemplate.exchange( - RequestEntity.post(URI.create("http://example.org/body")) - .contentType(MediaType.APPLICATION_XML) - .body("AbsentThing"), + response = this.restTemplate.exchange(RequestEntity + .post(URI.create("http://example.org/body")) + .contentType(MediaType.APPLICATION_XML) + .body("AbsentThing"), String.class); - } catch (AssertionError e) { + } + catch (AssertionError e) { response = null; } if (null != response) { - fail("There was a response for a request that shouldn't be matched : " + response); + fail("There was a response for a request that shouldn't be matched : " + + response); } } @@ -354,10 +371,10 @@ public class WiremockMockServerApplicationTests { .baseUrl("http://example.org") // .stubs("classpath:/mappings/body-matches-regex.json").build(); - assertThat(this.restTemplate.exchange( - RequestEntity.post(URI.create("http://example.org/body")) - .contentType(MediaType.APPLICATION_XML) - .body("RequiredThing"), + assertThat(this.restTemplate.exchange(RequestEntity + .post(URI.create("http://example.org/body")) + .contentType(MediaType.APPLICATION_XML) + .body("RequiredThing"), String.class).getBody()).isEqualTo("Hello Body"); } @@ -369,35 +386,41 @@ public class WiremockMockServerApplicationTests { ResponseEntity response; try { - response = this.restTemplate.exchange( - RequestEntity.post(URI.create("http://example.org/body")) - .contentType(MediaType.APPLICATION_XML) - .body("AbsentThing"), + response = this.restTemplate.exchange(RequestEntity + .post(URI.create("http://example.org/body")) + .contentType(MediaType.APPLICATION_XML) + .body("AbsentThing"), String.class); - } catch (AssertionError e) { + } + catch (AssertionError e) { response = null; } if (null != response) { - fail("There was a response for a request that shouldn't be matched : " + response); + fail("There was a response for a request that shouldn't be matched : " + + response); } } public static class Things { + public List things; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public Things(List things) { this.things = things; } + } public static class Thing { + public String name; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public Thing(String name) { this.name = name; } + } } diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockServerApplicationTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockServerApplicationTests.java index 7caa048411..ddb4ff1ca1 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockServerApplicationTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockServerApplicationTests.java @@ -18,19 +18,20 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes=WiremockTestsApplication.class, properties="app.baseUrl=http://localhost:5435", webEnvironment=WebEnvironment.NONE) +@SpringBootTest(classes = WiremockTestsApplication.class, properties = "app.baseUrl=http://localhost:5435", webEnvironment = WebEnvironment.NONE) public class WiremockServerApplicationTests { @ClassRule - public static WireMockClassRule wiremock = new WireMockClassRule(WireMockSpring.options().port(5435)); + public static WireMockClassRule wiremock = new WireMockClassRule( + WireMockSpring.options().port(5435)); @Autowired private Service service; @Test public void hello() throws Exception { - stubFor(get(urlEqualTo("/test")) - .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + stubFor(get(urlEqualTo("/test")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); assertThat(this.service.go()).isEqualTo("Hello World!"); } diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockServerRestAssuredApplicationTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockServerRestAssuredApplicationTests.java index 39cfb8901d..536217fff0 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockServerRestAssuredApplicationTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockServerRestAssuredApplicationTests.java @@ -39,25 +39,14 @@ public class WiremockServerRestAssuredApplicationTests { @Test public void contextLoads() throws Exception { - given() - .port(this.port) - .when() - .get("/resource") - .then() - .assertThat() - .statusCode(is(200)) - .content(equalTo("Hello World")); + given().port(this.port).when().get("/resource").then().assertThat() + .statusCode(is(200)).content(equalTo("Hello World")); } @Test public void statusIsMaintained() throws Exception { - given(this.documentationSpec.port(this.port)) - .filter(document("status")) - .when() - .get("/status") - .then() - .assertThat() - .statusCode(is(202)) + given(this.documentationSpec.port(this.port)).filter(document("status")).when() + .get("/status").then().assertThat().statusCode(is(202)) .content(equalTo("Hello World")); } diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockServerRestDocsApplicationTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockServerRestDocsApplicationTests.java index 8fb23892d4..471d91b425 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockServerRestDocsApplicationTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockServerRestDocsApplicationTests.java @@ -40,13 +40,13 @@ import wiremock.org.eclipse.jetty.http.HttpStatus; @AutoConfigureMockMvc public class WiremockServerRestDocsApplicationTests { - @Autowired private MockMvc mockMvc; + @Autowired + private MockMvc mockMvc; @Test public void contextLoads() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/resource")) - .andExpect(content().string("Hello World")) - .andDo(document("resource")); + .andExpect(content().string("Hello World")).andDo(document("resource")); } @Test @@ -59,16 +59,16 @@ public class WiremockServerRestDocsApplicationTests { @Test public void queryParamsAreFetchedFromStubs() throws Exception { - this.mockMvc.perform( - MockMvcRequestBuilders - .get("/project_metadata/spring-framework?callback=a_function_name&foo=foo&bar=bar")) + this.mockMvc.perform(MockMvcRequestBuilders.get( + "/project_metadata/spring-framework?callback=a_function_name&foo=foo&bar=bar")) .andExpect(status().isOk()) .andExpect(content().string("spring-framework a_function_name foo bar")) .andDo(document("query")); File file = new File("target/snippets/stubs", "query.json"); BDDAssertions.then(file).exists(); - StubMapping stubMapping = StubMapping.buildFrom(new String(Files.readAllBytes(file.toPath()))); + StubMapping stubMapping = StubMapping + .buildFrom(new String(Files.readAllBytes(file.toPath()))); Map queryParameters = stubMapping.getRequest() .getQueryParameters(); BDDAssertions.then(queryParameters.get("callback").getValuePattern()) @@ -99,9 +99,9 @@ public class WiremockServerRestDocsApplicationTests { @RequestMapping("/project_metadata/{projectId}") public ResponseEntity query(@PathVariable("projectId") String projectId, @RequestParam("callback") String callback, - @RequestParam("foo") String foo, - @RequestParam("bar") String bar) { - return ResponseEntity.ok().body(projectId + " " + callback + " " + foo + " " + bar); + @RequestParam("foo") String foo, @RequestParam("bar") String bar) { + return ResponseEntity.ok() + .body(projectId + " " + callback + " " + foo + " " + bar); } } diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockServerRestDocsMatcherApplicationTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockServerRestDocsMatcherApplicationTests.java index 4c0391e2cb..570ecbb60b 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockServerRestDocsMatcherApplicationTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockServerRestDocsMatcherApplicationTests.java @@ -33,14 +33,15 @@ public class WiremockServerRestDocsMatcherApplicationTests { @Autowired private MockMvc mockMvc; - + @Rule public ExpectedException expected = ExpectedException.none(); @Test public void matchesRequest() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/resource").content("greeting") - .contentType(MediaType.TEXT_PLAIN)) + this.mockMvc + .perform(MockMvcRequestBuilders.post("/resource").content("greeting") + .contentType(MediaType.TEXT_PLAIN)) .andExpect(MockMvcResultMatchers.content().string("Hello World")) .andDo(WireMockRestDocs.verify() .wiremock(WireMock.post(WireMock.urlPathEqualTo("/resource")) @@ -52,8 +53,9 @@ public class WiremockServerRestDocsMatcherApplicationTests { public void doesNotMatch() throws Exception { this.expected.expect(AssertionError.class); this.expected.expectMessage("wiremock did not match"); - this.mockMvc.perform(MockMvcRequestBuilders.post("/resource").content("greeting") - .contentType(MediaType.TEXT_PLAIN)) + this.mockMvc + .perform(MockMvcRequestBuilders.post("/resource").content("greeting") + .contentType(MediaType.TEXT_PLAIN)) .andExpect(MockMvcResultMatchers.content().string("Hello World")) .andDo(WireMockRestDocs.verify() .wiremock(WireMock.post(WireMock.urlPathEqualTo("/resource")) diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockTestsApplication.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockTestsApplication.java index 92c453df68..06aca0a895 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockTestsApplication.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/WiremockTestsApplication.java @@ -18,7 +18,7 @@ import org.springframework.web.client.RestTemplate; @Configuration @EnableAutoConfiguration -@Import({Service.class, Controller.class}) +@Import({ Service.class, Controller.class }) public class WiremockTestsApplication { @Bean @@ -29,6 +29,7 @@ public class WiremockTestsApplication { public static void main(String[] args) { SpringApplication.run(WiremockTestsApplication.class, args); } + } @RestController @@ -60,13 +61,15 @@ class Service { } public String go() { - return this.restTemplate.getForEntity(this.base + "/test", String.class).getBody(); + return this.restTemplate.getForEntity(this.base + "/test", String.class) + .getBody(); } public String pom() { - return this.restTemplate.exchange( - RequestEntity.get(URI.create(this.base + "/pom.xml")) - .accept(mediaTypes()).build(), String.class).getBody(); + return this.restTemplate + .exchange(RequestEntity.get(URI.create(this.base + "/pom.xml")) + .accept(mediaTypes()).build(), String.class) + .getBody(); } private MediaType[] mediaTypes() { @@ -77,10 +80,12 @@ class Service { } public String go2() { - return this.restTemplate.getForEntity(this.base + "/test2", String.class).getBody(); + return this.restTemplate.getForEntity(this.base + "/test2", String.class) + .getBody(); } public void setBase(String base) { this.base = base; } + } diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/issues/issue399/NotOrderedCustomizerTest.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/issues/issue399/NotOrderedCustomizerTest.java index dff423c26c..a9ac3e9c1e 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/issues/issue399/NotOrderedCustomizerTest.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/issues/issue399/NotOrderedCustomizerTest.java @@ -20,10 +20,13 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; @AutoConfigureWireMock(port = 0) public class NotOrderedCustomizerTest { - @Value("${wiremock.server.port}") Integer port; - @Autowired RestTemplateBuilder restTemplateBuilder; + @Value("${wiremock.server.port}") + Integer port; - @Test + @Autowired + RestTemplateBuilder restTemplateBuilder; + + @Test public void should_not_fail_when_ordered_customizer_added_interceptor_to_rest_template() { stubFor(get(urlEqualTo("/some-url")) .willReturn(aResponse().withStatus(200).withBody("Yeah!"))); @@ -34,4 +37,5 @@ public class NotOrderedCustomizerTest { BDDAssertions.then(body).isEqualTo("Yeah!"); } + } \ No newline at end of file diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/issues/issue399/OrderedCustomizerTest.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/issues/issue399/OrderedCustomizerTest.java index ad0a40a9a8..28fbdaf84b 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/issues/issue399/OrderedCustomizerTest.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/issues/issue399/OrderedCustomizerTest.java @@ -22,10 +22,13 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; @ActiveProfiles("bug") public class OrderedCustomizerTest { - @Value("${wiremock.server.port}") Integer port; - @Autowired RestTemplateBuilder restTemplateBuilder; + @Value("${wiremock.server.port}") + Integer port; - @Test + @Autowired + RestTemplateBuilder restTemplateBuilder; + + @Test public void should_not_fail_when_ordered_customizer_added_interceptor_to_rest_template() { stubFor(get(urlEqualTo("/some-url")) .willReturn(aResponse().withStatus(200).withBody("Yeah!"))); @@ -36,4 +39,5 @@ public class OrderedCustomizerTest { BDDAssertions.then(body).isEqualTo("Yeah!"); } + } \ No newline at end of file diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/issues/issue399/SpringContractWiremockIssueDemoApplication.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/issues/issue399/SpringContractWiremockIssueDemoApplication.java index 5dcead3c05..2d43b2c48b 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/issues/issue399/SpringContractWiremockIssueDemoApplication.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/issues/issue399/SpringContractWiremockIssueDemoApplication.java @@ -25,11 +25,12 @@ public class SpringContractWiremockIssueDemoApplication { @Profile("bug") public RestTemplateCustomizer someOrderedInterceptorCustomizer() { return new RestTemplateCustomizer() { - @Override public void customize(RestTemplate restTemplate) { + @Override + public void customize(RestTemplate restTemplate) { ClientHttpRequestInterceptor emptyInterceptor = new ClientHttpRequestInterceptor() { - @Override public ClientHttpResponse intercept(HttpRequest request, - byte[] body, ClientHttpRequestExecution execution) - throws IOException { + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, + ClientHttpRequestExecution execution) throws IOException { return execution.execute(request, body); } }; @@ -41,11 +42,12 @@ public class SpringContractWiremockIssueDemoApplication { @Bean public RestTemplateCustomizer someNotOrderedInterceptorCustomizer() { return new RestTemplateCustomizer() { - @Override public void customize(RestTemplate restTemplate) { + @Override + public void customize(RestTemplate restTemplate) { ClientHttpRequestInterceptor emptyInterceptor = new ClientHttpRequestInterceptor() { - @Override public ClientHttpResponse intercept(HttpRequest request, - byte[] body, ClientHttpRequestExecution execution) - throws IOException { + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, + ClientHttpRequestExecution execution) throws IOException { return execution.execute(request, body); } }; @@ -58,11 +60,12 @@ public class SpringContractWiremockIssueDemoApplication { @Order public RestTemplateCustomizer someLowestPrecedenceOrderedInterceptorCustomizer() { return new RestTemplateCustomizer() { - @Override public void customize(RestTemplate restTemplate) { + @Override + public void customize(RestTemplate restTemplate) { ClientHttpRequestInterceptor emptyInterceptor = new ClientHttpRequestInterceptor() { - @Override public ClientHttpResponse intercept(HttpRequest request, - byte[] body, ClientHttpRequestExecution execution) - throws IOException { + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, + ClientHttpRequestExecution execution) throws IOException { return execution.execute(request, body); } }; @@ -70,6 +73,7 @@ public class SpringContractWiremockIssueDemoApplication { } }; } + } class RestTemplateClient { @@ -84,4 +88,5 @@ class RestTemplateClient { return restTemplate.getForObject("/some-url", String.class); } + } \ No newline at end of file diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/restdocs/ContractDslSnippetTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/restdocs/ContractDslSnippetTests.java index f69831bb1a..2e0c6f2b42 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/restdocs/ContractDslSnippetTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/restdocs/ContractDslSnippetTests.java @@ -45,51 +45,53 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. public class ContractDslSnippetTests { private static final String OUTPUT = "target/generated-snippets"; + @Rule public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT); MockMvc mockMvc; - @Autowired WebApplicationContext context; + + @Autowired + WebApplicationContext context; @Before public void setUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)) - .build(); + .apply(documentationConfiguration(this.restDocumentation)).build(); } @Test public void should_create_contract_template_and_doc() throws Exception { - //tag::contract_snippet[] - this.mockMvc.perform(post("/foo") - .accept(MediaType.APPLICATION_PDF) - .accept(MediaType.APPLICATION_JSON) - .contentType(MediaType.APPLICATION_JSON) - .content("{\"foo\": 23, \"bar\" : \"baz\" }")) - .andExpect(status().isOk()) - .andExpect(content().string("bar")) + // tag::contract_snippet[] + this.mockMvc + .perform(post("/foo").accept(MediaType.APPLICATION_PDF) + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"foo\": 23, \"bar\" : \"baz\" }")) + .andExpect(status().isOk()).andExpect(content().string("bar")) // first WireMock - .andDo(WireMockRestDocs.verify() - .jsonPath("$[?(@.foo >= 20)]") + .andDo(WireMockRestDocs.verify().jsonPath("$[?(@.foo >= 20)]") .jsonPath("$[?(@.bar in ['baz','bazz','bazzz'])]") .contentType(MediaType.valueOf("application/json")) .stub("shouldGrantABeerIfOldEnough")) // then Contract DSL documentation .andDo(document("index", SpringCloudContractRestDocs.dslContract())); - //end::contract_snippet[] + // end::contract_snippet[] then(file("/contracts/index.groovy")).exists(); then(file("/index/dsl-contract.adoc")).exists(); - Collection parsedContracts = ContractVerifierDslConverter.convertAsCollection(new File("/"), file("/contracts/index.groovy")); + Collection parsedContracts = ContractVerifierDslConverter + .convertAsCollection(new File("/"), file("/contracts/index.groovy")); Contract parsedContract = parsedContracts.iterator().next(); then(parsedContract.getRequest().getHeaders().getEntries()).isNotNull(); - then(headerNames(parsedContract.getRequest().getHeaders().getEntries())).doesNotContain - (HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH); - then(headerNames(parsedContract.getResponse().getHeaders().getEntries())).doesNotContain - (HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH); + then(headerNames(parsedContract.getRequest().getHeaders().getEntries())) + .doesNotContain(HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH); + then(headerNames(parsedContract.getResponse().getHeaders().getEntries())) + .doesNotContain(HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH); then(parsedContract.getRequest().getMethod().getClientValue()).isNotNull(); then(parsedContract.getRequest().getUrl().getClientValue()).isNotNull(); - then(parsedContract.getRequest().getUrl().getClientValue().toString()).startsWith("/"); + then(parsedContract.getRequest().getUrl().getClientValue().toString()) + .startsWith("/"); then(parsedContract.getRequest().getBody().getClientValue()).isNotNull(); then(parsedContract.getRequest().getBodyMatchers().hasMatchers()).isTrue(); then(parsedContract.getResponse().getStatus().getClientValue()).isNotNull(); @@ -98,35 +100,42 @@ public class ContractDslSnippetTests { } @Test - public void should_create_contract_template_and_doc_with_placeholder_names() throws Exception { - this.mockMvc.perform(post("/foo") - .accept(MediaType.APPLICATION_PDF) - .accept(MediaType.APPLICATION_JSON) - .contentType(MediaType.APPLICATION_JSON) - .content("{\"foo\": 23, \"bar\" : \"baz\" }")) - .andExpect(status().isOk()) - .andExpect(content().string("bar")) + public void should_create_contract_template_and_doc_with_placeholder_names() + throws Exception { + this.mockMvc + .perform(post("/foo").accept(MediaType.APPLICATION_PDF) + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"foo\": 23, \"bar\" : \"baz\" }")) + .andExpect(status().isOk()).andExpect(content().string("bar")) // first WireMock - .andDo(WireMockRestDocs.verify() - .jsonPath("$[?(@.foo >= 20)]") + .andDo(WireMockRestDocs.verify().jsonPath("$[?(@.foo >= 20)]") .jsonPath("$[?(@.bar in ['baz','bazz','bazzz'])]") .contentType(MediaType.valueOf("application/json")) .stub("shouldGrantABeerIfOldEnough")) // then Contract DSL documentation - .andDo(document("{methodName}", SpringCloudContractRestDocs.dslContract())); + .andDo(document("{methodName}", + SpringCloudContractRestDocs.dslContract())); - then(file("/contracts/should_create_contract_template_and_doc_with_placeholder_names.groovy")).exists(); - then(file("/should_create_contract_template_and_doc_with_placeholder_names/dsl-contract.adoc")).exists(); - Collection parsedContracts = ContractVerifierDslConverter.convertAsCollection(new File("/"), file("/contracts/should_create_contract_template_and_doc_with_placeholder_names.groovy")); + then(file( + "/contracts/should_create_contract_template_and_doc_with_placeholder_names.groovy")) + .exists(); + then(file( + "/should_create_contract_template_and_doc_with_placeholder_names/dsl-contract.adoc")) + .exists(); + Collection parsedContracts = ContractVerifierDslConverter + .convertAsCollection(new File("/"), file( + "/contracts/should_create_contract_template_and_doc_with_placeholder_names.groovy")); Contract parsedContract = parsedContracts.iterator().next(); then(parsedContract.getRequest().getHeaders().getEntries()).isNotNull(); - then(headerNames(parsedContract.getRequest().getHeaders().getEntries())).doesNotContain - (HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH); - then(headerNames(parsedContract.getResponse().getHeaders().getEntries())).doesNotContain - (HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH); + then(headerNames(parsedContract.getRequest().getHeaders().getEntries())) + .doesNotContain(HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH); + then(headerNames(parsedContract.getResponse().getHeaders().getEntries())) + .doesNotContain(HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH); then(parsedContract.getRequest().getMethod().getClientValue()).isNotNull(); then(parsedContract.getRequest().getUrl().getClientValue()).isNotNull(); - then(parsedContract.getRequest().getUrl().getClientValue().toString()).startsWith("/"); + then(parsedContract.getRequest().getUrl().getClientValue().toString()) + .startsWith("/"); then(parsedContract.getRequest().getBody().getClientValue()).isNotNull(); then(parsedContract.getRequest().getBodyMatchers().hasMatchers()).isTrue(); then(parsedContract.getResponse().getStatus().getClientValue()).isNotNull(); @@ -135,19 +144,21 @@ public class ContractDslSnippetTests { } @Test - public void should_create_contract_template_and_doc_without_body_and_headers() throws Exception { + public void should_create_contract_template_and_doc_without_body_and_headers() + throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/foo")) - .andExpect(status().isOk()) - .andDo(document("empty", dslContract())); + .andExpect(status().isOk()).andDo(document("empty", dslContract())); then(file("/contracts/empty.groovy")).exists(); then(file("/empty/dsl-contract.adoc")).exists(); - Collection parsedContracts = ContractVerifierDslConverter.convertAsCollection(new File("/"), file("/contracts/empty.groovy")); + Collection parsedContracts = ContractVerifierDslConverter + .convertAsCollection(new File("/"), file("/contracts/empty.groovy")); Contract parsedContract = parsedContracts.iterator().next(); then(parsedContract.getRequest().getHeaders()).isNull(); then(parsedContract.getRequest().getMethod().getClientValue()).isNotNull(); then(parsedContract.getRequest().getUrl().getClientValue()).isNotNull(); - then(parsedContract.getRequest().getUrl().getClientValue().toString()).startsWith("/"); + then(parsedContract.getRequest().getUrl().getClientValue().toString()) + .startsWith("/"); then(parsedContract.getRequest().getBody()).isNull(); then(parsedContract.getResponse().getStatus().getClientValue()).isNotNull(); then(parsedContract.getResponse().getHeaders()).isNull(); @@ -180,5 +191,7 @@ public class ContractDslSnippetTests { @GetMapping("/foo") void getFoo() { } + } + } \ No newline at end of file diff --git a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockSnippetTests.java b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockSnippetTests.java index 76a8c01d23..8de20e4c06 100644 --- a/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockSnippetTests.java +++ b/spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/restdocs/WireMockSnippetTests.java @@ -45,14 +45,17 @@ public class WireMockSnippetTests { @Mock(answer = Answers.RETURNS_DEEP_STUBS) Operation operation; + @Rule public TemporaryFolder tmp = new TemporaryFolder(); + private File outputFolder; @Before public void setup() throws IOException { this.outputFolder = this.tmp.newFolder(); - ManualRestDocumentation restDocumentation = new ManualRestDocumentation(this.outputFolder.getAbsolutePath()); + ManualRestDocumentation restDocumentation = new ManualRestDocumentation( + this.outputFolder.getAbsolutePath()); restDocumentation.beforeTest(this.getClass(), "method"); RestDocumentationContext context = restDocumentation.beforeOperation(); given(this.operation.getAttributes().get(anyString())).willReturn(null); @@ -79,8 +82,7 @@ public class WireMockSnippetTests { } @Test - public void should_use_placeholders_in_stub_file_name() - throws Exception { + public void should_use_placeholders_in_stub_file_name() throws Exception { given(this.operation.getName()).willReturn("{method-name}/{step}"); WireMockSnippet snippet = new WireMockSnippet(); @@ -308,7 +310,8 @@ public class WireMockSnippetTests { return URI.create("http://foo/bar"); } - @Override public Collection getCookies() { + @Override + public Collection getCookies() { return Collections.emptySet(); } }; @@ -329,7 +332,8 @@ public class WireMockSnippetTests { @Override public HttpHeaders getHeaders() { HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + httpHeaders.add(HttpHeaders.CONTENT_TYPE, + MediaType.APPLICATION_JSON_VALUE); return httpHeaders; } @@ -353,9 +357,11 @@ public class WireMockSnippetTests { return URI.create("http://foo/bar"); } - @Override public Collection getCookies() { + @Override + public Collection getCookies() { return Collections.emptySet(); } }; } + } \ No newline at end of file diff --git a/tests/samples-messaging-amqp/src/main/java/com/example/AmqpMessagingApplication.java b/tests/samples-messaging-amqp/src/main/java/com/example/AmqpMessagingApplication.java index 8762e60946..4fa3bc40b3 100644 --- a/tests/samples-messaging-amqp/src/main/java/com/example/AmqpMessagingApplication.java +++ b/tests/samples-messaging-amqp/src/main/java/com/example/AmqpMessagingApplication.java @@ -24,15 +24,18 @@ public class AmqpMessagingApplication { @Bean public MessageConverter messageConverter(ObjectMapper objectMapper) { - final Jackson2JsonMessageConverter jsonMessageConverter = new Jackson2JsonMessageConverter(objectMapper); + final Jackson2JsonMessageConverter jsonMessageConverter = new Jackson2JsonMessageConverter( + objectMapper); jsonMessageConverter.setCreateMessageIds(true); - final ContentTypeDelegatingMessageConverter messageConverter = new ContentTypeDelegatingMessageConverter(jsonMessageConverter); + final ContentTypeDelegatingMessageConverter messageConverter = new ContentTypeDelegatingMessageConverter( + jsonMessageConverter); messageConverter.addDelegate(CONTENT_TYPE_JSON, jsonMessageConverter); return messageConverter; } @Bean - public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, MessageConverter messageConverter) { + public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, + MessageConverter messageConverter) { RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); rabbitTemplate.setMessageConverter(messageConverter); return rabbitTemplate; diff --git a/tests/samples-messaging-amqp/src/main/java/com/example/Book.java b/tests/samples-messaging-amqp/src/main/java/com/example/Book.java index 5e0832cb90..c99a20fa52 100644 --- a/tests/samples-messaging-amqp/src/main/java/com/example/Book.java +++ b/tests/samples-messaging-amqp/src/main/java/com/example/Book.java @@ -14,4 +14,5 @@ public class Book { public String getName() { return this.name; } + } diff --git a/tests/samples-messaging-amqp/src/main/java/com/example/Issue178ListenerConfiguration.java b/tests/samples-messaging-amqp/src/main/java/com/example/Issue178ListenerConfiguration.java index 4ba68e4563..642b9ed2e6 100644 --- a/tests/samples-messaging-amqp/src/main/java/com/example/Issue178ListenerConfiguration.java +++ b/tests/samples-messaging-amqp/src/main/java/com/example/Issue178ListenerConfiguration.java @@ -21,8 +21,10 @@ import com.fasterxml.jackson.databind.ObjectMapper; */ @Configuration class Issue178ListenerConfiguration { + @Bean - SimpleMessageListenerContainer messageListenerContainer(ConnectionFactory connectionFactory, RabbitTemplate rabbitTemplate) { + SimpleMessageListenerContainer messageListenerContainer( + ConnectionFactory connectionFactory, RabbitTemplate rabbitTemplate) { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.addQueueNames("rated-item-service.rated-item-event.exchange"); @@ -36,9 +38,12 @@ class Issue178ListenerConfiguration { public void onMessage(Message message) { System.out.println("received: " + message); try { - String payload = new ObjectMapper().writeValueAsString(new MyPojo("992e46d8-ab05-4a26-a740-6ef7b0daeab3", "CREATED")); - Message outputMessage = MessageBuilder.withBody(payload.getBytes()).build(); - rabbitTemplate.send(issue178OutputExchange().getName(), "routingkey", outputMessage); + String payload = new ObjectMapper().writeValueAsString(new MyPojo( + "992e46d8-ab05-4a26-a740-6ef7b0daeab3", "CREATED")); + Message outputMessage = MessageBuilder.withBody(payload.getBytes()) + .build(); + rabbitTemplate.send(issue178OutputExchange().getName(), "routingkey", + outputMessage); } catch (JsonProcessingException e) { throw new RuntimeException(e); @@ -48,7 +53,9 @@ class Issue178ListenerConfiguration { } static class MyPojo { + public String ratedItemId; + public String eventType; public MyPojo(String ratedItemId, String eventType) { @@ -58,9 +65,11 @@ class Issue178ListenerConfiguration { public MyPojo() { } + } - @Bean Queue issue178InputQueue() { + @Bean + Queue issue178InputQueue() { return new Queue("rated-item-service.rated-item-event.exchange", false); } @@ -74,8 +83,10 @@ class Issue178ListenerConfiguration { return new TopicExchange("bill-service.rated-item-event.retry-exchange"); } - @Bean Binding binding() { - return BindingBuilder.bind(issue178InputQueue()).to(issue178InputExchange()).with("rated-item-service.rated-item-event.exchange"); + @Bean + Binding binding() { + return BindingBuilder.bind(issue178InputQueue()).to(issue178InputExchange()) + .with("rated-item-service.rated-item-event.exchange"); } } diff --git a/tests/samples-messaging-amqp/src/main/java/com/example/MessagePublisher.java b/tests/samples-messaging-amqp/src/main/java/com/example/MessagePublisher.java index 420ade4ff0..387e10ef92 100644 --- a/tests/samples-messaging-amqp/src/main/java/com/example/MessagePublisher.java +++ b/tests/samples-messaging-amqp/src/main/java/com/example/MessagePublisher.java @@ -17,4 +17,5 @@ public class MessagePublisher { public void sendMessage(Book book) { this.rabbitTemplate.convertAndSend(this.exchange.getName(), "routingkey", book); } + } diff --git a/tests/samples-messaging-amqp/src/main/java/com/example/RabbitManager.java b/tests/samples-messaging-amqp/src/main/java/com/example/RabbitManager.java index da78ee23e1..b38915d01e 100644 --- a/tests/samples-messaging-amqp/src/main/java/com/example/RabbitManager.java +++ b/tests/samples-messaging-amqp/src/main/java/com/example/RabbitManager.java @@ -16,6 +16,7 @@ import org.springframework.messaging.handler.annotation.Headers; import org.springframework.stereotype.Component; interface BookService { + void sendBook(Book book, String replyTo); void newBook(Book book); @@ -34,65 +35,71 @@ public class RabbitManager { public static final Logger LOG = LoggerFactory.getLogger(RabbitManager.class); private BookService service; + private RabbitTemplate rabbitTemplate; - @Autowired public RabbitManager(BookService service, RabbitTemplate rabbitTemplate) { + @Autowired + public RabbitManager(BookService service, RabbitTemplate rabbitTemplate) { this.service = service; this.rabbitTemplate = rabbitTemplate; } - @RabbitListener(bindings = @QueueBinding(value = @Queue(), - exchange = @Exchange(value = "input", durable = "true", - autoDelete = "false", type = "topic"), key = "event")) - public void newBook( - Book book, @Headers Map headers) { + @RabbitListener(bindings = @QueueBinding(value = @Queue(), exchange = @Exchange(value = "input", durable = "true", autoDelete = "false", type = "topic"), key = "event")) + public void newBook(Book book, @Headers Map headers) { LOG.info("Received new book with bookname = " + book.getName()); LOG.info("Headers = " + headers); this.service.sendBook(book, headers.get("amqp_replyTo")); } - @RabbitListener(bindings = @QueueBinding(value = @Queue(), - exchange = @Exchange(value = "input", durable = "true", - autoDelete = "false", type = "topic"), key = "event2")) - public void newBook2( - Book book, @Headers Map headers) { + @RabbitListener(bindings = @QueueBinding(value = @Queue(), exchange = @Exchange(value = "input", durable = "true", autoDelete = "false", type = "topic"), key = "event2")) + public void newBook2(Book book, @Headers Map headers) { LOG.info("newBook2 Received new book with bookname = " + book.getName()); LOG.info("newBook2 Headers = " + headers); this.service.sendBook(book, headers.get("amqp_replyTo")); } + } @Component class BookServiceImpl implements BookService { + public static final Logger LOG = LoggerFactory.getLogger(BookServiceImpl.class); private List books; + private RabbitTemplate rabbitTemplate; - @Autowired public BookServiceImpl(RabbitTemplate rabbitTemplate) { + @Autowired + public BookServiceImpl(RabbitTemplate rabbitTemplate) { this.books = new LinkedList<>(); this.rabbitTemplate = rabbitTemplate; } - @Override public void sendBook(Book book, String replyTo) { + @Override + public void sendBook(Book book, String replyTo) { LOG.info("Received new book with bookname = " + book.getName()); newBook(book); this.rabbitTemplate.convertAndSend("", replyTo, book); } - @Override public void newBook(Book book) { + @Override + public void newBook(Book book) { this.books.add(book); } - @Override public Book getBook(int index) { + @Override + public Book getBook(int index) { return this.books.get(index); } - @Override public int noOfBooks() { + @Override + public int noOfBooks() { return this.books.size(); } - @Override public List getBooks() { + @Override + public List getBooks() { return this.books; } + } diff --git a/tests/samples-messaging-integration/src/main/java/com/example/BookDeleted.java b/tests/samples-messaging-integration/src/main/java/com/example/BookDeleted.java index 15635f725e..4f30222b88 100644 --- a/tests/samples-messaging-integration/src/main/java/com/example/BookDeleted.java +++ b/tests/samples-messaging-integration/src/main/java/com/example/BookDeleted.java @@ -22,10 +22,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; @SuppressWarnings("serial") public class BookDeleted implements Serializable { + public final String bookName; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public BookDeleted(String bookName) { this.bookName = bookName; } + } diff --git a/tests/samples-messaging-integration/src/main/java/com/example/BookListener.java b/tests/samples-messaging-integration/src/main/java/com/example/BookListener.java index b707286536..0267231b76 100644 --- a/tests/samples-messaging-integration/src/main/java/com/example/BookListener.java +++ b/tests/samples-messaging-integration/src/main/java/com/example/BookListener.java @@ -48,7 +48,8 @@ public class BookListener { * upon receiving message on the output messageFrom */ public void bookDeleted(BookDeleted bookDeleted) { - log.info("Deleting book [ "+ bookDeleted + "]"); + log.info("Deleting book [ " + bookDeleted + "]"); this.bookSuccessfullyDeleted.set(true); } + } diff --git a/tests/samples-messaging-integration/src/main/java/com/example/BookReturned.java b/tests/samples-messaging-integration/src/main/java/com/example/BookReturned.java index 44b6b35003..71f8b2ab07 100644 --- a/tests/samples-messaging-integration/src/main/java/com/example/BookReturned.java +++ b/tests/samples-messaging-integration/src/main/java/com/example/BookReturned.java @@ -22,10 +22,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; @SuppressWarnings("serial") public class BookReturned implements Serializable { + public final String bookName; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) BookReturned(String bookName) { this.bookName = bookName; } + } diff --git a/tests/samples-messaging-integration/src/main/java/com/example/BookService.java b/tests/samples-messaging-integration/src/main/java/com/example/BookService.java index 2b97ffc3e8..beb2af1b28 100644 --- a/tests/samples-messaging-integration/src/main/java/com/example/BookService.java +++ b/tests/samples-messaging-integration/src/main/java/com/example/BookService.java @@ -36,7 +36,7 @@ public class BookService { * a possibility to "trigger" sending of a message to the given messageFrom server * side: will run the method and await upon receiving message on the output * messageFrom - * + * * Method triggers sending a message to a source */ public void returnBook(BookReturned bookReturned) { @@ -44,4 +44,5 @@ public class BookService { this.outputChannel.send(MessageBuilder.withPayload(bookReturned) .setHeader("BOOK-NAME", bookReturned.bookName).build()); } + } diff --git a/tests/samples-messaging-integration/src/main/java/com/example/IntegrationMessagingApplication.java b/tests/samples-messaging-integration/src/main/java/com/example/IntegrationMessagingApplication.java index fe11aa6f9f..ff33d51dc5 100644 --- a/tests/samples-messaging-integration/src/main/java/com/example/IntegrationMessagingApplication.java +++ b/tests/samples-messaging-integration/src/main/java/com/example/IntegrationMessagingApplication.java @@ -27,4 +27,5 @@ public class IntegrationMessagingApplication { public static void main(String[] args) { SpringApplication.run(IntegrationMessagingApplication.class, args); } + } diff --git a/tests/samples-messaging-spring/src/main/java/com/example/BookDeleted.java b/tests/samples-messaging-spring/src/main/java/com/example/BookDeleted.java index 15635f725e..4f30222b88 100644 --- a/tests/samples-messaging-spring/src/main/java/com/example/BookDeleted.java +++ b/tests/samples-messaging-spring/src/main/java/com/example/BookDeleted.java @@ -22,10 +22,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; @SuppressWarnings("serial") public class BookDeleted implements Serializable { + public final String bookName; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public BookDeleted(String bookName) { this.bookName = bookName; } + } diff --git a/tests/samples-messaging-spring/src/main/java/com/example/BookListener.java b/tests/samples-messaging-spring/src/main/java/com/example/BookListener.java index 3aee3a92a9..5f6d1fb777 100644 --- a/tests/samples-messaging-spring/src/main/java/com/example/BookListener.java +++ b/tests/samples-messaging-spring/src/main/java/com/example/BookListener.java @@ -34,12 +34,11 @@ import com.fasterxml.jackson.databind.ObjectMapper; @Service public class BookListener { - - + private static final Logger log = LoggerFactory.getLogger(BookListener.class); - private @Autowired JmsTemplate jmsTemplate; + private ObjectMapper objectMapper = new ObjectMapper(); /** @@ -50,7 +49,8 @@ public class BookListener { */ @JmsListener(destination = "input") public void returnBook(String messageAsString) throws Exception { - final BookReturned bookReturned = this.objectMapper.readerFor(BookReturned.class).readValue(messageAsString); + final BookReturned bookReturned = this.objectMapper.readerFor(BookReturned.class) + .readValue(messageAsString); log.info("Returning book [$bookReturned]"); MessageCreator messageCreator = new MessageCreator() { @Override @@ -64,18 +64,21 @@ public class BookListener { } /** - Scenario for "should generate tests triggered by a message": - client side: if sends a message to input.messageFrom then message will be sent to output.messageFrom - server side: will send a message to input, verify the message contents and await upon receiving message on the output messageFrom + * Scenario for "should generate tests triggered by a message": client side: if sends + * a message to input.messageFrom then message will be sent to output.messageFrom + * server side: will send a message to input, verify the message contents and await + * upon receiving message on the output messageFrom * @throws java.io.IOException * @throws com.fasterxml.jackson.core.JsonProcessingException */ @JmsListener(destination = "delete") public void bookDeleted(String bookDeletedAsString) throws Exception { - BookDeleted bookDeleted = this.objectMapper.readerFor(BookDeleted.class).readValue(bookDeletedAsString); + BookDeleted bookDeleted = this.objectMapper.readerFor(BookDeleted.class) + .readValue(bookDeletedAsString); log.info("Deleting book " + bookDeleted); this.bookSuccessfulyDeleted.set(true); } AtomicBoolean bookSuccessfulyDeleted = new AtomicBoolean(false); + } diff --git a/tests/samples-messaging-spring/src/main/java/com/example/BookReturned.java b/tests/samples-messaging-spring/src/main/java/com/example/BookReturned.java index 44b6b35003..71f8b2ab07 100644 --- a/tests/samples-messaging-spring/src/main/java/com/example/BookReturned.java +++ b/tests/samples-messaging-spring/src/main/java/com/example/BookReturned.java @@ -22,10 +22,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; @SuppressWarnings("serial") public class BookReturned implements Serializable { + public final String bookName; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) BookReturned(String bookName) { this.bookName = bookName; } + } diff --git a/tests/samples-messaging-spring/src/main/java/com/example/BookService.java b/tests/samples-messaging-spring/src/main/java/com/example/BookService.java index 070b005f11..f0bc1b8246 100644 --- a/tests/samples-messaging-spring/src/main/java/com/example/BookService.java +++ b/tests/samples-messaging-spring/src/main/java/com/example/BookService.java @@ -39,7 +39,7 @@ public class BookService { * a possibility to "trigger" sending of a message to the given messageFrom server * side: will run the method and await upon receiving message on the output * messageFrom - * + * * Method triggers sending a message to a source */ public void returnBook(final BookReturned bookReturned) { @@ -54,4 +54,5 @@ public class BookService { }; this.jmsTemplate.send("output", messageCreator); } + } diff --git a/tests/samples-messaging-spring/src/main/java/com/example/SpringMessagingApplication.java b/tests/samples-messaging-spring/src/main/java/com/example/SpringMessagingApplication.java index 269b3776aa..30845faa5c 100644 --- a/tests/samples-messaging-spring/src/main/java/com/example/SpringMessagingApplication.java +++ b/tests/samples-messaging-spring/src/main/java/com/example/SpringMessagingApplication.java @@ -27,4 +27,5 @@ class SpringMessagingApplication { static void main(String[] args) { SpringApplication.run(SpringMessagingApplication.class, args); } + } diff --git a/tests/samples-messaging-stream/src/main/java/com/example/BookDeleted.java b/tests/samples-messaging-stream/src/main/java/com/example/BookDeleted.java index 15635f725e..4f30222b88 100644 --- a/tests/samples-messaging-stream/src/main/java/com/example/BookDeleted.java +++ b/tests/samples-messaging-stream/src/main/java/com/example/BookDeleted.java @@ -22,10 +22,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; @SuppressWarnings("serial") public class BookDeleted implements Serializable { + public final String bookName; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public BookDeleted(String bookName) { this.bookName = bookName; } + } diff --git a/tests/samples-messaging-stream/src/main/java/com/example/BookListener.java b/tests/samples-messaging-stream/src/main/java/com/example/BookListener.java index 0aa2833240..98f7a64fd1 100644 --- a/tests/samples-messaging-stream/src/main/java/com/example/BookListener.java +++ b/tests/samples-messaging-stream/src/main/java/com/example/BookListener.java @@ -62,4 +62,5 @@ public class BookListener { } public AtomicBoolean bookSuccessfulyDeleted = new AtomicBoolean(false); + } diff --git a/tests/samples-messaging-stream/src/main/java/com/example/BookReturned.java b/tests/samples-messaging-stream/src/main/java/com/example/BookReturned.java index 44b6b35003..71f8b2ab07 100644 --- a/tests/samples-messaging-stream/src/main/java/com/example/BookReturned.java +++ b/tests/samples-messaging-stream/src/main/java/com/example/BookReturned.java @@ -22,10 +22,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; @SuppressWarnings("serial") public class BookReturned implements Serializable { + public final String bookName; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) BookReturned(String bookName) { this.bookName = bookName; } + } diff --git a/tests/samples-messaging-stream/src/main/java/com/example/BookService.java b/tests/samples-messaging-stream/src/main/java/com/example/BookService.java index 074789bd9a..47969efd0d 100644 --- a/tests/samples-messaging-stream/src/main/java/com/example/BookService.java +++ b/tests/samples-messaging-stream/src/main/java/com/example/BookService.java @@ -40,7 +40,7 @@ public class BookService { * a possibility to "trigger" sending of a message to the given messageFrom server * side: will run the method and await upon receiving message on the output * messageFrom - * + * * Method triggers sending a message to a source */ public void returnBook(BookReturned bookReturned) { @@ -48,4 +48,5 @@ public class BookService { this.source.output().send(MessageBuilder.withPayload(bookReturned) .setHeader("BOOK-NAME", bookReturned.bookName).build()); } + } diff --git a/tests/samples-messaging-stream/src/main/java/com/example/DeleteSink.java b/tests/samples-messaging-stream/src/main/java/com/example/DeleteSink.java index 31b2ad01b8..cf1476d8a2 100644 --- a/tests/samples-messaging-stream/src/main/java/com/example/DeleteSink.java +++ b/tests/samples-messaging-stream/src/main/java/com/example/DeleteSink.java @@ -29,4 +29,5 @@ interface DeleteSink extends Sink { @Input(DeleteSink.INPUT) SubscribableChannel delete(); + } diff --git a/tests/samples-messaging-stream/src/main/java/com/example/StreamMessagingApplication.java b/tests/samples-messaging-stream/src/main/java/com/example/StreamMessagingApplication.java index 07f2d3b3f9..dd9f7c1d6f 100644 --- a/tests/samples-messaging-stream/src/main/java/com/example/StreamMessagingApplication.java +++ b/tests/samples-messaging-stream/src/main/java/com/example/StreamMessagingApplication.java @@ -23,10 +23,11 @@ import org.springframework.cloud.stream.messaging.Sink; import org.springframework.cloud.stream.messaging.Source; @SpringBootApplication -@EnableBinding({Source.class, Sink.class}) +@EnableBinding({ Source.class, Sink.class }) class StreamMessagingApplication { public static void main(String[] args) { SpringApplication.run(StreamMessagingApplication.class, args); } + } diff --git a/tests/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpMessagingApplication.java b/tests/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpMessagingApplication.java index 1bab010836..83f5d31fdd 100644 --- a/tests/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpMessagingApplication.java +++ b/tests/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpMessagingApplication.java @@ -32,15 +32,18 @@ public class AmqpMessagingApplication { @Bean public MessageConverter messageConverter(ObjectMapper objectMapper) { - final Jackson2JsonMessageConverter jsonMessageConverter = new Jackson2JsonMessageConverter(objectMapper); + final Jackson2JsonMessageConverter jsonMessageConverter = new Jackson2JsonMessageConverter( + objectMapper); jsonMessageConverter.setCreateMessageIds(true); - final ContentTypeDelegatingMessageConverter messageConverter = new ContentTypeDelegatingMessageConverter(jsonMessageConverter); + final ContentTypeDelegatingMessageConverter messageConverter = new ContentTypeDelegatingMessageConverter( + jsonMessageConverter); messageConverter.addDelegate(CONTENT_TYPE_JSON, jsonMessageConverter); return messageConverter; } @Bean - public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, MessageConverter messageConverter) { + public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, + MessageConverter messageConverter) { RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); rabbitTemplate.setMessageConverter(messageConverter); return rabbitTemplate; @@ -51,7 +54,8 @@ public class AmqpMessagingApplication { static class MessageListenerAdapterConfig { @Bean - public MessageListenerAdapter messageListenerAdapter(MessageSubscriber messageSubscriber, MessageConverter messageConverter) { + public MessageListenerAdapter messageListenerAdapter( + MessageSubscriber messageSubscriber, MessageConverter messageConverter) { return new MessageListenerAdapter(messageSubscriber, messageConverter); } @@ -59,14 +63,16 @@ public class AmqpMessagingApplication { @Bean public Binding binding() { - return BindingBuilder.bind(new Queue("test.queue")).to(new DirectExchange("contract-test.exchange")).with("#"); + return BindingBuilder.bind(new Queue("test.queue")) + .to(new DirectExchange("contract-test.exchange")).with("#"); } // end::amqp_binding[] // tag::amqp_listener[] @Bean - public SimpleMessageListenerContainer simpleMessageListenerContainer(ConnectionFactory connectionFactory, - MessageListenerAdapter listenerAdapter) { + public SimpleMessageListenerContainer simpleMessageListenerContainer( + ConnectionFactory connectionFactory, + MessageListenerAdapter listenerAdapter) { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.setQueueNames("test.queue"); @@ -80,6 +86,7 @@ public class AmqpMessagingApplication { public MessageSubscriber messageSubscriber() { return new MessageSubscriber(); } + } @Configuration @@ -93,8 +100,8 @@ public class AmqpMessagingApplication { } @Bean - public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory, - MessageConverter messageConverter) { + public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory( + ConnectionFactory connectionFactory, MessageConverter messageConverter) { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setConnectionFactory(connectionFactory); factory.setConcurrentConsumers(3); @@ -102,5 +109,7 @@ public class AmqpMessagingApplication { factory.setMessageConverter(messageConverter); return factory; } + } + } diff --git a/tests/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/MessageSubscriber.java b/tests/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/MessageSubscriber.java index f859e4a7a9..850b851d01 100644 --- a/tests/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/MessageSubscriber.java +++ b/tests/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/MessageSubscriber.java @@ -5,4 +5,5 @@ public class MessageSubscriber { public void handleMessage(Person person) { } + } diff --git a/tests/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/MessageSubscriberRabbitListener.java b/tests/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/MessageSubscriberRabbitListener.java index d046f6365a..03150e70fb 100644 --- a/tests/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/MessageSubscriberRabbitListener.java +++ b/tests/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/MessageSubscriberRabbitListener.java @@ -10,14 +10,14 @@ public class MessageSubscriberRabbitListener { private Person person; // tag::amqp_annotated_listener[] - @RabbitListener(bindings = @QueueBinding( - value = @Queue(value = "test.queue"), - exchange = @Exchange(value = "contract-test.exchange", ignoreDeclarationExceptions = "true"))) + @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "test.queue"), exchange = @Exchange(value = "contract-test.exchange", ignoreDeclarationExceptions = "true"))) public void handlePerson(Person person) { this.person = person; } + // end::amqp_annotated_listener[] public Person getPerson() { return this.person; } + } diff --git a/tests/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/Person.java b/tests/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/Person.java index 87f6286491..163149dcfc 100644 --- a/tests/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/Person.java +++ b/tests/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/Person.java @@ -3,6 +3,7 @@ package org.springframework.cloud.contract.stubrunner.messaging.amqp; public class Person { private Integer id; + private String name; public Integer getId() { @@ -20,4 +21,5 @@ public class Person { public void setName(String name) { this.name = name; } + } diff --git a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/Application.java b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/Application.java index 56af56d989..836d122652 100644 --- a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/Application.java +++ b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/Application.java @@ -14,11 +14,12 @@ public class Application { } - @RestController class CustomController { + @GetMapping("/foo") String foo() { return "bar"; } + } \ No newline at end of file diff --git a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/LoanApplicationService.java b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/LoanApplicationService.java index 6bc690e4e4..21b5e9e5d3 100644 --- a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/LoanApplicationService.java +++ b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/LoanApplicationService.java @@ -17,8 +17,7 @@ import com.example.loan.model.LoanApplicationStatus; @Service public class LoanApplicationService { - private static final String FRAUD_SERVICE_JSON_VERSION_1 = - "application/vnd.fraud.v1+json"; + private static final String FRAUD_SERVICE_JSON_VERSION_1 = "application/vnd.fraud.v1+json"; private final RestTemplate restTemplate; @@ -29,11 +28,9 @@ public class LoanApplicationService { } public LoanApplicationResult loanApplication(LoanApplication loanApplication) { - FraudServiceRequest request = - new FraudServiceRequest(loanApplication); + FraudServiceRequest request = new FraudServiceRequest(loanApplication); - FraudServiceResponse response = - sendRequestToFraudDetectionService(request); + FraudServiceResponse response = sendRequestToFraudDetectionService(request); return buildResponseFromFraudResult(response); } @@ -44,27 +41,30 @@ public class LoanApplicationService { httpHeaders.add(HttpHeaders.CONTENT_TYPE, FRAUD_SERVICE_JSON_VERSION_1); // tag::client_call_server[] - ResponseEntity response = - this.restTemplate.exchange(this.fraudUrl + "/fraudcheck", HttpMethod.PUT, - new HttpEntity<>(request, httpHeaders), - FraudServiceResponse.class); + ResponseEntity response = this.restTemplate.exchange( + this.fraudUrl + "/fraudcheck", HttpMethod.PUT, + new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class); // end::client_call_server[] return response.getBody(); } - private LoanApplicationResult buildResponseFromFraudResult(FraudServiceResponse response) { + private LoanApplicationResult buildResponseFromFraudResult( + FraudServiceResponse response) { LoanApplicationStatus applicationStatus = null; if (FraudCheckStatus.OK == response.getFraudCheckStatus()) { applicationStatus = LoanApplicationStatus.LOAN_APPLIED; - } else if (FraudCheckStatus.FRAUD == response.getFraudCheckStatus()) { + } + else if (FraudCheckStatus.FRAUD == response.getFraudCheckStatus()) { applicationStatus = LoanApplicationStatus.LOAN_APPLICATION_REJECTED; } - return new LoanApplicationResult(applicationStatus, response.getRejectionReason()); + return new LoanApplicationResult(applicationStatus, + response.getRejectionReason()); } public void setFraudUrl(String fraudUrl) { this.fraudUrl = fraudUrl; } + } diff --git a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/Client.java b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/Client.java index d588e93b4b..385c723152 100644 --- a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/Client.java +++ b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/Client.java @@ -3,7 +3,7 @@ package com.example.loan.model; public class Client { private String clientId; - + public Client() { } @@ -18,4 +18,5 @@ public class Client { public void setClientId(String clientId) { this.clientId = clientId; } + } diff --git a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/FraudCheckStatus.java b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/FraudCheckStatus.java index c5217ef471..e2dd348bf9 100644 --- a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/FraudCheckStatus.java +++ b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/FraudCheckStatus.java @@ -1,5 +1,7 @@ package com.example.loan.model; public enum FraudCheckStatus { + OK, FRAUD + } diff --git a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/FraudServiceRequest.java b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/FraudServiceRequest.java index 85f3b37d06..a9443e2eca 100644 --- a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/FraudServiceRequest.java +++ b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/FraudServiceRequest.java @@ -31,4 +31,5 @@ public class FraudServiceRequest { public void setLoanAmount(BigDecimal loanAmount) { this.loanAmount = loanAmount; } + } diff --git a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/FraudServiceResponse.java b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/FraudServiceResponse.java index eb5f64116d..4d421c432d 100644 --- a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/FraudServiceResponse.java +++ b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/FraudServiceResponse.java @@ -24,4 +24,5 @@ public class FraudServiceResponse { public void setRejectionReason(String rejectionReason) { this.rejectionReason = rejectionReason; } + } diff --git a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/LoanApplication.java b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/LoanApplication.java index 85a7f8c5d9..14b48b440b 100644 --- a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/LoanApplication.java +++ b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/LoanApplication.java @@ -41,4 +41,5 @@ public class LoanApplication { public void setLoanApplicationId(String loanApplicationId) { this.loanApplicationId = loanApplicationId; } + } diff --git a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/LoanApplicationResult.java b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/LoanApplicationResult.java index 5214e0d4f7..7cc9bf1081 100644 --- a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/LoanApplicationResult.java +++ b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/LoanApplicationResult.java @@ -9,7 +9,8 @@ public class LoanApplicationResult { public LoanApplicationResult() { } - public LoanApplicationResult(LoanApplicationStatus loanApplicationStatus, String rejectionReason) { + public LoanApplicationResult(LoanApplicationStatus loanApplicationStatus, + String rejectionReason) { this.loanApplicationStatus = loanApplicationStatus; this.rejectionReason = rejectionReason; } @@ -29,4 +30,5 @@ public class LoanApplicationResult { public void setRejectionReason(String rejectionReason) { this.rejectionReason = rejectionReason; } + } diff --git a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/LoanApplicationStatus.java b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/LoanApplicationStatus.java index 34cf91a89f..ceceb6cff6 100644 --- a/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/LoanApplicationStatus.java +++ b/tests/spring-cloud-contract-stub-runner-context-path/src/main/java/com/example/loan/model/LoanApplicationStatus.java @@ -1,5 +1,7 @@ package com.example.loan.model; public enum LoanApplicationStatus { + LOAN_APPLIED, LOAN_APPLICATION_REJECTED + } diff --git a/tests/spring-cloud-contract-stub-runner-context-path/src/test/java/com/example/loan/FailFastLoanApplicationServiceTests.java b/tests/spring-cloud-contract-stub-runner-context-path/src/test/java/com/example/loan/FailFastLoanApplicationServiceTests.java index 3856475c64..e713e78f4e 100644 --- a/tests/spring-cloud-contract-stub-runner-context-path/src/test/java/com/example/loan/FailFastLoanApplicationServiceTests.java +++ b/tests/spring-cloud-contract-stub-runner-context-path/src/test/java/com/example/loan/FailFastLoanApplicationServiceTests.java @@ -35,30 +35,34 @@ public class FailFastLoanApplicationServiceTests { @Test public void shouldFailToStartContextWhenNoStubCanBeFound() { // When - final Throwable throwable = catchThrowable(() -> new SpringApplicationBuilder(Application.class, StubRunnerConfiguration.class) - .properties(ImmutableMap.of( - "stubrunner.stubsMode", "REMOTE", - "stubrunner.repositoryRoot", "classpath:m2repo/repository/", - "stubrunner.ids", new String[]{"org.springframework.cloud.contract.verifier.stubs:should-not-be-found"})) - .run()); + final Throwable throwable = catchThrowable(() -> new SpringApplicationBuilder( + Application.class, StubRunnerConfiguration.class) + .properties(ImmutableMap.of("stubrunner.stubsMode", "REMOTE", + "stubrunner.repositoryRoot", + "classpath:m2repo/repository/", "stubrunner.ids", + new String[] { + "org.springframework.cloud.contract.verifier.stubs:should-not-be-found" })) + .run()); // Then assertThat(throwable).isInstanceOf(BeanCreationException.class); assertThat(throwable.getCause()).isInstanceOf(BeanInstantiationException.class); assertThat(throwable.getCause().getCause()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("For groupId [org.springframework.cloud.contract.verifier.stubs] artifactId [should-not-be-found] " - + "and classifier [stubs] the version was not resolved! The following exceptions took place"); + .isInstanceOf(IllegalArgumentException.class).hasMessageContaining( + "For groupId [org.springframework.cloud.contract.verifier.stubs] artifactId [should-not-be-found] " + + "and classifier [stubs] the version was not resolved! The following exceptions took place"); } @Test public void shouldNotTryAndWorkOfflineWhenRemoteModeIsOn() { // When - final Throwable throwable = catchThrowable(() -> new SpringApplicationBuilder(Application.class, StubRunnerConfiguration.class) - .properties(ImmutableMap.of( - "stubrunner.stubsMode", "CLASSPATH", - "stubrunner.ids", new String[]{"org.springframework.cloud.contract.verifier.stubs:should-not-be-found"})) - .run()); + final Throwable throwable = catchThrowable(() -> new SpringApplicationBuilder( + Application.class, StubRunnerConfiguration.class) + .properties(ImmutableMap.of("stubrunner.stubsMode", "CLASSPATH", + "stubrunner.ids", + new String[] { + "org.springframework.cloud.contract.verifier.stubs:should-not-be-found" })) + .run()); // Then assertThat(throwable).isInstanceOf(BeanCreationException.class); diff --git a/tests/spring-cloud-contract-stub-runner-context-path/src/test/java/com/example/loan/LoanApplicationServiceTests.java b/tests/spring-cloud-contract-stub-runner-context-path/src/test/java/com/example/loan/LoanApplicationServiceTests.java index f3ed2d3174..9289236182 100644 --- a/tests/spring-cloud-contract-stub-runner-context-path/src/test/java/com/example/loan/LoanApplicationServiceTests.java +++ b/tests/spring-cloud-contract-stub-runner-context-path/src/test/java/com/example/loan/LoanApplicationServiceTests.java @@ -22,26 +22,33 @@ import static org.assertj.core.api.Assertions.assertThat; // tag::autoconfigure_stubrunner[] @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) -@AutoConfigureStubRunner(repositoryRoot = "classpath:m2repo/repository/", - ids = { "org.springframework.cloud.contract.verifier.stubs:contextPathFraudDetectionServer" }, - stubsMode = StubRunnerProperties.StubsMode.REMOTE) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@AutoConfigureStubRunner(repositoryRoot = "classpath:m2repo/repository/", ids = { + "org.springframework.cloud.contract.verifier.stubs:contextPathFraudDetectionServer" }, stubsMode = StubRunnerProperties.StubsMode.REMOTE) public class LoanApplicationServiceTests { -// end::autoconfigure_stubrunner[] - @Autowired private LoanApplicationService service; - @Autowired private StubFinder stubFinder; - @LocalServerPort Integer port; + // end::autoconfigure_stubrunner[] + + @Autowired + private LoanApplicationService service; + + @Autowired + private StubFinder stubFinder; + + @LocalServerPort + Integer port; @Before public void setPort() { - this.service.setFraudUrl(this.stubFinder.findStubUrl("contextPathFraudDetectionServer").toString() + "/fraud-path/"); + this.service.setFraudUrl( + this.stubFinder.findStubUrl("contextPathFraudDetectionServer").toString() + + "/fraud-path/"); } @Test public void shouldStartThisAppWithContextPath() { - String response = new RestTemplate() - .getForObject("http://localhost:" + this.port + "/my-path/foo", String.class); + String response = new RestTemplate().getForObject( + "http://localhost:" + this.port + "/my-path/foo", String.class); assertThat(response).isNotEmpty(); }