Format source code

Closes gh-923
This commit is contained in:
Stephane Nicoll
2019-06-11 22:55:09 +02:00
parent 4132306a53
commit 2f50cf1c8f
280 changed files with 2961 additions and 4965 deletions

View File

@@ -33,8 +33,7 @@ import org.springframework.context.annotation.Configuration;
public class InitializrActuatorEndpointsAutoConfiguration {
@Bean
public BomRangesInfoContributor bomRangesInfoContributor(
InitializrMetadataProvider metadataProvider) {
public BomRangesInfoContributor bomRangesInfoContributor(InitializrMetadataProvider metadataProvider) {
return new BomRangesInfoContributor(metadataProvider);
}

View File

@@ -57,10 +57,9 @@ class InitializrStatsAutoConfiguration {
@Bean
@ConditionalOnBean(InitializrMetadataProvider.class)
public ProjectGenerationStatPublisher projectRequestStatHandler(
RestTemplateBuilder restTemplateBuilder) {
return new ProjectGenerationStatPublisher(new ProjectRequestDocumentFactory(),
this.statsProperties, restTemplateBuilder, statsRetryTemplate());
public ProjectGenerationStatPublisher projectRequestStatHandler(RestTemplateBuilder restTemplateBuilder) {
return new ProjectGenerationStatPublisher(new ProjectRequestDocumentFactory(), this.statsProperties,
restTemplateBuilder, statsRetryTemplate());
}
@Bean
@@ -70,8 +69,7 @@ class InitializrStatsAutoConfiguration {
ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
backOffPolicy.setInitialInterval(3000L);
backOffPolicy.setMultiplier(3);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(
this.statsProperties.getElastic().getMaxAttempts(),
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(this.statsProperties.getElastic().getMaxAttempts(),
Collections.singletonMap(Exception.class, true));
retryTemplate.setBackOffPolicy(backOffPolicy);
retryTemplate.setRetryPolicy(retryPolicy);

View File

@@ -41,18 +41,16 @@ public class BomRangesInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
Map<String, Object> details = new LinkedHashMap<>();
this.metadataProvider.get().getConfiguration().getEnv().getBoms()
.forEach((k, v) -> {
if (v.getMappings() != null && !v.getMappings().isEmpty()) {
Map<String, Object> bom = new LinkedHashMap<>();
v.getMappings().forEach((it) -> {
String requirement = "Spring Boot "
+ it.determineVersionRangeRequirement();
bom.put(it.getVersion(), requirement);
});
details.put(k, bom);
}
this.metadataProvider.get().getConfiguration().getEnv().getBoms().forEach((k, v) -> {
if (v.getMappings() != null && !v.getMappings().isEmpty()) {
Map<String, Object> bom = new LinkedHashMap<>();
v.getMappings().forEach((it) -> {
String requirement = "Spring Boot " + it.determineVersionRangeRequirement();
bom.put(it.getVersion(), requirement);
});
details.put(k, bom);
}
});
if (!details.isEmpty()) {
builder.withDetail("bom-ranges", details);
}

View File

@@ -65,8 +65,7 @@ public class DependencyRangesInfoContributor implements InfoContributor {
});
if (!dep.isEmpty()) {
if (dependency.getRange() == null) {
boolean openRange = dep.values().stream()
.anyMatch((v) -> v.getHigherVersion() == null);
boolean openRange = dep.values().stream().anyMatch((v) -> v.getHigherVersion() == null);
if (!openRange) {
Version higher = getHigher(dep);
dep.put("managed", new VersionRange(higher));

View File

@@ -44,8 +44,7 @@ import org.springframework.web.util.UriComponentsBuilder;
*/
public class ProjectGenerationStatPublisher {
private static final Log logger = LogFactory
.getLog(ProjectGenerationStatPublisher.class);
private static final Log logger = LogFactory.getLog(ProjectGenerationStatPublisher.class);
private final ProjectRequestDocumentFactory documentFactory;
@@ -58,15 +57,12 @@ public class ProjectGenerationStatPublisher {
private final RetryTemplate retryTemplate;
public ProjectGenerationStatPublisher(ProjectRequestDocumentFactory documentFactory,
StatsProperties statsProperties, RestTemplateBuilder restTemplateBuilder,
RetryTemplate retryTemplate) {
StatsProperties statsProperties, RestTemplateBuilder restTemplateBuilder, RetryTemplate retryTemplate) {
this.documentFactory = documentFactory;
this.objectMapper = createObjectMapper();
StatsProperties.Elastic elastic = statsProperties.getElastic();
UriComponentsBuilder uriBuilder = UriComponentsBuilder
.fromUri(determineEntityUrl(elastic));
this.restTemplate = configureAuthorization(restTemplateBuilder, elastic,
uriBuilder).build();
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUri(determineEntityUrl(elastic));
this.restTemplate = configureAuthorization(restTemplateBuilder, elastic, uriBuilder).build();
this.requestUrl = uriBuilder.userInfo(null).build().toUri();
this.retryTemplate = retryTemplate;
}
@@ -82,8 +78,8 @@ public class ProjectGenerationStatPublisher {
}
json = toJson(document);
RequestEntity<String> request = RequestEntity.post(this.requestUrl)
.contentType(MediaType.APPLICATION_JSON).body(json);
RequestEntity<String> request = RequestEntity.post(this.requestUrl).contentType(MediaType.APPLICATION_JSON)
.body(json);
this.retryTemplate.execute((context) -> {
this.restTemplate.exchange(request, String.class);
@@ -91,9 +87,7 @@ public class ProjectGenerationStatPublisher {
});
}
catch (Exception ex) {
logger.warn(String.format(
"Failed to publish stat to index, document follows %n%n%s%n", json),
ex);
logger.warn(String.format("Failed to publish stat to index, document follows %n%n%s%n", json), ex);
}
}
@@ -121,25 +115,21 @@ public class ProjectGenerationStatPublisher {
this.requestUrl = requestUrl;
}
private static RestTemplateBuilder configureAuthorization(
RestTemplateBuilder restTemplateBuilder, Elastic elastic,
private static RestTemplateBuilder configureAuthorization(RestTemplateBuilder restTemplateBuilder, Elastic elastic,
UriComponentsBuilder uriComponentsBuilder) {
String userInfo = uriComponentsBuilder.build().getUserInfo();
if (StringUtils.hasText(userInfo)) {
String[] credentials = userInfo.split(":");
return restTemplateBuilder.basicAuthentication(credentials[0],
credentials[1]);
return restTemplateBuilder.basicAuthentication(credentials[0], credentials[1]);
}
else if (StringUtils.hasText(elastic.getUsername())) {
return restTemplateBuilder.basicAuthentication(elastic.getUsername(),
elastic.getPassword());
return restTemplateBuilder.basicAuthentication(elastic.getUsername(), elastic.getPassword());
}
return restTemplateBuilder;
}
private static URI determineEntityUrl(Elastic elastic) {
String entityUrl = elastic.getUri() + "/" + elastic.getIndexName() + "/"
+ elastic.getEntityName();
String entityUrl = elastic.getUri() + "/" + elastic.getIndexName() + "/" + elastic.getEntityName();
try {
return new URI(entityUrl);
}

View File

@@ -169,19 +169,14 @@ public class ProjectRequestDocument {
@Override
public String toString() {
return new StringJoiner(", ", ProjectRequestDocument.class.getSimpleName() + "[",
"]").add("generationTimestamp=" + this.generationTimestamp)
.add("type='" + this.type + "'")
.add("buildSystem='" + this.buildSystem + "'")
.add("groupId='" + this.groupId + "'")
.add("artifactId='" + this.artifactId + "'")
.add("javaVersion='" + this.javaVersion + "'")
.add("language='" + this.language + "'")
.add("packaging='" + this.packaging + "'")
.add("packageName='" + this.packageName + "'")
.add("version=" + this.version).add("client=" + this.client)
.add("dependencies=" + this.dependencies)
.add("errorState=" + this.errorState).toString();
return new StringJoiner(", ", ProjectRequestDocument.class.getSimpleName() + "[", "]")
.add("generationTimestamp=" + this.generationTimestamp).add("type='" + this.type + "'")
.add("buildSystem='" + this.buildSystem + "'").add("groupId='" + this.groupId + "'")
.add("artifactId='" + this.artifactId + "'").add("javaVersion='" + this.javaVersion + "'")
.add("language='" + this.language + "'").add("packaging='" + this.packaging + "'")
.add("packageName='" + this.packageName + "'").add("version=" + this.version)
.add("client=" + this.client).add("dependencies=" + this.dependencies)
.add("errorState=" + this.errorState).toString();
}
/**
@@ -198,8 +193,7 @@ public class ProjectRequestDocument {
public VersionInformation(Version version) {
this.id = version.toString();
this.major = String.format("%s", version.getMajor());
this.minor = (version.getMinor() != null)
? String.format("%s.%s", version.getMajor(), version.getMinor())
this.minor = (version.getMinor() != null) ? String.format("%s.%s", version.getMajor(), version.getMinor())
: null;
}
@@ -217,9 +211,8 @@ public class ProjectRequestDocument {
@Override
public String toString() {
return new StringJoiner(", ", "{", "}").add("id='" + this.id + "'")
.add("major='" + this.major + "'").add("minor='" + this.minor + "'")
.toString();
return new StringJoiner(", ", "{", "}").add("id='" + this.id + "'").add("major='" + this.major + "'")
.add("minor='" + this.minor + "'").toString();
}
}
@@ -263,8 +256,8 @@ public class ProjectRequestDocument {
@Override
public String toString() {
return new StringJoiner(", ", "{", "}").add("id='" + this.id + "'")
.add("values=" + this.values).add("count=" + this.count).toString();
return new StringJoiner(", ", "{", "}").add("id='" + this.id + "'").add("values=" + this.values)
.add("count=" + this.count).toString();
}
}
@@ -307,9 +300,8 @@ public class ProjectRequestDocument {
@Override
public String toString() {
return new StringJoiner(", ", "{", "}").add("id='" + this.id + "'")
.add("version='" + this.version + "'").add("ip='" + this.ip + "'")
.add("country='" + this.country + "'").toString();
return new StringJoiner(", ", "{", "}").add("id='" + this.id + "'").add("version='" + this.version + "'")
.add("ip='" + this.ip + "'").add("country='" + this.country + "'").toString();
}
}
@@ -388,10 +380,9 @@ public class ProjectRequestDocument {
@Override
public String toString() {
return new StringJoiner(", ", "{", "}").add("invalid=" + this.invalid)
.add("javaVersion=" + this.javaVersion)
.add("language=" + this.language).add("packaging=" + this.packaging)
.add("type=" + this.type).add("dependencies=" + this.dependencies)
.add("message='" + this.message + "'").toString();
.add("javaVersion=" + this.javaVersion).add("language=" + this.language)
.add("packaging=" + this.packaging).add("type=" + this.type)
.add("dependencies=" + this.dependencies).add("message='" + this.message + "'").toString();
}
}
@@ -419,8 +410,7 @@ public class ProjectRequestDocument {
@Override
public String toString() {
return new StringJoiner(", ", "{", "}").add(String.join(", ", this.values))
.toString();
return new StringJoiner(", ", "{", "}").add(String.join(", ", this.values)).toString();
}
}

View File

@@ -59,8 +59,7 @@ public class ProjectRequestDocumentFactory {
}
document.setLanguage(request.getLanguage());
if (StringUtils.hasText(request.getLanguage())
&& metadata.getLanguages().get(request.getLanguage()) == null) {
if (StringUtils.hasText(request.getLanguage()) && metadata.getLanguages().get(request.getLanguage()) == null) {
document.triggerError().setLanguage(true);
}
@@ -72,8 +71,7 @@ public class ProjectRequestDocumentFactory {
document.setType(request.getType());
document.setBuildSystem(determineBuildSystem(request));
if (StringUtils.hasText(request.getType())
&& metadata.getTypes().get(request.getType()) == null) {
if (StringUtils.hasText(request.getType()) && metadata.getTypes().get(request.getType()) == null) {
document.triggerError().setType(true);
}
@@ -82,11 +80,9 @@ public class ProjectRequestDocumentFactory {
dependencies.addAll(request.getStyle());
dependencies.addAll(request.getDependencies());
List<String> validDependencies = dependencies.stream()
.filter((id) -> metadata.getDependencies().get(id) != null)
.collect(Collectors.toList());
.filter((id) -> metadata.getDependencies().get(id) != null).collect(Collectors.toList());
document.setDependencies(new DependencyInformation(validDependencies));
List<String> invalidDependencies = dependencies.stream()
.filter((id) -> (!validDependencies.contains(id)))
List<String> invalidDependencies = dependencies.stream().filter((id) -> (!validDependencies.contains(id)))
.collect(Collectors.toList());
if (!invalidDependencies.isEmpty()) {
document.triggerError().triggerInvalidDependencies(invalidDependencies);
@@ -140,8 +136,7 @@ public class ProjectRequestDocumentFactory {
private String determineIp(WebProjectRequest request) {
String candidate = (String) request.getParameters().get("cf-connecting-ip");
return (StringUtils.hasText(candidate)) ? candidate
: (String) request.getParameters().get("x-forwarded-for");
return (StringUtils.hasText(candidate)) ? candidate : (String) request.getParameters().get("x-forwarded-for");
}
private String determineCountry(WebProjectRequest request) {

View File

@@ -38,8 +38,7 @@ class ActuatorIntegrationTests extends AbstractFullStackInitializrIntegrationTes
@Test
void infoHasExternalProperties() {
String body = getRestTemplate().getForObject(createUrl("/actuator/info"),
String.class);
String body = getRestTemplate().getForObject(createUrl("/actuator/info"), String.class);
assertThat(body).contains("\"spring-boot\"");
assertThat(body).contains("\"version\":\"2.1.4.RELEASE\"");
}

View File

@@ -36,21 +36,17 @@ import static org.assertj.core.api.Assertions.assertThat;
class InitializrActuatorEndpointsAutoConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class,
InitializrAutoConfiguration.class,
RestTemplateAutoConfiguration.class,
InitializrActuatorEndpointsAutoConfiguration.class));
.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, InitializrAutoConfiguration.class,
RestTemplateAutoConfiguration.class, InitializrActuatorEndpointsAutoConfiguration.class));
@Test
void autoConfigRegistersBomRangesInfoContributor() {
this.contextRunner.run((context) -> assertThat(context)
.hasSingleBean(BomRangesInfoContributor.class));
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(BomRangesInfoContributor.class));
}
@Test
void autoConfigRegistersDependencyRangesInfoContributor() {
this.contextRunner.run((context) -> assertThat(context)
.hasSingleBean(DependencyRangesInfoContributor.class));
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(DependencyRangesInfoContributor.class));
}
}

View File

@@ -48,32 +48,25 @@ import static org.mockito.Mockito.mock;
class InitializrStatsAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class,
InitializrAutoConfiguration.class,
RestTemplateAutoConfiguration.class,
InitializrStatsAutoConfiguration.class));
.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, InitializrAutoConfiguration.class,
RestTemplateAutoConfiguration.class, InitializrStatsAutoConfiguration.class));
@Test
void autoConfigRegistersProjectGenerationStatPublisher() {
this.contextRunner
.withPropertyValues("initializr.stats.elastic.uri=http://localhost:9200")
.run((context) -> assertThat(context)
.hasSingleBean(ProjectGenerationStatPublisher.class));
this.contextRunner.withPropertyValues("initializr.stats.elastic.uri=http://localhost:9200")
.run((context) -> assertThat(context).hasSingleBean(ProjectGenerationStatPublisher.class));
}
@Test
void autoConfigRegistersRetryTemplate() {
this.contextRunner
.withPropertyValues("initializr.stats.elastic.uri=http://localhost:9200")
this.contextRunner.withPropertyValues("initializr.stats.elastic.uri=http://localhost:9200")
.run((context) -> assertThat(context).hasSingleBean(RetryTemplate.class));
}
@Test
void statsRetryTemplateConditionalOnMissingBean() {
this.contextRunner
.withUserConfiguration(CustomStatsRetryTemplateConfiguration.class)
.withPropertyValues("initializr.stats.elastic.uri=http://localhost:9200")
.run((context) -> {
this.contextRunner.withUserConfiguration(CustomStatsRetryTemplateConfiguration.class)
.withPropertyValues("initializr.stats.elastic.uri=http://localhost:9200").run((context) -> {
assertThat(context).hasSingleBean(RetryTemplate.class);
RetryTemplate retryTemplate = context.getBean(RetryTemplate.class);
ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils
@@ -85,15 +78,11 @@ class InitializrStatsAutoConfigurationTests {
@Test
void customRestTemplateBuilderIsUsed() {
this.contextRunner.withUserConfiguration(CustomRestTemplateConfiguration.class)
.withPropertyValues("initializr.stats.elastic.uri=http://localhost:9200")
.run((context) -> {
assertThat(context)
.hasSingleBean(ProjectGenerationStatPublisher.class);
.withPropertyValues("initializr.stats.elastic.uri=http://localhost:9200").run((context) -> {
assertThat(context).hasSingleBean(ProjectGenerationStatPublisher.class);
RestTemplate restTemplate = (RestTemplate) new DirectFieldAccessor(
context.getBean(ProjectGenerationStatPublisher.class))
.getPropertyValue("restTemplate");
assertThat(restTemplate.getErrorHandler())
.isSameAs(CustomRestTemplateConfiguration.errorHandler);
context.getBean(ProjectGenerationStatPublisher.class)).getPropertyValue("restTemplate");
assertThat(restTemplate.getErrorHandler()).isSameAs(CustomRestTemplateConfiguration.errorHandler);
});
}
@@ -125,8 +114,7 @@ class InitializrStatsAutoConfigurationTests {
@Import(InfrastructureConfiguration.class)
static class CustomRestTemplateConfiguration {
private static final ResponseErrorHandler errorHandler = mock(
ResponseErrorHandler.class);
private static final ResponseErrorHandler errorHandler = mock(ResponseErrorHandler.class);
@Bean
public RestTemplateCustomizer testRestTemplateCustomizer() {

View File

@@ -38,8 +38,7 @@ class BomRangesInfoContributorTests {
@Test
void noBom() {
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
.build();
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().build();
Info info = getInfo(metadata);
assertThat(info.getDetails()).doesNotContainKeys("bom-ranges");
}
@@ -47,8 +46,7 @@ class BomRangesInfoContributorTests {
@Test
void noMapping() {
BillOfMaterials bom = BillOfMaterials.create("com.example", "bom", "1.0.0");
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
.addBom("foo", bom).build();
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().addBom("foo", bom).build();
Info info = getInfo(metadata);
assertThat(info.getDetails()).doesNotContainKeys("bom-ranges");
}
@@ -56,29 +54,23 @@ class BomRangesInfoContributorTests {
@Test
void withMappings() {
BillOfMaterials bom = BillOfMaterials.create("com.example", "bom", "1.0.0");
bom.getMappings().add(
BillOfMaterials.Mapping.create("[1.3.0.RELEASE,1.3.8.RELEASE]", "1.1.0"));
bom.getMappings().add(
BillOfMaterials.Mapping.create("1.3.8.BUILD-SNAPSHOT", "1.1.1-SNAPSHOT"));
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
.addBom("foo", bom).build();
bom.getMappings().add(BillOfMaterials.Mapping.create("[1.3.0.RELEASE,1.3.8.RELEASE]", "1.1.0"));
bom.getMappings().add(BillOfMaterials.Mapping.create("1.3.8.BUILD-SNAPSHOT", "1.1.1-SNAPSHOT"));
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().addBom("foo", bom).build();
Info info = getInfo(metadata);
assertThat(info.getDetails()).containsKeys("bom-ranges");
@SuppressWarnings("unchecked")
Map<String, Object> ranges = (Map<String, Object>) info.getDetails()
.get("bom-ranges");
Map<String, Object> ranges = (Map<String, Object>) info.getDetails().get("bom-ranges");
assertThat(ranges).containsOnlyKeys("foo");
@SuppressWarnings("unchecked")
Map<String, Object> foo = (Map<String, Object>) ranges.get("foo");
assertThat(foo).containsExactly(
entry("1.1.0", "Spring Boot >=1.3.0.RELEASE and <=1.3.8.RELEASE"),
assertThat(foo).containsExactly(entry("1.1.0", "Spring Boot >=1.3.0.RELEASE and <=1.3.8.RELEASE"),
entry("1.1.1-SNAPSHOT", "Spring Boot >=1.3.8.BUILD-SNAPSHOT"));
}
private static Info getInfo(InitializrMetadata metadata) {
Info.Builder builder = new Info.Builder();
new BomRangesInfoContributor(new SimpleInitializrMetadataProvider(metadata))
.contribute(builder);
new BomRangesInfoContributor(new SimpleInitializrMetadataProvider(metadata)).contribute(builder);
return builder.build();
}

View File

@@ -39,30 +39,26 @@ class DependencyRangesInfoContributorTests {
@Test
void noDependencyWithVersion() {
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
.build();
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().build();
Info info = getInfo(metadata);
assertThat(info.getDetails()).doesNotContainKeys("dependency-ranges");
}
@Test
void dependencyWithNoMapping() {
Dependency dependency = Dependency.withId("foo", "com.example", "foo",
"1.2.3.RELEASE");
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
.addDependencyGroup("foo", dependency).build();
Dependency dependency = Dependency.withId("foo", "com.example", "foo", "1.2.3.RELEASE");
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().addDependencyGroup("foo", dependency)
.build();
Info info = getInfo(metadata);
assertThat(info.getDetails()).doesNotContainKeys("dependency-ranges");
}
@Test
void dependencyWithRangeOnArtifact() {
Dependency dependency = Dependency.withId("foo", "com.example", "foo",
"1.2.3.RELEASE");
dependency.getMappings().add(Dependency.Mapping
.create("[1.1.0.RELEASE, 1.2.0.RELEASE)", null, "foo2", null));
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
.addDependencyGroup("foo", dependency).build();
Dependency dependency = Dependency.withId("foo", "com.example", "foo", "1.2.3.RELEASE");
dependency.getMappings().add(Dependency.Mapping.create("[1.1.0.RELEASE, 1.2.0.RELEASE)", null, "foo2", null));
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().addDependencyGroup("foo", dependency)
.build();
Info info = getInfo(metadata);
assertThat(info.getDetails()).doesNotContainKeys("dependency-ranges");
}
@@ -70,67 +66,60 @@ class DependencyRangesInfoContributorTests {
@Test
void dependencyWithRangeAndBom() {
BillOfMaterials bom = BillOfMaterials.create("com.example", "bom", "1.0.0");
Dependency dependency = Dependency.withId("foo", "com.example", "foo",
"1.2.3.RELEASE");
dependency.getMappings().add(Dependency.Mapping
.create("[1.1.0.RELEASE, 1.2.0.RELEASE)", null, null, "0.1.0.RELEASE"));
Dependency dependency = Dependency.withId("foo", "com.example", "foo", "1.2.3.RELEASE");
dependency.getMappings()
.add(Dependency.Mapping.create("[1.1.0.RELEASE, 1.2.0.RELEASE)", null, null, "0.1.0.RELEASE"));
dependency.setBom("bom");
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
.addBom("bom", bom).addDependencyGroup("foo", dependency).build();
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().addBom("bom", bom)
.addDependencyGroup("foo", dependency).build();
Info info = getInfo(metadata);
assertThat(info.getDetails()).doesNotContainKeys("dependency-ranges");
}
@Test
void dependencyNoMappingSimpleRange() {
Dependency dependency = Dependency.withId("foo", "com.example", "foo",
"1.2.3.RELEASE");
Dependency dependency = Dependency.withId("foo", "com.example", "foo", "1.2.3.RELEASE");
dependency.setVersionRange("[1.1.0.RELEASE, 1.5.0.RELEASE)");
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
.addDependencyGroup("foo", dependency).build();
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().addDependencyGroup("foo", dependency)
.build();
Info info = getInfo(metadata);
assertThat(info.getDetails()).containsKeys("dependency-ranges");
@SuppressWarnings("unchecked")
Map<String, Object> ranges = (Map<String, Object>) info.getDetails()
.get("dependency-ranges");
Map<String, Object> ranges = (Map<String, Object>) info.getDetails().get("dependency-ranges");
assertThat(ranges).containsOnlyKeys("foo");
@SuppressWarnings("unchecked")
Map<String, Object> foo = (Map<String, Object>) ranges.get("foo");
assertThat(foo).containsExactly(
entry("1.2.3.RELEASE", "Spring Boot >=1.1.0.RELEASE and <1.5.0.RELEASE"));
assertThat(foo).containsExactly(entry("1.2.3.RELEASE", "Spring Boot >=1.1.0.RELEASE and <1.5.0.RELEASE"));
}
@Test
void dependencyWithMappingAndOpenRange() {
Dependency dependency = Dependency.withId("foo", null, null, "0.3.0.RELEASE");
dependency.getMappings().add(Dependency.Mapping
.create("[1.1.0.RELEASE, 1.2.0.RELEASE)", null, null, "0.1.0.RELEASE"));
dependency.getMappings().add(
Dependency.Mapping.create("1.2.0.RELEASE", null, null, "0.2.0.RELEASE"));
dependency.getMappings()
.add(Dependency.Mapping.create("[1.1.0.RELEASE, 1.2.0.RELEASE)", null, null, "0.1.0.RELEASE"));
dependency.getMappings().add(Dependency.Mapping.create("1.2.0.RELEASE", null, null, "0.2.0.RELEASE"));
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
.addDependencyGroup("test", dependency).build();
Info info = getInfo(metadata);
assertDependencyId(info, "foo");
Map<String, Object> foo = getDependencyRangeInfo(info, "foo");
assertThat(foo).containsExactly(
entry("0.1.0.RELEASE", "Spring Boot >=1.1.0.RELEASE and <1.2.0.RELEASE"),
assertThat(foo).containsExactly(entry("0.1.0.RELEASE", "Spring Boot >=1.1.0.RELEASE and <1.2.0.RELEASE"),
entry("0.2.0.RELEASE", "Spring Boot >=1.2.0.RELEASE"));
}
@Test
void dependencyWithMappingAndNoOpenRange() {
Dependency dependency = Dependency.withId("foo", null, null, "0.3.0.RELEASE");
dependency.getMappings().add(Dependency.Mapping
.create("[1.1.0.RELEASE, 1.2.0.RELEASE)", null, null, "0.1.0.RELEASE"));
dependency.getMappings().add(Dependency.Mapping
.create("[1.2.0.RELEASE, 1.3.0.RELEASE)", null, null, "0.2.0.RELEASE"));
dependency.getMappings()
.add(Dependency.Mapping.create("[1.1.0.RELEASE, 1.2.0.RELEASE)", null, null, "0.1.0.RELEASE"));
dependency.getMappings()
.add(Dependency.Mapping.create("[1.2.0.RELEASE, 1.3.0.RELEASE)", null, null, "0.2.0.RELEASE"));
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
.addDependencyGroup("test", dependency).build();
Info info = getInfo(metadata);
assertDependencyId(info, "foo");
Map<String, Object> foo = getDependencyRangeInfo(info, "foo");
assertThat(foo).containsExactly(
entry("0.1.0.RELEASE", "Spring Boot >=1.1.0.RELEASE and <1.2.0.RELEASE"),
assertThat(foo).containsExactly(entry("0.1.0.RELEASE", "Spring Boot >=1.1.0.RELEASE and <1.2.0.RELEASE"),
entry("0.2.0.RELEASE", "Spring Boot >=1.2.0.RELEASE and <1.3.0.RELEASE"),
entry("managed", "Spring Boot >=1.3.0.RELEASE"));
}
@@ -138,23 +127,20 @@ class DependencyRangesInfoContributorTests {
@SuppressWarnings("unchecked")
private void assertDependencyId(Info info, String... dependencyIds) {
assertThat(info.getDetails()).containsKeys("dependency-ranges");
Map<String, Object> ranges = (Map<String, Object>) info.getDetails()
.get("dependency-ranges");
Map<String, Object> ranges = (Map<String, Object>) info.getDetails().get("dependency-ranges");
assertThat(ranges).containsOnlyKeys(dependencyIds);
}
@SuppressWarnings("unchecked")
private Map<String, Object> getDependencyRangeInfo(Info info, String id) {
assertThat(info.getDetails()).containsKeys("dependency-ranges");
Map<String, Object> ranges = (Map<String, Object>) info.getDetails()
.get("dependency-ranges");
Map<String, Object> ranges = (Map<String, Object>) info.getDetails().get("dependency-ranges");
return (Map<String, Object>) ranges.get(id);
}
private static Info getInfo(InitializrMetadata metadata) {
Info.Builder builder = new Info.Builder();
new DependencyRangesInfoContributor(
new SimpleInitializrMetadataProvider(metadata)).contribute(builder);
new DependencyRangesInfoContributor(new SimpleInitializrMetadataProvider(metadata)).contribute(builder);
return builder.build();
}

View File

@@ -47,8 +47,7 @@ import static org.assertj.core.api.Assertions.fail;
*/
@Import(StatsMockController.class)
@ActiveProfiles({ "test-default", "test-custom-stats" })
class MainControllerStatsIntegrationTests
extends AbstractFullStackInitializrIntegrationTests {
class MainControllerStatsIntegrationTests extends AbstractFullStackInitializrIntegrationTests {
@Autowired
private StatsMockController statsMockController;
@@ -60,8 +59,8 @@ class MainControllerStatsIntegrationTests
public void setup() {
this.statsMockController.stats.clear();
// Make sure our mock is going to be invoked with the stats
this.projectGenerationStatPublisher.updateRequestUrl(
URI.create("http://localhost:" + this.port + "/elastic/test/my-entity"));
this.projectGenerationStatPublisher
.updateRequestUrl(URI.create("http://localhost:" + this.port + "/elastic/test/my-entity"));
}
@Test
@@ -100,8 +99,7 @@ class MainControllerStatsIntegrationTests
StatsMockController.Content content = this.statsMockController.stats.get(0);
JsonNode json = parseJson(content.json);
assertThat(json.has("requestIp")).as("requestIp property should not be set")
.isFalse();
assertThat(json.has("requestIp")).as("requestIp property should not be set").isFalse();
}
@Test
@@ -113,8 +111,7 @@ class MainControllerStatsIntegrationTests
StatsMockController.Content content = this.statsMockController.stats.get(0);
JsonNode json = parseJson(content.json);
assertThat(json.get("client").get("ip").textValue()).as("Wrong requestIp")
.isEqualTo("10.0.0.123");
assertThat(json.get("client").get("ip").textValue()).as("Wrong requestIp").isEqualTo("10.0.0.123");
}
@Test
@@ -126,22 +123,20 @@ class MainControllerStatsIntegrationTests
StatsMockController.Content content = this.statsMockController.stats.get(0);
JsonNode json = parseJson(content.json);
assertThat(json.has("requestIpv4"))
.as("requestIpv4 property should not be set if value is not a valid IPv4")
assertThat(json.has("requestIpv4")).as("requestIpv4 property should not be set if value is not a valid IPv4")
.isFalse();
}
@Test
void requestCountryIsNotSetWhenHeaderIsSetToXX() throws Exception {
RequestEntity<?> request = RequestEntity.get(new URI(createUrl("/starter.zip")))
.header("cf-ipcountry", "XX").build();
RequestEntity<?> request = RequestEntity.get(new URI(createUrl("/starter.zip"))).header("cf-ipcountry", "XX")
.build();
getRestTemplate().exchange(request, String.class);
assertThat(this.statsMockController.stats).as("No stat got generated").hasSize(1);
StatsMockController.Content content = this.statsMockController.stats.get(0);
JsonNode json = parseJson(content.json);
assertThat(json.has("requestCountry"))
.as("requestCountry property should not be set if value is set to xx")
assertThat(json.has("requestCountry")).as("requestCountry property should not be set if value is set to xx")
.isFalse();
}
@@ -170,11 +165,10 @@ class MainControllerStatsIntegrationTests
@Test
void errorPublishingStatsDoesNotBubbleUp() {
this.projectGenerationStatPublisher.updateRequestUrl(
URI.create("http://localhost:" + this.port + "/elastic-error"));
this.projectGenerationStatPublisher
.updateRequestUrl(URI.create("http://localhost:" + this.port + "/elastic-error"));
downloadArchive("/starter.zip");
assertThat(this.statsMockController.stats).as("No stat should be available")
.isEmpty();
assertThat(this.statsMockController.stats).as("No stat should be available").isEmpty();
}
@RestController

View File

@@ -64,10 +64,9 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat
*/
class ProjectGenerationStatPublisherTests {
private final InitializrMetadata metadata = InitializrMetadataTestBuilder
.withDefaults().addDependencyGroup("core", "security", "validation", "aop")
.addDependencyGroup("web", "web", "data-rest", "jersey")
.addDependencyGroup("data", "data-jpa", "jdbc")
private final InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
.addDependencyGroup("core", "security", "validation", "aop")
.addDependencyGroup("web", "web", "data-rest", "jersey").addDependencyGroup("data", "data-jpa", "jdbc")
.addDependencyGroup("database", "h2", "mysql").build();
private RetryTemplate retryTemplate;
@@ -84,10 +83,9 @@ class ProjectGenerationStatPublisherTests {
private void configureService(StatsProperties properties) {
ProjectRequestDocumentFactory documentFactory = new ProjectRequestDocumentFactory();
this.retryTemplate = new RetryTemplate();
this.statPublisher = new ProjectGenerationStatPublisher(documentFactory,
properties, new RestTemplateBuilder(), this.retryTemplate);
this.mockServer = MockRestServiceServer
.createServer(this.statPublisher.getRestTemplate());
this.statPublisher = new ProjectGenerationStatPublisher(documentFactory, properties, new RestTemplateBuilder(),
this.retryTemplate);
this.mockServer = MockRestServiceServer.createServer(this.statPublisher.getRestTemplate());
}
@Test
@@ -127,19 +125,16 @@ class ProjectGenerationStatPublisherTests {
properties.getElastic().setUri("https://example.com/test/");
configureService(properties);
testAuthorization("https://example.com/test/initializr/request",
(request) -> assertThat(request.getHeaders().containsKey("Authorization"))
.isFalse());
(request) -> assertThat(request.getHeaders().containsKey("Authorization")).isFalse());
}
private void testAuthorization(String expectedUri,
RequestMatcher authorizationMatcher) {
private void testAuthorization(String expectedUri, RequestMatcher authorizationMatcher) {
ProjectRequest request = createProjectRequest();
request.setGroupId("com.example.foo");
request.setArtifactId("my-project");
this.mockServer.expect(requestTo(expectedUri)).andExpect(method(HttpMethod.POST))
.andExpect(authorizationMatcher)
.andRespond(withStatus(HttpStatus.CREATED)
.body(mockResponse(UUID.randomUUID().toString(), true))
.andRespond(withStatus(HttpStatus.CREATED).body(mockResponse(UUID.randomUUID().toString(), true))
.contentType(MediaType.APPLICATION_JSON));
handleEvent(request);
this.mockServer.verify();
@@ -159,10 +154,8 @@ class ProjectGenerationStatPublisherTests {
request.getParameters().put("cf-ipcountry", "BE");
this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
.andExpect(method(HttpMethod.POST))
.andExpect(json("stat/request-simple.json"))
.andRespond(withStatus(HttpStatus.CREATED)
.body(mockResponse(UUID.randomUUID().toString(), true))
.andExpect(method(HttpMethod.POST)).andExpect(json("stat/request-simple.json"))
.andRespond(withStatus(HttpStatus.CREATED).body(mockResponse(UUID.randomUUID().toString(), true))
.contentType(MediaType.APPLICATION_JSON));
handleEvent(request);
@@ -180,10 +173,8 @@ class ProjectGenerationStatPublisherTests {
request.setLanguage("java");
this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
.andExpect(method(HttpMethod.POST))
.andExpect(json("stat/request-no-client.json"))
.andRespond(withStatus(HttpStatus.CREATED)
.body(mockResponse(UUID.randomUUID().toString(), true))
.andExpect(method(HttpMethod.POST)).andExpect(json("stat/request-no-client.json"))
.andRespond(withStatus(HttpStatus.CREATED).body(mockResponse(UUID.randomUUID().toString(), true))
.contentType(MediaType.APPLICATION_JSON));
handleEvent(request);
@@ -201,10 +192,8 @@ class ProjectGenerationStatPublisherTests {
request.setLanguage("java");
this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
.andExpect(method(HttpMethod.POST))
.andExpect(json("stat/request-invalid-type.json"))
.andRespond(withStatus(HttpStatus.CREATED)
.body(mockResponse(UUID.randomUUID().toString(), true))
.andExpect(method(HttpMethod.POST)).andExpect(json("stat/request-invalid-type.json"))
.andRespond(withStatus(HttpStatus.CREATED).body(mockResponse(UUID.randomUUID().toString(), true))
.contentType(MediaType.APPLICATION_JSON));
handleEvent(request);
@@ -222,10 +211,8 @@ class ProjectGenerationStatPublisherTests {
request.setLanguage("c");
this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
.andExpect(method(HttpMethod.POST))
.andExpect(json("stat/request-invalid-language.json"))
.andRespond(withStatus(HttpStatus.CREATED)
.body(mockResponse(UUID.randomUUID().toString(), true))
.andExpect(method(HttpMethod.POST)).andExpect(json("stat/request-invalid-language.json"))
.andRespond(withStatus(HttpStatus.CREATED).body(mockResponse(UUID.randomUUID().toString(), true))
.contentType(MediaType.APPLICATION_JSON));
handleEvent(request);
@@ -244,10 +231,8 @@ class ProjectGenerationStatPublisherTests {
request.setJavaVersion("1.2");
this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
.andExpect(method(HttpMethod.POST))
.andExpect(json("stat/request-invalid-java-version.json"))
.andRespond(withStatus(HttpStatus.CREATED)
.body(mockResponse(UUID.randomUUID().toString(), true))
.andExpect(method(HttpMethod.POST)).andExpect(json("stat/request-invalid-java-version.json"))
.andRespond(withStatus(HttpStatus.CREATED).body(mockResponse(UUID.randomUUID().toString(), true))
.contentType(MediaType.APPLICATION_JSON));
handleEvent(request);
@@ -265,10 +250,8 @@ class ProjectGenerationStatPublisherTests {
request.setLanguage("java");
this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
.andExpect(method(HttpMethod.POST))
.andExpect(json("stat/request-invalid-dependencies.json"))
.andRespond(withStatus(HttpStatus.CREATED)
.body(mockResponse(UUID.randomUUID().toString(), true))
.andExpect(method(HttpMethod.POST)).andExpect(json("stat/request-invalid-dependencies.json"))
.andRespond(withStatus(HttpStatus.CREATED).body(mockResponse(UUID.randomUUID().toString(), true))
.contentType(MediaType.APPLICATION_JSON));
handleEvent(request);
@@ -280,17 +263,14 @@ class ProjectGenerationStatPublisherTests {
ProjectRequest request = createProjectRequest();
this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
.andExpect(method(HttpMethod.POST))
.andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));
.andExpect(method(HttpMethod.POST)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));
this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
.andExpect(method(HttpMethod.POST)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));
this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
.andExpect(method(HttpMethod.POST))
.andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));
this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
.andExpect(method(HttpMethod.POST))
.andRespond(withStatus(HttpStatus.CREATED)
.body(mockResponse(UUID.randomUUID().toString(), true))
.andRespond(withStatus(HttpStatus.CREATED).body(mockResponse(UUID.randomUUID().toString(), true))
.contentType(MediaType.APPLICATION_JSON));
handleEvent(request);
@@ -300,16 +280,13 @@ class ProjectGenerationStatPublisherTests {
@Test
void fatalErrorOnlyLogs() {
ProjectRequest request = createProjectRequest();
this.retryTemplate.setRetryPolicy(new SimpleRetryPolicy(2,
Collections.singletonMap(Exception.class, true)));
this.retryTemplate.setRetryPolicy(new SimpleRetryPolicy(2, Collections.singletonMap(Exception.class, true)));
this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
.andExpect(method(HttpMethod.POST))
.andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));
.andExpect(method(HttpMethod.POST)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));
this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
.andExpect(method(HttpMethod.POST))
.andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));
.andExpect(method(HttpMethod.POST)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));
handleEvent(request);
this.mockServer.verify();
@@ -326,10 +303,8 @@ class ProjectGenerationStatPublisherTests {
}
private static String mockResponse(String id, boolean created) {
return "{\"_index\":\"initializr\",\"_type\":\"request\",\"_id\":\"" + id
+ "\",\"_version\":1,\"_shards\""
+ ":{\"total\":1,\"successful\":1,\"failed\":0},\"created\":" + created
+ "}";
return "{\"_index\":\"initializr\",\"_type\":\"request\",\"_id\":\"" + id + "\",\"_version\":1,\"_shards\""
+ ":{\"total\":1,\"successful\":1,\"failed\":0},\"created\":" + created + "}";
}
private static StatsProperties createProperties() {
@@ -359,18 +334,15 @@ class ProjectGenerationStatPublisherTests {
private static void assertJsonContent(String expected, String actual) {
try {
JSONAssert.assertEquals(expected, actual, new CustomComparator(
JSONCompareMode.STRICT,
JSONAssert.assertEquals(expected, actual, new CustomComparator(JSONCompareMode.STRICT,
Customization.customization("generationTimestamp", (o1, o2) -> {
Instant timestamp = Instant.ofEpochMilli((long) o1);
return timestamp
.isAfter(Instant.now().minus(2, ChronoUnit.SECONDS))
return timestamp.isAfter(Instant.now().minus(2, ChronoUnit.SECONDS))
&& timestamp.isBefore(Instant.now());
})));
}
catch (JSONException ex) {
throw new AssertionError(
"Failed to parse expected or actual JSON request content", ex);
throw new AssertionError("Failed to parse expected or actual JSON request content", ex);
}
}

View File

@@ -35,10 +35,9 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
class ProjectRequestDocumentFactoryTests {
private final InitializrMetadata metadata = InitializrMetadataTestBuilder
.withDefaults().addDependencyGroup("core", "security", "validation", "aop")
.addDependencyGroup("web", "web", "data-rest", "jersey")
.addDependencyGroup("data", "data-jpa", "jdbc")
private final InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
.addDependencyGroup("core", "security", "validation", "aop")
.addDependencyGroup("web", "web", "data-rest", "jersey").addDependencyGroup("data", "data-jpa", "jdbc")
.addDependencyGroup("database", "h2", "mysql").build();
private final ProjectRequestDocumentFactory factory = new ProjectRequestDocumentFactory();
@@ -224,8 +223,7 @@ class ProjectRequestDocumentFactoryTests {
request.setDependencies(Arrays.asList("web", "invalid", "data-jpa", "invalid-2"));
ProjectGeneratedEvent event = createProjectGeneratedEvent(request);
ProjectRequestDocument document = this.factory.createDocument(event);
assertThat(document.getDependencies().getValues()).containsExactly("web",
"data-jpa");
assertThat(document.getDependencies().getValues()).containsExactly("web", "data-jpa");
assertThat(document.getErrorState().isInvalid()).isTrue();
assertThat(document.getErrorState().getJavaVersion()).isNull();
assertThat(document.getErrorState().getLanguage()).isNull();
@@ -233,8 +231,7 @@ class ProjectRequestDocumentFactoryTests {
assertThat(document.getErrorState().getType()).isNull();
assertThat(document.getErrorState().getDependencies()).isNotNull();
assertThat(document.getErrorState().getDependencies().isInvalid()).isTrue();
assertThat(document.getErrorState().getDependencies().getValues())
.containsExactly("invalid", "invalid-2");
assertThat(document.getErrorState().getDependencies().getValues()).containsExactly("invalid", "invalid-2");
}
@Test

View File

@@ -37,15 +37,14 @@ public class MetricsAssert {
}
public MetricsAssert hasValue(long value, String... metrics) {
Arrays.asList(metrics).forEach(
(metric) -> assertThat(this.meterRegistry.get(metric).counter().count())
.isEqualTo(value));
Arrays.asList(metrics)
.forEach((metric) -> assertThat(this.meterRegistry.get(metric).counter().count()).isEqualTo(value));
return this;
}
public MetricsAssert hasNoValue(String... metrics) {
Arrays.asList(metrics).forEach((metric) -> assertThat(
Search.in(this.meterRegistry).name((n) -> n.startsWith(metric)).counter())
Arrays.asList(metrics).forEach(
(metric) -> assertThat(Search.in(this.meterRegistry).name((n) -> n.startsWith(metric)).counter())
.isNull());
return this;
}