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
- * 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 extends ELEMENT> 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 extends ELEMENT> actual) {
+ public static CollectionAssert assertThat(
+ Iterable extends ELEMENT> 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