mirror of
https://gitee.com/dcren/initializr.git
synced 2025-12-17 09:35:53 +08:00
Format source code
Closes gh-923
This commit is contained in:
@@ -35,16 +35,14 @@ import org.springframework.util.StringUtils;
|
||||
*
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
public class CloudfoundryEnvironmentPostProcessor
|
||||
implements EnvironmentPostProcessor, Ordered {
|
||||
public class CloudfoundryEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
|
||||
|
||||
private static final String PROPERTY_SOURCE_NAME = "defaultProperties";
|
||||
|
||||
private static final int ORDER = ConfigFileApplicationListener.DEFAULT_ORDER + 1;
|
||||
|
||||
@Override
|
||||
public void postProcessEnvironment(ConfigurableEnvironment environment,
|
||||
SpringApplication springApplication) {
|
||||
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication springApplication) {
|
||||
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
String uri = environment.getProperty("vcap.services.stats-index.credentials.uri");
|
||||
@@ -59,8 +57,7 @@ public class CloudfoundryEnvironmentPostProcessor
|
||||
return ORDER;
|
||||
}
|
||||
|
||||
private static void addOrReplace(MutablePropertySources propertySources,
|
||||
Map<String, Object> map) {
|
||||
private static void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) {
|
||||
MapPropertySource target = null;
|
||||
if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
|
||||
PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
|
||||
|
||||
@@ -70,8 +70,7 @@ import org.springframework.core.env.Environment;
|
||||
*/
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(InitializrProperties.class)
|
||||
@AutoConfigureAfter({ JacksonAutoConfiguration.class,
|
||||
RestTemplateAutoConfiguration.class })
|
||||
@AutoConfigureAfter({ JacksonAutoConfiguration.class, RestTemplateAutoConfiguration.class })
|
||||
public class InitializrAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@@ -97,8 +96,7 @@ public class InitializrAutoConfiguration {
|
||||
private Cache determineCache(Environment environment, CacheManager cacheManager) {
|
||||
if (cacheManager != null) {
|
||||
Binder binder = Binder.get(environment);
|
||||
boolean cache = binder.bind("spring.mustache.cache", Boolean.class)
|
||||
.orElse(true);
|
||||
boolean cache = binder.bind("spring.mustache.cache", Boolean.class).orElse(true);
|
||||
if (cache) {
|
||||
return cacheManager.getCache("initializr.templates");
|
||||
}
|
||||
@@ -108,21 +106,17 @@ public class InitializrAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public InitializrMetadataUpdateStrategy initializrMetadataUpdateStrategy(
|
||||
RestTemplateBuilder restTemplateBuilder, ObjectMapper objectMapper) {
|
||||
return new DefaultInitializrMetadataUpdateStrategy(restTemplateBuilder.build(),
|
||||
objectMapper);
|
||||
public InitializrMetadataUpdateStrategy initializrMetadataUpdateStrategy(RestTemplateBuilder restTemplateBuilder,
|
||||
ObjectMapper objectMapper) {
|
||||
return new DefaultInitializrMetadataUpdateStrategy(restTemplateBuilder.build(), objectMapper);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(InitializrMetadataProvider.class)
|
||||
public InitializrMetadataProvider initializrMetadataProvider(
|
||||
InitializrProperties properties,
|
||||
public InitializrMetadataProvider initializrMetadataProvider(InitializrProperties properties,
|
||||
InitializrMetadataUpdateStrategy initializrMetadataUpdateStrategy) {
|
||||
InitializrMetadata metadata = InitializrMetadataBuilder
|
||||
.fromInitializrProperties(properties).build();
|
||||
return new DefaultInitializrMetadataProvider(metadata,
|
||||
initializrMetadataUpdateStrategy);
|
||||
InitializrMetadata metadata = InitializrMetadataBuilder.fromInitializrProperties(properties).build();
|
||||
return new DefaultInitializrMetadataProvider(metadata, initializrMetadataUpdateStrategy);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -145,19 +139,16 @@ public class InitializrAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public MainController initializrMainController(
|
||||
InitializrMetadataProvider metadataProvider,
|
||||
TemplateRenderer templateRenderer,
|
||||
DependencyMetadataProvider dependencyMetadataProvider,
|
||||
public MainController initializrMainController(InitializrMetadataProvider metadataProvider,
|
||||
TemplateRenderer templateRenderer, DependencyMetadataProvider dependencyMetadataProvider,
|
||||
ProjectGenerationInvoker projectGenerationInvoker) {
|
||||
return new MainController(metadataProvider, templateRenderer,
|
||||
dependencyMetadataProvider, projectGenerationInvoker);
|
||||
return new MainController(metadataProvider, templateRenderer, dependencyMetadataProvider,
|
||||
projectGenerationInvoker);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public ProjectGenerationInvoker projectGenerationInvoker(
|
||||
ApplicationContext applicationContext,
|
||||
public ProjectGenerationInvoker projectGenerationInvoker(ApplicationContext applicationContext,
|
||||
ApplicationEventPublisher eventPublisher,
|
||||
ProjectRequestToDescriptionConverter projectRequestToDescriptionConverter) {
|
||||
return new ProjectGenerationInvoker(applicationContext, eventPublisher,
|
||||
@@ -187,8 +178,7 @@ public class InitializrAutoConfiguration {
|
||||
public JCacheManagerCustomizer initializrCacheManagerCustomizer() {
|
||||
return (cacheManager) -> {
|
||||
cacheManager.createCache("initializr.metadata",
|
||||
config().setExpiryPolicyFactory(
|
||||
CreatedExpiryPolicy.factoryOf(Duration.TEN_MINUTES)));
|
||||
config().setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.TEN_MINUTES)));
|
||||
cacheManager.createCache("initializr.dependency-metadata", config());
|
||||
cacheManager.createCache("initializr.project-resources", config());
|
||||
cacheManager.createCache("initializr.templates", config());
|
||||
@@ -196,8 +186,8 @@ public class InitializrAutoConfiguration {
|
||||
}
|
||||
|
||||
private MutableConfiguration<Object, Object> config() {
|
||||
return new MutableConfiguration<>().setStoreByValue(false)
|
||||
.setManagementEnabled(true).setStatisticsEnabled(true);
|
||||
return new MutableConfiguration<>().setStoreByValue(false).setManagementEnabled(true)
|
||||
.setStatisticsEnabled(true);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -36,16 +36,15 @@ class InitializrModule extends SimpleModule {
|
||||
addSerializer(new VersionPropertySerializer());
|
||||
}
|
||||
|
||||
private static class VersionPropertySerializer
|
||||
extends StdSerializer<VersionProperty> {
|
||||
private static class VersionPropertySerializer extends StdSerializer<VersionProperty> {
|
||||
|
||||
VersionPropertySerializer() {
|
||||
super(VersionProperty.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(VersionProperty value, JsonGenerator gen,
|
||||
SerializerProvider provider) throws IOException {
|
||||
public void serialize(VersionProperty value, JsonGenerator gen, SerializerProvider provider)
|
||||
throws IOException {
|
||||
gen.writeString(value.toStandardFormat());
|
||||
}
|
||||
|
||||
|
||||
@@ -49,24 +49,21 @@ public class InitializrWebConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
|
||||
configurer
|
||||
.defaultContentTypeStrategy(new CommandLineContentNegotiationStrategy());
|
||||
configurer.defaultContentTypeStrategy(new CommandLineContentNegotiationStrategy());
|
||||
}
|
||||
|
||||
/**
|
||||
* A command-line aware {@link ContentNegotiationStrategy} that forces the media type
|
||||
* to "text/plain" for compatible agents.
|
||||
*/
|
||||
private static class CommandLineContentNegotiationStrategy
|
||||
implements ContentNegotiationStrategy {
|
||||
private static class CommandLineContentNegotiationStrategy implements ContentNegotiationStrategy {
|
||||
|
||||
private final UrlPathHelper urlPathHelper = new UrlPathHelper();
|
||||
|
||||
@Override
|
||||
public List<MediaType> resolveMediaTypes(NativeWebRequest request)
|
||||
throws HttpMediaTypeNotAcceptableException {
|
||||
String path = this.urlPathHelper.getPathWithinApplication(
|
||||
request.getNativeRequest(HttpServletRequest.class));
|
||||
public List<MediaType> resolveMediaTypes(NativeWebRequest request) throws HttpMediaTypeNotAcceptableException {
|
||||
String path = this.urlPathHelper
|
||||
.getPathWithinApplication(request.getNativeRequest(HttpServletRequest.class));
|
||||
if (!StringUtils.hasText(path) || !path.equals("/")) { // Only care about "/"
|
||||
return MEDIA_TYPE_ALL_LIST;
|
||||
}
|
||||
@@ -74,8 +71,7 @@ public class InitializrWebConfig implements WebMvcConfigurer {
|
||||
if (userAgent != null) {
|
||||
Agent agent = Agent.fromUserAgent(userAgent);
|
||||
if (agent != null) {
|
||||
if (AgentId.CURL.equals(agent.getId())
|
||||
|| AgentId.HTTPIE.equals(agent.getId())) {
|
||||
if (AgentId.CURL.equals(agent.getId()) || AgentId.HTTPIE.equals(agent.getId())) {
|
||||
return Collections.singletonList(MediaType.TEXT_PLAIN);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,16 +41,12 @@ public class DependencyMetadataV21JsonMapper implements DependencyMetadataJsonMa
|
||||
public String write(DependencyMetadata metadata) {
|
||||
ObjectNode json = nodeFactory.objectNode();
|
||||
json.put("bootVersion", metadata.getBootVersion().toString());
|
||||
json.set("dependencies",
|
||||
mapNode(metadata.getDependencies().entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey,
|
||||
(entry) -> mapDependency(entry.getValue())))));
|
||||
json.set("repositories",
|
||||
mapNode(metadata.getRepositories().entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey,
|
||||
(entry) -> mapRepository(entry.getValue())))));
|
||||
json.set("boms", mapNode(metadata.getBoms().entrySet().stream().collect(Collectors
|
||||
.toMap(Map.Entry::getKey, (entry) -> mapBom(entry.getValue())))));
|
||||
json.set("dependencies", mapNode(metadata.getDependencies().entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, (entry) -> mapDependency(entry.getValue())))));
|
||||
json.set("repositories", mapNode(metadata.getRepositories().entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, (entry) -> mapRepository(entry.getValue())))));
|
||||
json.set("boms", mapNode(metadata.getBoms().entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, (entry) -> mapBom(entry.getValue())))));
|
||||
return json.toString();
|
||||
}
|
||||
|
||||
@@ -73,8 +69,7 @@ public class DependencyMetadataV21JsonMapper implements DependencyMetadataJsonMa
|
||||
|
||||
private static JsonNode mapRepository(Repository repo) {
|
||||
ObjectNode node = nodeFactory.objectNode();
|
||||
node.put("name", repo.getName())
|
||||
.put("url", (repo.getUrl() != null) ? repo.getUrl().toString() : null)
|
||||
node.put("name", repo.getName()).put("url", (repo.getUrl() != null) ? repo.getUrl().toString() : null)
|
||||
.put("snapshotEnabled", repo.isSnapshotsEnabled());
|
||||
return node;
|
||||
}
|
||||
|
||||
@@ -40,8 +40,8 @@ public class InitializrMetadataV21JsonMapper extends InitializrMetadataV2JsonMap
|
||||
private final TemplateVariables dependenciesVariables;
|
||||
|
||||
public InitializrMetadataV21JsonMapper() {
|
||||
this.dependenciesVariables = new TemplateVariables(new TemplateVariable(
|
||||
"bootVersion", TemplateVariable.VariableType.REQUEST_PARAM));
|
||||
this.dependenciesVariables = new TemplateVariables(
|
||||
new TemplateVariable("bootVersion", TemplateVariable.VariableType.REQUEST_PARAM));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -53,27 +53,17 @@ public class InitializrMetadataV2JsonMapper implements InitializrMetadataJsonMap
|
||||
|
||||
public InitializrMetadataV2JsonMapper() {
|
||||
this.templateVariables = new TemplateVariables(
|
||||
new TemplateVariable("dependencies",
|
||||
TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("packaging",
|
||||
TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("javaVersion",
|
||||
TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("language",
|
||||
TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("bootVersion",
|
||||
TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("groupId",
|
||||
TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("artifactId",
|
||||
TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("version",
|
||||
TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("dependencies", TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("packaging", TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("javaVersion", TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("language", TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("bootVersion", TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("groupId", TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("artifactId", TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("version", TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("name", TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("description",
|
||||
TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("packageName",
|
||||
TemplateVariable.VariableType.REQUEST_PARAM));
|
||||
new TemplateVariable("description", TemplateVariable.VariableType.REQUEST_PARAM),
|
||||
new TemplateVariable("packageName", TemplateVariable.VariableType.REQUEST_PARAM));
|
||||
}
|
||||
|
||||
protected JsonNodeFactory nodeFactory() {
|
||||
@@ -124,8 +114,7 @@ public class InitializrMetadataV2JsonMapper implements InitializrMetadataJsonMap
|
||||
ObjectNode dependencies = nodeFactory.objectNode();
|
||||
dependencies.put("type", capability.getType().getName());
|
||||
ArrayNode values = nodeFactory.arrayNode();
|
||||
values.addAll(capability.getContent().stream().map(this::mapDependencyGroup)
|
||||
.collect(Collectors.toList()));
|
||||
values.addAll(capability.getContent().stream().map(this::mapDependencyGroup).collect(Collectors.toList()));
|
||||
dependencies.set("values", values);
|
||||
parent.set(capability.getId(), dependencies);
|
||||
}
|
||||
@@ -138,8 +127,7 @@ public class InitializrMetadataV2JsonMapper implements InitializrMetadataJsonMap
|
||||
type.put("default", defaultType.getId());
|
||||
}
|
||||
ArrayNode values = nodeFactory.arrayNode();
|
||||
values.addAll(capability.getContent().stream().map(this::mapType)
|
||||
.collect(Collectors.toList()));
|
||||
values.addAll(capability.getContent().stream().map(this::mapType).collect(Collectors.toList()));
|
||||
type.set("values", values);
|
||||
parent.set("type", type);
|
||||
}
|
||||
@@ -152,8 +140,7 @@ public class InitializrMetadataV2JsonMapper implements InitializrMetadataJsonMap
|
||||
single.put("default", defaultType.getId());
|
||||
}
|
||||
ArrayNode values = nodeFactory.arrayNode();
|
||||
values.addAll(capability.getContent().stream().map(this::mapValue)
|
||||
.collect(Collectors.toList()));
|
||||
values.addAll(capability.getContent().stream().map(this::mapValue).collect(Collectors.toList()));
|
||||
single.set("values", values);
|
||||
parent.set(capability.getId(), single);
|
||||
}
|
||||
@@ -171,8 +158,7 @@ public class InitializrMetadataV2JsonMapper implements InitializrMetadataJsonMap
|
||||
protected ObjectNode mapDependencyGroup(DependencyGroup group) {
|
||||
ObjectNode result = nodeFactory.objectNode();
|
||||
result.put("name", group.getName());
|
||||
if ((group instanceof Describable)
|
||||
&& ((Describable) group).getDescription() != null) {
|
||||
if ((group instanceof Describable) && ((Describable) group).getDescription() != null) {
|
||||
result.put("description", ((Describable) group).getDescription());
|
||||
}
|
||||
ArrayNode items = nodeFactory.arrayNode();
|
||||
@@ -207,8 +193,7 @@ public class InitializrMetadataV2JsonMapper implements InitializrMetadataJsonMap
|
||||
ObjectNode result = nodeFactory.objectNode();
|
||||
result.put("id", value.getId());
|
||||
result.put("name", value.getName());
|
||||
if ((value instanceof Describable)
|
||||
&& ((Describable) value).getDescription() != null) {
|
||||
if ((value instanceof Describable) && ((Describable) value).getDescription() != null) {
|
||||
result.put("description", ((Describable) value).getDescription());
|
||||
}
|
||||
return result;
|
||||
|
||||
@@ -47,8 +47,7 @@ public final class LinkMapper {
|
||||
public static ObjectNode mapLinks(List<Link> links) {
|
||||
ObjectNode result = nodeFactory.objectNode();
|
||||
Map<String, List<Link>> byRel = new LinkedHashMap<>();
|
||||
links.forEach((it) -> byRel.computeIfAbsent(it.getRel(), (k) -> new ArrayList<>())
|
||||
.add(it));
|
||||
links.forEach((it) -> byRel.computeIfAbsent(it.getRel(), (k) -> new ArrayList<>()).add(it));
|
||||
byRel.forEach((rel, l) -> {
|
||||
if (l.size() == 1) {
|
||||
ObjectNode root = JsonNodeFactory.instance.objectNode();
|
||||
|
||||
@@ -43,16 +43,15 @@ public abstract class AbstractInitializrController {
|
||||
|
||||
public boolean isForceSsl() {
|
||||
if (this.forceSsl == null) {
|
||||
this.forceSsl = this.metadataProvider.get().getConfiguration().getEnv()
|
||||
.isForceSsl();
|
||||
this.forceSsl = this.metadataProvider.get().getConfiguration().getEnv().isForceSsl();
|
||||
}
|
||||
return this.forceSsl;
|
||||
|
||||
}
|
||||
|
||||
@ExceptionHandler
|
||||
public void invalidProjectRequest(HttpServletResponse response,
|
||||
InvalidProjectRequestException ex) throws IOException {
|
||||
public void invalidProjectRequest(HttpServletResponse response, InvalidProjectRequestException ex)
|
||||
throws IOException {
|
||||
response.sendError(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
|
||||
}
|
||||
|
||||
@@ -62,8 +61,7 @@ public abstract class AbstractInitializrController {
|
||||
* @see io.spring.initializr.metadata.InitializrConfiguration.Env#isForceSsl()
|
||||
*/
|
||||
protected String generateAppUrl() {
|
||||
ServletUriComponentsBuilder builder = ServletUriComponentsBuilder
|
||||
.fromCurrentServletMapping();
|
||||
ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentServletMapping();
|
||||
if (isForceSsl()) {
|
||||
builder.scheme("https");
|
||||
}
|
||||
|
||||
@@ -80,8 +80,7 @@ public class MainController extends AbstractInitializrController {
|
||||
/**
|
||||
* HAL JSON content type.
|
||||
*/
|
||||
public static final MediaType HAL_JSON_CONTENT_TYPE = MediaType
|
||||
.parseMediaType("application/hal+json");
|
||||
public static final MediaType HAL_JSON_CONTENT_TYPE = MediaType.parseMediaType("application/hal+json");
|
||||
|
||||
private final DependencyMetadataProvider dependencyMetadataProvider;
|
||||
|
||||
@@ -89,10 +88,8 @@ public class MainController extends AbstractInitializrController {
|
||||
|
||||
private final ProjectGenerationInvoker projectGenerationInvoker;
|
||||
|
||||
public MainController(InitializrMetadataProvider metadataProvider,
|
||||
TemplateRenderer templateRenderer,
|
||||
DependencyMetadataProvider dependencyMetadataProvider,
|
||||
ProjectGenerationInvoker projectGenerationInvoker) {
|
||||
public MainController(InitializrMetadataProvider metadataProvider, TemplateRenderer templateRenderer,
|
||||
DependencyMetadataProvider dependencyMetadataProvider, ProjectGenerationInvoker projectGenerationInvoker) {
|
||||
super(metadataProvider);
|
||||
this.dependencyMetadataProvider = dependencyMetadataProvider;
|
||||
this.commandLineHelpGenerator = new CommandLineHelpGenerator(templateRenderer);
|
||||
@@ -115,9 +112,7 @@ public class MainController extends AbstractInitializrController {
|
||||
|
||||
@RequestMapping(path = "/", produces = "text/plain")
|
||||
public ResponseEntity<String> serviceCapabilitiesText(
|
||||
@RequestHeader(value = HttpHeaders.USER_AGENT,
|
||||
required = false) String userAgent)
|
||||
throws IOException {
|
||||
@RequestHeader(value = HttpHeaders.USER_AGENT, required = false) String userAgent) throws IOException {
|
||||
String appUrl = generateAppUrl();
|
||||
InitializrMetadata metadata = this.metadataProvider.get();
|
||||
|
||||
@@ -126,31 +121,26 @@ public class MainController extends AbstractInitializrController {
|
||||
Agent agent = Agent.fromUserAgent(userAgent);
|
||||
if (agent != null) {
|
||||
if (AgentId.CURL.equals(agent.getId())) {
|
||||
String content = this.commandLineHelpGenerator
|
||||
.generateCurlCapabilities(metadata, appUrl);
|
||||
String content = this.commandLineHelpGenerator.generateCurlCapabilities(metadata, appUrl);
|
||||
return builder.eTag(createUniqueId(content)).body(content);
|
||||
}
|
||||
if (AgentId.HTTPIE.equals(agent.getId())) {
|
||||
String content = this.commandLineHelpGenerator
|
||||
.generateHttpieCapabilities(metadata, appUrl);
|
||||
String content = this.commandLineHelpGenerator.generateHttpieCapabilities(metadata, appUrl);
|
||||
return builder.eTag(createUniqueId(content)).body(content);
|
||||
}
|
||||
if (AgentId.SPRING_BOOT_CLI.equals(agent.getId())) {
|
||||
String content = this.commandLineHelpGenerator
|
||||
.generateSpringBootCliCapabilities(metadata, appUrl);
|
||||
String content = this.commandLineHelpGenerator.generateSpringBootCliCapabilities(metadata, appUrl);
|
||||
return builder.eTag(createUniqueId(content)).body(content);
|
||||
}
|
||||
}
|
||||
}
|
||||
String content = this.commandLineHelpGenerator
|
||||
.generateGenericCapabilities(metadata, appUrl);
|
||||
String content = this.commandLineHelpGenerator.generateGenericCapabilities(metadata, appUrl);
|
||||
return builder.eTag(createUniqueId(content)).body(content);
|
||||
}
|
||||
|
||||
@RequestMapping(path = { "/", "/metadata/client" }, produces = "application/hal+json")
|
||||
public ResponseEntity<String> serviceCapabilitiesHal() {
|
||||
return serviceCapabilitiesFor(InitializrMetadataVersion.V2_1,
|
||||
HAL_JSON_CONTENT_TYPE);
|
||||
return serviceCapabilitiesFor(InitializrMetadataVersion.V2_1, HAL_JSON_CONTENT_TYPE);
|
||||
}
|
||||
|
||||
@RequestMapping(path = { "/", "/metadata/client" },
|
||||
@@ -159,29 +149,23 @@ public class MainController extends AbstractInitializrController {
|
||||
return serviceCapabilitiesFor(InitializrMetadataVersion.V2_1);
|
||||
}
|
||||
|
||||
@RequestMapping(path = { "/", "/metadata/client" },
|
||||
produces = "application/vnd.initializr.v2+json")
|
||||
@RequestMapping(path = { "/", "/metadata/client" }, produces = "application/vnd.initializr.v2+json")
|
||||
public ResponseEntity<String> serviceCapabilitiesV2() {
|
||||
return serviceCapabilitiesFor(InitializrMetadataVersion.V2);
|
||||
}
|
||||
|
||||
private ResponseEntity<String> serviceCapabilitiesFor(
|
||||
InitializrMetadataVersion version) {
|
||||
private ResponseEntity<String> serviceCapabilitiesFor(InitializrMetadataVersion version) {
|
||||
return serviceCapabilitiesFor(version, version.getMediaType());
|
||||
}
|
||||
|
||||
private ResponseEntity<String> serviceCapabilitiesFor(
|
||||
InitializrMetadataVersion version, MediaType contentType) {
|
||||
private ResponseEntity<String> serviceCapabilitiesFor(InitializrMetadataVersion version, MediaType contentType) {
|
||||
String appUrl = generateAppUrl();
|
||||
String content = getJsonMapper(version).write(this.metadataProvider.get(),
|
||||
appUrl);
|
||||
return ResponseEntity.ok().contentType(contentType).eTag(createUniqueId(content))
|
||||
.varyBy("Accept").cacheControl(CacheControl.maxAge(7, TimeUnit.DAYS))
|
||||
.body(content);
|
||||
String content = getJsonMapper(version).write(this.metadataProvider.get(), appUrl);
|
||||
return ResponseEntity.ok().contentType(contentType).eTag(createUniqueId(content)).varyBy("Accept")
|
||||
.cacheControl(CacheControl.maxAge(7, TimeUnit.DAYS)).body(content);
|
||||
}
|
||||
|
||||
private static InitializrMetadataJsonMapper getJsonMapper(
|
||||
InitializrMetadataVersion version) {
|
||||
private static InitializrMetadataJsonMapper getJsonMapper(InitializrMetadataVersion version) {
|
||||
switch (version) {
|
||||
case V2:
|
||||
return new InitializrMetadataV2JsonMapper();
|
||||
@@ -190,23 +174,18 @@ public class MainController extends AbstractInitializrController {
|
||||
}
|
||||
}
|
||||
|
||||
@RequestMapping(path = "/dependencies",
|
||||
produces = { "application/vnd.initializr.v2.1+json", "application/json" })
|
||||
public ResponseEntity<String> dependenciesV21(
|
||||
@RequestParam(required = false) String bootVersion) {
|
||||
@RequestMapping(path = "/dependencies", produces = { "application/vnd.initializr.v2.1+json", "application/json" })
|
||||
public ResponseEntity<String> dependenciesV21(@RequestParam(required = false) String bootVersion) {
|
||||
return dependenciesFor(InitializrMetadataVersion.V2_1, bootVersion);
|
||||
}
|
||||
|
||||
private ResponseEntity<String> dependenciesFor(InitializrMetadataVersion version,
|
||||
String bootVersion) {
|
||||
private ResponseEntity<String> dependenciesFor(InitializrMetadataVersion version, String bootVersion) {
|
||||
InitializrMetadata metadata = this.metadataProvider.get();
|
||||
Version v = (bootVersion != null) ? Version.parse(bootVersion)
|
||||
: Version.parse(metadata.getBootVersions().getDefault().getId());
|
||||
DependencyMetadata dependencyMetadata = this.dependencyMetadataProvider
|
||||
.get(metadata, v);
|
||||
DependencyMetadata dependencyMetadata = this.dependencyMetadataProvider.get(metadata, v);
|
||||
String content = new DependencyMetadataV21JsonMapper().write(dependencyMetadata);
|
||||
return ResponseEntity.ok().contentType(version.getMediaType())
|
||||
.eTag(createUniqueId(content))
|
||||
return ResponseEntity.ok().contentType(version.getMediaType()).eTag(createUniqueId(content))
|
||||
.cacheControl(CacheControl.maxAge(7, TimeUnit.DAYS)).body(content);
|
||||
}
|
||||
|
||||
@@ -235,15 +214,13 @@ public class MainController extends AbstractInitializrController {
|
||||
public ResponseEntity<byte[]> gradle(ProjectRequest request) {
|
||||
request.setType("gradle-build");
|
||||
byte[] gradleBuild = this.projectGenerationInvoker.invokeBuildGeneration(request);
|
||||
return createResponseEntity(gradleBuild, "application/octet-stream",
|
||||
"build.gradle");
|
||||
return createResponseEntity(gradleBuild, "application/octet-stream", "build.gradle");
|
||||
}
|
||||
|
||||
@RequestMapping("/starter.zip")
|
||||
@ResponseBody
|
||||
public ResponseEntity<byte[]> springZip(ProjectRequest request) throws IOException {
|
||||
ProjectGenerationResult result = this.projectGenerationInvoker
|
||||
.invokeProjectStructureGeneration(request);
|
||||
ProjectGenerationResult result = this.projectGenerationInvoker.invokeProjectStructureGeneration(request);
|
||||
File dir = result.getRootDirectory().toFile();
|
||||
File download = this.projectGenerationInvoker.createDistributionFile(dir, ".zip");
|
||||
String wrapperScript = getWrapperScript(result.getProjectDescription());
|
||||
@@ -270,11 +247,9 @@ public class MainController extends AbstractInitializrController {
|
||||
@RequestMapping(path = "/starter.tgz", produces = "application/x-compress")
|
||||
@ResponseBody
|
||||
public ResponseEntity<byte[]> springTgz(ProjectRequest request) throws IOException {
|
||||
ProjectGenerationResult result = this.projectGenerationInvoker
|
||||
.invokeProjectStructureGeneration(request);
|
||||
ProjectGenerationResult result = this.projectGenerationInvoker.invokeProjectStructureGeneration(request);
|
||||
File dir = result.getRootDirectory().toFile();
|
||||
File download = this.projectGenerationInvoker.createDistributionFile(dir,
|
||||
".tar.gz");
|
||||
File download = this.projectGenerationInvoker.createDistributionFile(dir, ".tar.gz");
|
||||
String wrapperScript = getWrapperScript(result.getProjectDescription());
|
||||
Tar zip = new Tar();
|
||||
zip.setProject(new Project());
|
||||
@@ -294,13 +269,11 @@ public class MainController extends AbstractInitializrController {
|
||||
method.setValue("gzip");
|
||||
zip.setCompression(method);
|
||||
zip.execute();
|
||||
return upload(download, dir, generateFileName(request, "tar.gz"),
|
||||
"application/x-compress");
|
||||
return upload(download, dir, generateFileName(request, "tar.gz"), "application/x-compress");
|
||||
}
|
||||
|
||||
private String generateFileName(ProjectRequest request, String extension) {
|
||||
String candidate = (StringUtils.hasText(request.getArtifactId())
|
||||
? request.getArtifactId()
|
||||
String candidate = (StringUtils.hasText(request.getArtifactId()) ? request.getArtifactId()
|
||||
: this.metadataProvider.get().getArtifactId().getContent());
|
||||
String tmp = candidate.replaceAll(" ", "_");
|
||||
try {
|
||||
@@ -314,22 +287,19 @@ public class MainController extends AbstractInitializrController {
|
||||
private static String getWrapperScript(ResolvedProjectDescription description) {
|
||||
BuildSystem buildSystem = description.getBuildSystem();
|
||||
String script = buildSystem.id().equals(MavenBuildSystem.ID) ? "mvnw" : "gradlew";
|
||||
return (description.getBaseDirectory() != null)
|
||||
? description.getBaseDirectory() + "/" + script : script;
|
||||
return (description.getBaseDirectory() != null) ? description.getBaseDirectory() + "/" + script : script;
|
||||
}
|
||||
|
||||
private ResponseEntity<byte[]> upload(File download, File dir, String fileName,
|
||||
String contentType) throws IOException {
|
||||
private ResponseEntity<byte[]> upload(File download, File dir, String fileName, String contentType)
|
||||
throws IOException {
|
||||
byte[] bytes = StreamUtils.copyToByteArray(new FileInputStream(download));
|
||||
logger.info(String.format("Uploading: %s (%s bytes)", download, bytes.length));
|
||||
ResponseEntity<byte[]> result = createResponseEntity(bytes, contentType,
|
||||
fileName);
|
||||
ResponseEntity<byte[]> result = createResponseEntity(bytes, contentType, fileName);
|
||||
this.projectGenerationInvoker.cleanTempFiles(dir);
|
||||
return result;
|
||||
}
|
||||
|
||||
private ResponseEntity<byte[]> createResponseEntity(byte[] content,
|
||||
String contentType, String fileName) {
|
||||
private ResponseEntity<byte[]> createResponseEntity(byte[] content, String contentType, String fileName) {
|
||||
String contentDispositionValue = "attachment; filename=\"" + fileName + "\"";
|
||||
return ResponseEntity.ok().header("Content-Type", contentType)
|
||||
.header("Content-Disposition", contentDispositionValue).body(content);
|
||||
@@ -337,8 +307,7 @@ public class MainController extends AbstractInitializrController {
|
||||
|
||||
private String createUniqueId(String content) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
DigestUtils.appendMd5DigestAsHex(content.getBytes(StandardCharsets.UTF_8),
|
||||
builder);
|
||||
DigestUtils.appendMd5DigestAsHex(content.getBytes(StandardCharsets.UTF_8), builder);
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
|
||||
@@ -27,8 +27,7 @@ public class ProjectFailedEvent extends ProjectRequestEvent {
|
||||
|
||||
private final Exception cause;
|
||||
|
||||
public ProjectFailedEvent(ProjectRequest request, InitializrMetadata metadata,
|
||||
Exception cause) {
|
||||
public ProjectFailedEvent(ProjectRequest request, InitializrMetadata metadata, Exception cause) {
|
||||
super(request, metadata);
|
||||
this.cause = cause;
|
||||
}
|
||||
|
||||
@@ -60,8 +60,7 @@ public class ProjectGenerationInvoker {
|
||||
private transient Map<String, List<File>> temporaryFiles = new LinkedHashMap<>();
|
||||
|
||||
public ProjectGenerationInvoker(ApplicationContext parentApplicationContext,
|
||||
ApplicationEventPublisher eventPublisher,
|
||||
ProjectRequestToDescriptionConverter converter) {
|
||||
ApplicationEventPublisher eventPublisher, ProjectRequestToDescriptionConverter converter) {
|
||||
this.parentApplicationContext = parentApplicationContext;
|
||||
this.eventPublisher = eventPublisher;
|
||||
this.converter = converter;
|
||||
@@ -73,18 +72,13 @@ public class ProjectGenerationInvoker {
|
||||
* @param request the project request
|
||||
* @return the {@link ProjectGenerationResult}
|
||||
*/
|
||||
public ProjectGenerationResult invokeProjectStructureGeneration(
|
||||
ProjectRequest request) {
|
||||
InitializrMetadata metadata = this.parentApplicationContext
|
||||
.getBean(InitializrMetadataProvider.class).get();
|
||||
public ProjectGenerationResult invokeProjectStructureGeneration(ProjectRequest request) {
|
||||
InitializrMetadata metadata = this.parentApplicationContext.getBean(InitializrMetadataProvider.class).get();
|
||||
try {
|
||||
ProjectDescription projectDescription = this.converter.convert(request,
|
||||
metadata);
|
||||
ProjectGenerator projectGenerator = new ProjectGenerator(
|
||||
(projectGenerationContext) -> customizeProjectGenerationContext(
|
||||
projectGenerationContext, metadata));
|
||||
ProjectGenerationResult result = projectGenerator.generate(projectDescription,
|
||||
generateProject(request));
|
||||
ProjectDescription projectDescription = this.converter.convert(request, metadata);
|
||||
ProjectGenerator projectGenerator = new ProjectGenerator((
|
||||
projectGenerationContext) -> customizeProjectGenerationContext(projectGenerationContext, metadata));
|
||||
ProjectGenerationResult result = projectGenerator.generate(projectDescription, generateProject(request));
|
||||
File file = result.getRootDirectory().toFile();
|
||||
String name = file.getName();
|
||||
addTempFile(name, file);
|
||||
@@ -96,13 +90,11 @@ public class ProjectGenerationInvoker {
|
||||
}
|
||||
}
|
||||
|
||||
private ProjectAssetGenerator<ProjectGenerationResult> generateProject(
|
||||
ProjectRequest request) {
|
||||
private ProjectAssetGenerator<ProjectGenerationResult> generateProject(ProjectRequest request) {
|
||||
return (context) -> {
|
||||
Path projectDir = new DefaultProjectAssetGenerator().generate(context);
|
||||
publishProjectGeneratedEvent(request, context);
|
||||
return new ProjectGenerationResult(
|
||||
context.getBean(ResolvedProjectDescription.class), projectDir);
|
||||
return new ProjectGenerationResult(context.getBean(ResolvedProjectDescription.class), projectDir);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -114,14 +106,11 @@ public class ProjectGenerationInvoker {
|
||||
* @return the generated build content
|
||||
*/
|
||||
public byte[] invokeBuildGeneration(ProjectRequest request) {
|
||||
InitializrMetadata metadata = this.parentApplicationContext
|
||||
.getBean(InitializrMetadataProvider.class).get();
|
||||
InitializrMetadata metadata = this.parentApplicationContext.getBean(InitializrMetadataProvider.class).get();
|
||||
try {
|
||||
ProjectDescription projectDescription = this.converter.convert(request,
|
||||
metadata);
|
||||
ProjectGenerator projectGenerator = new ProjectGenerator(
|
||||
(projectGenerationContext) -> customizeProjectGenerationContext(
|
||||
projectGenerationContext, metadata));
|
||||
ProjectDescription projectDescription = this.converter.convert(request, metadata);
|
||||
ProjectGenerator projectGenerator = new ProjectGenerator((
|
||||
projectGenerationContext) -> customizeProjectGenerationContext(projectGenerationContext, metadata));
|
||||
return projectGenerator.generate(projectDescription, generateBuild(request));
|
||||
}
|
||||
catch (ProjectGenerationException ex) {
|
||||
@@ -175,39 +164,34 @@ public class ProjectGenerationInvoker {
|
||||
}
|
||||
|
||||
private byte[] generateBuild(ProjectGenerationContext context) throws IOException {
|
||||
ResolvedProjectDescription projectDescription = context
|
||||
.getBean(ResolvedProjectDescription.class);
|
||||
ResolvedProjectDescription projectDescription = context.getBean(ResolvedProjectDescription.class);
|
||||
StringWriter out = new StringWriter();
|
||||
BuildWriter buildWriter = context.getBeanProvider(BuildWriter.class)
|
||||
.getIfAvailable();
|
||||
BuildWriter buildWriter = context.getBeanProvider(BuildWriter.class).getIfAvailable();
|
||||
if (buildWriter != null) {
|
||||
buildWriter.writeBuild(out);
|
||||
return out.toString().getBytes();
|
||||
}
|
||||
else {
|
||||
throw new IllegalStateException("No BuildWriter implementation found for "
|
||||
+ projectDescription.getLanguage());
|
||||
throw new IllegalStateException(
|
||||
"No BuildWriter implementation found for " + projectDescription.getLanguage());
|
||||
}
|
||||
}
|
||||
|
||||
private void customizeProjectGenerationContext(
|
||||
AnnotationConfigApplicationContext context, InitializrMetadata metadata) {
|
||||
private void customizeProjectGenerationContext(AnnotationConfigApplicationContext context,
|
||||
InitializrMetadata metadata) {
|
||||
context.setParent(this.parentApplicationContext);
|
||||
context.registerBean(InitializrMetadata.class, () -> metadata);
|
||||
context.registerBean(BuildItemResolver.class, () -> new MetadataBuildItemResolver(
|
||||
metadata,
|
||||
context.registerBean(BuildItemResolver.class, () -> new MetadataBuildItemResolver(metadata,
|
||||
context.getBean(ResolvedProjectDescription.class).getPlatformVersion()));
|
||||
}
|
||||
|
||||
private void publishProjectGeneratedEvent(ProjectRequest request,
|
||||
ProjectGenerationContext context) {
|
||||
private void publishProjectGeneratedEvent(ProjectRequest request, ProjectGenerationContext context) {
|
||||
InitializrMetadata metadata = context.getBean(InitializrMetadata.class);
|
||||
ProjectGeneratedEvent event = new ProjectGeneratedEvent(request, metadata);
|
||||
this.eventPublisher.publishEvent(event);
|
||||
}
|
||||
|
||||
private void publishProjectFailedEvent(ProjectRequest request,
|
||||
InitializrMetadata metadata, Exception cause) {
|
||||
private void publishProjectFailedEvent(ProjectRequest request, InitializrMetadata metadata, Exception cause) {
|
||||
ProjectFailedEvent event = new ProjectFailedEvent(request, metadata, cause);
|
||||
this.eventPublisher.publishEvent(event);
|
||||
}
|
||||
|
||||
@@ -31,8 +31,7 @@ public class ProjectGenerationResult {
|
||||
|
||||
private final Path rootDirectory;
|
||||
|
||||
ProjectGenerationResult(ResolvedProjectDescription projectDescription,
|
||||
Path rootDirectory) {
|
||||
ProjectGenerationResult(ResolvedProjectDescription projectDescription, Path rootDirectory) {
|
||||
this.projectDescription = projectDescription;
|
||||
this.rootDirectory = rootDirectory;
|
||||
}
|
||||
|
||||
@@ -42,35 +42,27 @@ public class ProjectRequestToDescriptionConverter {
|
||||
|
||||
private static final Version VERSION_1_5_0 = Version.parse("1.5.0.RELEASE");
|
||||
|
||||
public ProjectDescription convert(ProjectRequest request,
|
||||
InitializrMetadata metadata) {
|
||||
public ProjectDescription convert(ProjectRequest request, InitializrMetadata metadata) {
|
||||
validate(request, metadata);
|
||||
String springBootVersion = getSpringBootVersion(request, metadata);
|
||||
List<Dependency> resolvedDependencies = getResolvedDependencies(request,
|
||||
springBootVersion, metadata);
|
||||
List<Dependency> resolvedDependencies = getResolvedDependencies(request, springBootVersion, metadata);
|
||||
validateDependencyRange(springBootVersion, resolvedDependencies);
|
||||
ProjectDescription description = new ProjectDescription();
|
||||
description.setApplicationName(getApplicationName(request, metadata));
|
||||
description.setArtifactId(determineValue(request.getArtifactId(),
|
||||
() -> metadata.getArtifactId().getContent()));
|
||||
description.setArtifactId(determineValue(request.getArtifactId(), () -> metadata.getArtifactId().getContent()));
|
||||
description.setBaseDirectory(request.getBaseDir());
|
||||
description.setBuildSystem(getBuildSystem(request, metadata));
|
||||
description.setDescription(determineValue(request.getDescription(),
|
||||
() -> metadata.getDescription().getContent()));
|
||||
description.setGroupId(determineValue(request.getGroupId(),
|
||||
() -> metadata.getGroupId().getContent()));
|
||||
description.setLanguage(
|
||||
Language.forId(request.getLanguage(), request.getJavaVersion()));
|
||||
description.setName(
|
||||
determineValue(request.getName(), () -> metadata.getName().getContent()));
|
||||
description
|
||||
.setDescription(determineValue(request.getDescription(), () -> metadata.getDescription().getContent()));
|
||||
description.setGroupId(determineValue(request.getGroupId(), () -> metadata.getGroupId().getContent()));
|
||||
description.setLanguage(Language.forId(request.getLanguage(), request.getJavaVersion()));
|
||||
description.setName(determineValue(request.getName(), () -> metadata.getName().getContent()));
|
||||
description.setPackageName(getPackageName(request, metadata));
|
||||
description.setPackaging(Packaging.forId(request.getPackaging()));
|
||||
description.setPlatformVersion(Version.parse(springBootVersion));
|
||||
description.setVersion(determineValue(request.getVersion(),
|
||||
() -> metadata.getVersion().getContent()));
|
||||
resolvedDependencies
|
||||
.forEach((dependency) -> description.addDependency(dependency.getId(),
|
||||
MetadataBuildItemMapper.toDependency(dependency)));
|
||||
description.setVersion(determineValue(request.getVersion(), () -> metadata.getVersion().getContent()));
|
||||
resolvedDependencies.forEach((dependency) -> description.addDependency(dependency.getId(),
|
||||
MetadataBuildItemMapper.toDependency(dependency)));
|
||||
return description;
|
||||
}
|
||||
|
||||
@@ -89,8 +81,8 @@ public class ProjectRequestToDescriptionConverter {
|
||||
private void validateSpringBootVersion(ProjectRequest request) {
|
||||
Version bootVersion = Version.safeParse(request.getBootVersion());
|
||||
if (bootVersion != null && bootVersion.compareTo(VERSION_1_5_0) < 0) {
|
||||
throw new InvalidProjectRequestException("Invalid Spring Boot version "
|
||||
+ bootVersion + " must be 1.5.0 or higher");
|
||||
throw new InvalidProjectRequestException(
|
||||
"Invalid Spring Boot version " + bootVersion + " must be 1.5.0 or higher");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,31 +90,27 @@ public class ProjectRequestToDescriptionConverter {
|
||||
if (type != null) {
|
||||
Type typeFromMetadata = metadata.getTypes().get(type);
|
||||
if (typeFromMetadata == null) {
|
||||
throw new InvalidProjectRequestException(
|
||||
"Unknown type '" + type + "' check project metadata");
|
||||
throw new InvalidProjectRequestException("Unknown type '" + type + "' check project metadata");
|
||||
}
|
||||
if (!typeFromMetadata.getTags().containsKey("build")) {
|
||||
throw new InvalidProjectRequestException("Invalid type '" + type
|
||||
+ "' (missing build tag) check project metadata");
|
||||
throw new InvalidProjectRequestException(
|
||||
"Invalid type '" + type + "' (missing build tag) check project metadata");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateLanguage(String language, InitializrMetadata metadata) {
|
||||
if (language != null) {
|
||||
DefaultMetadataElement languageFromMetadata = metadata.getLanguages()
|
||||
.get(language);
|
||||
DefaultMetadataElement languageFromMetadata = metadata.getLanguages().get(language);
|
||||
if (languageFromMetadata == null) {
|
||||
throw new InvalidProjectRequestException(
|
||||
"Unknown language '" + language + "' check project metadata");
|
||||
throw new InvalidProjectRequestException("Unknown language '" + language + "' check project metadata");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validatePackaging(String packaging, InitializrMetadata metadata) {
|
||||
if (packaging != null) {
|
||||
DefaultMetadataElement packagingFromMetadata = metadata.getPackagings()
|
||||
.get(packaging);
|
||||
DefaultMetadataElement packagingFromMetadata = metadata.getPackagings().get(packaging);
|
||||
if (packagingFromMetadata == null) {
|
||||
throw new InvalidProjectRequestException(
|
||||
"Unknown packaging '" + packaging + "' check project metadata");
|
||||
@@ -130,32 +118,26 @@ public class ProjectRequestToDescriptionConverter {
|
||||
}
|
||||
}
|
||||
|
||||
private void validateDependencies(ProjectRequest request,
|
||||
InitializrMetadata metadata) {
|
||||
List<String> dependencies = (!request.getStyle().isEmpty() ? request.getStyle()
|
||||
: request.getDependencies());
|
||||
private void validateDependencies(ProjectRequest request, InitializrMetadata metadata) {
|
||||
List<String> dependencies = (!request.getStyle().isEmpty() ? request.getStyle() : request.getDependencies());
|
||||
dependencies.forEach((dep) -> {
|
||||
Dependency dependency = metadata.getDependencies().get(dep);
|
||||
if (dependency == null) {
|
||||
throw new InvalidProjectRequestException(
|
||||
"Unknown dependency '" + dep + "' check project metadata");
|
||||
throw new InvalidProjectRequestException("Unknown dependency '" + dep + "' check project metadata");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void validateDependencyRange(String springBootVersion,
|
||||
List<Dependency> resolvedDependencies) {
|
||||
private void validateDependencyRange(String springBootVersion, List<Dependency> resolvedDependencies) {
|
||||
resolvedDependencies.forEach((dep) -> {
|
||||
if (!dep.match(Version.parse(springBootVersion))) {
|
||||
throw new InvalidProjectRequestException(
|
||||
"Dependency '" + dep.getId() + "' is not compatible "
|
||||
+ "with Spring Boot " + springBootVersion);
|
||||
throw new InvalidProjectRequestException("Dependency '" + dep.getId() + "' is not compatible "
|
||||
+ "with Spring Boot " + springBootVersion);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private BuildSystem getBuildSystem(ProjectRequest request,
|
||||
InitializrMetadata metadata) {
|
||||
private BuildSystem getBuildSystem(ProjectRequest request, InitializrMetadata metadata) {
|
||||
Type typeFromMetadata = metadata.getTypes().get(request.getType());
|
||||
return BuildSystem.forId(typeFromMetadata.getTags().get("build"));
|
||||
}
|
||||
@@ -165,24 +147,21 @@ public class ProjectRequestToDescriptionConverter {
|
||||
metadata.getPackageName().getContent());
|
||||
}
|
||||
|
||||
private String getApplicationName(ProjectRequest request,
|
||||
InitializrMetadata metadata) {
|
||||
private String getApplicationName(ProjectRequest request, InitializrMetadata metadata) {
|
||||
if (!StringUtils.hasText(request.getApplicationName())) {
|
||||
return metadata.getConfiguration().generateApplicationName(request.getName());
|
||||
}
|
||||
return request.getApplicationName();
|
||||
}
|
||||
|
||||
private String getSpringBootVersion(ProjectRequest request,
|
||||
InitializrMetadata metadata) {
|
||||
private String getSpringBootVersion(ProjectRequest request, InitializrMetadata metadata) {
|
||||
return (request.getBootVersion() != null) ? request.getBootVersion()
|
||||
: metadata.getBootVersions().getDefault().getId();
|
||||
}
|
||||
|
||||
private List<Dependency> getResolvedDependencies(ProjectRequest request,
|
||||
String springBootVersion, InitializrMetadata metadata) {
|
||||
List<String> depIds = (!request.getStyle().isEmpty() ? request.getStyle()
|
||||
: request.getDependencies());
|
||||
private List<Dependency> getResolvedDependencies(ProjectRequest request, String springBootVersion,
|
||||
InitializrMetadata metadata) {
|
||||
List<String> depIds = (!request.getStyle().isEmpty() ? request.getStyle() : request.getDependencies());
|
||||
Version requestedVersion = Version.parse(springBootVersion);
|
||||
return depIds.stream().map((it) -> {
|
||||
Dependency dependency = metadata.getDependencies().get(it);
|
||||
|
||||
@@ -134,13 +134,11 @@ public class Agent {
|
||||
|
||||
private static class UserAgentHandler {
|
||||
|
||||
private static final Pattern TOOL_REGEX = Pattern
|
||||
.compile("([^\\/]*)\\/([^ ]*).*");
|
||||
private static final Pattern TOOL_REGEX = Pattern.compile("([^\\/]*)\\/([^ ]*).*");
|
||||
|
||||
private static final Pattern STS_REGEX = Pattern.compile("STS (.*)");
|
||||
|
||||
private static final Pattern NETBEANS_REGEX = Pattern
|
||||
.compile("nb-springboot-plugin\\/(.*)");
|
||||
private static final Pattern NETBEANS_REGEX = Pattern.compile("nb-springboot-plugin\\/(.*)");
|
||||
|
||||
public static Agent parse(String userAgent) {
|
||||
Matcher matcher = TOOL_REGEX.matcher(userAgent);
|
||||
|
||||
@@ -39,10 +39,8 @@ import org.springframework.beans.BeanWrapperImpl;
|
||||
public class CommandLineHelpGenerator {
|
||||
|
||||
private static final String LOGO = " . ____ _ __ _ _\n"
|
||||
+ " /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n"
|
||||
+ "( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n"
|
||||
+ " \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n"
|
||||
+ " ' |____| .__|_| |_|_| |_\\__, | / / / /\n"
|
||||
+ " /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n" + "( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n"
|
||||
+ " \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n" + " ' |____| .__|_| |_|_| |_\\__, | / / / /\n"
|
||||
+ " =========|_|==============|___/=/_/_/_/";
|
||||
|
||||
private final TemplateRenderer template;
|
||||
@@ -59,8 +57,7 @@ public class CommandLineHelpGenerator {
|
||||
* @return the generic capabilities text document
|
||||
* @throws IOException if rendering the capabilities failed
|
||||
*/
|
||||
public String generateGenericCapabilities(InitializrMetadata metadata,
|
||||
String serviceUrl) throws IOException {
|
||||
public String generateGenericCapabilities(InitializrMetadata metadata, String serviceUrl) throws IOException {
|
||||
Map<String, Object> model = initializeCommandLineModel(metadata, serviceUrl);
|
||||
model.put("hasExamples", false);
|
||||
return this.template.render("cli/cli-capabilities", model);
|
||||
@@ -73,8 +70,7 @@ public class CommandLineHelpGenerator {
|
||||
* @return the generic capabilities text document
|
||||
* @throws IOException if rendering the capabilities failed
|
||||
*/
|
||||
public String generateCurlCapabilities(InitializrMetadata metadata, String serviceUrl)
|
||||
throws IOException {
|
||||
public String generateCurlCapabilities(InitializrMetadata metadata, String serviceUrl) throws IOException {
|
||||
Map<String, Object> model = initializeCommandLineModel(metadata, serviceUrl);
|
||||
model.put("examples", this.template.render("cli/curl-examples", model));
|
||||
model.put("hasExamples", true);
|
||||
@@ -88,8 +84,7 @@ public class CommandLineHelpGenerator {
|
||||
* @return the generic capabilities text document
|
||||
* @throws IOException if rendering the capabilities failed
|
||||
*/
|
||||
public String generateHttpieCapabilities(InitializrMetadata metadata,
|
||||
String serviceUrl) throws IOException {
|
||||
public String generateHttpieCapabilities(InitializrMetadata metadata, String serviceUrl) throws IOException {
|
||||
Map<String, Object> model = initializeCommandLineModel(metadata, serviceUrl);
|
||||
model.put("examples", this.template.render("cli/httpie-examples", model));
|
||||
model.put("hasExamples", true);
|
||||
@@ -104,15 +99,13 @@ public class CommandLineHelpGenerator {
|
||||
* @return the generic capabilities text document
|
||||
* @throws IOException if rendering the capabilities failed
|
||||
*/
|
||||
public String generateSpringBootCliCapabilities(InitializrMetadata metadata,
|
||||
String serviceUrl) throws IOException {
|
||||
public String generateSpringBootCliCapabilities(InitializrMetadata metadata, String serviceUrl) throws IOException {
|
||||
Map<String, Object> model = initializeSpringBootCliModel(metadata, serviceUrl);
|
||||
model.put("hasExamples", false);
|
||||
return this.template.render("cli/boot-cli-capabilities", model);
|
||||
}
|
||||
|
||||
protected Map<String, Object> initializeCommandLineModel(InitializrMetadata metadata,
|
||||
String serviceUrl) {
|
||||
protected Map<String, Object> initializeCommandLineModel(InitializrMetadata metadata, String serviceUrl) {
|
||||
Map<String, Object> model = new LinkedHashMap<>();
|
||||
model.put("logo", LOGO);
|
||||
model.put("serviceUrl", serviceUrl);
|
||||
@@ -120,8 +113,8 @@ public class CommandLineHelpGenerator {
|
||||
model.put("types", generateTypeTable(metadata, "Rel", false));
|
||||
|
||||
Map<String, Object> defaults = metadata.defaults();
|
||||
defaults.put("applicationName", metadata.getConfiguration()
|
||||
.generateApplicationName(metadata.getName().getContent()));
|
||||
defaults.put("applicationName",
|
||||
metadata.getConfiguration().generateApplicationName(metadata.getName().getContent()));
|
||||
defaults.put("baseDir", "no base dir");
|
||||
defaults.put("dependencies", "none");
|
||||
|
||||
@@ -129,8 +122,7 @@ public class CommandLineHelpGenerator {
|
||||
String[][] parameterTable = new String[defaults.size() + 1][];
|
||||
parameterTable[0] = new String[] { "Parameter", "Description", "Default value" };
|
||||
int i = 1;
|
||||
for (String id : defaults.keySet().stream().sorted()
|
||||
.collect(Collectors.toList())) {
|
||||
for (String id : defaults.keySet().stream().sorted().collect(Collectors.toList())) {
|
||||
String[] data = new String[3];
|
||||
data[0] = id;
|
||||
data[1] = (String) parametersDescription.get(id);
|
||||
@@ -142,8 +134,7 @@ public class CommandLineHelpGenerator {
|
||||
return model;
|
||||
}
|
||||
|
||||
protected Map<String, Object> initializeSpringBootCliModel(
|
||||
InitializrMetadata metadata, String serviceUrl) {
|
||||
protected Map<String, Object> initializeSpringBootCliModel(InitializrMetadata metadata, String serviceUrl) {
|
||||
Map<String, Object> model = new LinkedHashMap<>();
|
||||
model.put("logo", LOGO);
|
||||
model.put("serviceUrl", serviceUrl);
|
||||
@@ -155,8 +146,7 @@ public class CommandLineHelpGenerator {
|
||||
String[][] parameterTable = new String[defaults.size() + 1][];
|
||||
parameterTable[0] = new String[] { "Id", "Description", "Default value" };
|
||||
int i = 1;
|
||||
for (String id : defaults.keySet().stream().sorted()
|
||||
.collect(Collectors.toList())) {
|
||||
for (String id : defaults.keySet().stream().sorted().collect(Collectors.toList())) {
|
||||
String[] data = new String[3];
|
||||
data[0] = id;
|
||||
data[1] = (String) parametersDescription.get(id);
|
||||
@@ -168,25 +158,21 @@ public class CommandLineHelpGenerator {
|
||||
}
|
||||
|
||||
protected String generateDependencyTable(InitializrMetadata metadata) {
|
||||
String[][] dependencyTable = new String[metadata.getDependencies().getAll().size()
|
||||
+ 1][];
|
||||
String[][] dependencyTable = new String[metadata.getDependencies().getAll().size() + 1][];
|
||||
dependencyTable[0] = new String[] { "Id", "Description", "Required version" };
|
||||
int i = 1;
|
||||
for (Dependency dep : metadata.getDependencies().getAll().stream()
|
||||
.sorted(Comparator.comparing(MetadataElement::getId))
|
||||
.collect(Collectors.toList())) {
|
||||
.sorted(Comparator.comparing(MetadataElement::getId)).collect(Collectors.toList())) {
|
||||
String[] data = new String[3];
|
||||
data[0] = dep.getId();
|
||||
data[1] = (dep.getDescription() != null) ? dep.getDescription()
|
||||
: dep.getName();
|
||||
data[1] = (dep.getDescription() != null) ? dep.getDescription() : dep.getName();
|
||||
data[2] = dep.getVersionRequirement();
|
||||
dependencyTable[i++] = data;
|
||||
}
|
||||
return TableGenerator.generate(dependencyTable);
|
||||
}
|
||||
|
||||
protected String generateTypeTable(InitializrMetadata metadata, String linkHeader,
|
||||
boolean addTags) {
|
||||
protected String generateTypeTable(InitializrMetadata metadata, String linkHeader, boolean addTags) {
|
||||
String[][] typeTable = new String[metadata.getTypes().getContent().size() + 1][];
|
||||
if (addTags) {
|
||||
typeTable[0] = new String[] { linkHeader, "Description", "Tags" };
|
||||
@@ -195,13 +181,11 @@ public class CommandLineHelpGenerator {
|
||||
typeTable[0] = new String[] { linkHeader, "Description" };
|
||||
}
|
||||
int i = 1;
|
||||
for (Type type : metadata.getTypes().getContent().stream()
|
||||
.sorted(Comparator.comparing(MetadataElement::getId))
|
||||
for (Type type : metadata.getTypes().getContent().stream().sorted(Comparator.comparing(MetadataElement::getId))
|
||||
.collect(Collectors.toList())) {
|
||||
String[] data = new String[typeTable[0].length];
|
||||
data[0] = (type.isDefault() ? type.getId() + " *" : type.getId());
|
||||
data[1] = (type.getDescription() != null) ? type.getDescription()
|
||||
: type.getName();
|
||||
data[1] = (type.getDescription() != null) ? type.getDescription() : type.getName();
|
||||
if (addTags) {
|
||||
data[2] = buildTagRepresentation(type);
|
||||
}
|
||||
@@ -210,17 +194,14 @@ public class CommandLineHelpGenerator {
|
||||
return TableGenerator.generate(typeTable);
|
||||
}
|
||||
|
||||
protected Map<String, Object> buildParametersDescription(
|
||||
InitializrMetadata metadata) {
|
||||
protected Map<String, Object> buildParametersDescription(InitializrMetadata metadata) {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
BeanWrapperImpl wrapper = new BeanWrapperImpl(metadata);
|
||||
for (PropertyDescriptor descriptor : wrapper.getPropertyDescriptors()) {
|
||||
Object value = wrapper.getPropertyValue(descriptor.getName());
|
||||
BeanWrapperImpl nested = new BeanWrapperImpl(value);
|
||||
if (nested.isReadableProperty("description")
|
||||
&& nested.isReadableProperty("id")) {
|
||||
result.put((String) nested.getPropertyValue("id"),
|
||||
nested.getPropertyValue("description"));
|
||||
if (nested.isReadableProperty("description") && nested.isReadableProperty("id")) {
|
||||
result.put((String) nested.getPropertyValue("id"), nested.getPropertyValue("description"));
|
||||
}
|
||||
}
|
||||
result.put("applicationName", "application name");
|
||||
@@ -232,10 +213,8 @@ public class CommandLineHelpGenerator {
|
||||
if (type.getTags().isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
return String.join(",",
|
||||
type.getTags().entrySet().stream()
|
||||
.map((entry) -> entry.getKey() + ":" + entry.getValue())
|
||||
.toArray(String[]::new));
|
||||
return String.join(",", type.getTags().entrySet().stream()
|
||||
.map((entry) -> entry.getKey() + ":" + entry.getValue()).toArray(String[]::new));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -266,8 +245,7 @@ public class CommandLineHelpGenerator {
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static void appendRow(StringBuilder sb, String[][] content,
|
||||
int[] columnsLength, int rowIndex) {
|
||||
private static void appendRow(StringBuilder sb, String[][] content, int[] columnsLength, int rowIndex) {
|
||||
String[] row = content[rowIndex];
|
||||
if (row != null) {
|
||||
for (int i = 0; i < row.length; i++) {
|
||||
|
||||
@@ -49,23 +49,22 @@ public class DefaultDependencyMetadataProvider implements DependencyMetadataProv
|
||||
Map<String, Repository> repositories = new LinkedHashMap<>();
|
||||
for (Dependency dependency : dependencies.values()) {
|
||||
if (dependency.getRepository() != null) {
|
||||
repositories.put(dependency.getRepository(), metadata.getConfiguration()
|
||||
.getEnv().getRepositories().get(dependency.getRepository()));
|
||||
repositories.put(dependency.getRepository(),
|
||||
metadata.getConfiguration().getEnv().getRepositories().get(dependency.getRepository()));
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, BillOfMaterials> boms = new LinkedHashMap<>();
|
||||
for (Dependency dependency : dependencies.values()) {
|
||||
if (dependency.getBom() != null) {
|
||||
boms.put(dependency.getBom(), metadata.getConfiguration().getEnv()
|
||||
.getBoms().get(dependency.getBom()).resolve(bootVersion));
|
||||
boms.put(dependency.getBom(),
|
||||
metadata.getConfiguration().getEnv().getBoms().get(dependency.getBom()).resolve(bootVersion));
|
||||
}
|
||||
}
|
||||
// Each resolved bom may require additional repositories
|
||||
for (BillOfMaterials bom : boms.values()) {
|
||||
for (String id : bom.getRepositories()) {
|
||||
repositories.put(id,
|
||||
metadata.getConfiguration().getEnv().getRepositories().get(id));
|
||||
repositories.put(id, metadata.getConfiguration().getEnv().getRepositories().get(id));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,18 +33,15 @@ import org.springframework.web.client.RestTemplate;
|
||||
*
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
public class DefaultInitializrMetadataUpdateStrategy
|
||||
implements InitializrMetadataUpdateStrategy {
|
||||
public class DefaultInitializrMetadataUpdateStrategy implements InitializrMetadataUpdateStrategy {
|
||||
|
||||
private static final Log logger = LogFactory
|
||||
.getLog(DefaultInitializrMetadataUpdateStrategy.class);
|
||||
private static final Log logger = LogFactory.getLog(DefaultInitializrMetadataUpdateStrategy.class);
|
||||
|
||||
private final RestTemplate restTemplate;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public DefaultInitializrMetadataUpdateStrategy(RestTemplate restTemplate,
|
||||
ObjectMapper objectMapper) {
|
||||
public DefaultInitializrMetadataUpdateStrategy(RestTemplate restTemplate, ObjectMapper objectMapper) {
|
||||
this.restTemplate = restTemplate;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
@@ -73,8 +70,7 @@ public class DefaultInitializrMetadataUpdateStrategy
|
||||
if (StringUtils.hasText(url)) {
|
||||
try {
|
||||
logger.info("Fetching Spring Boot metadata from " + url);
|
||||
return new SpringBootMetadataReader(this.objectMapper, this.restTemplate,
|
||||
url).getBootVersions();
|
||||
return new SpringBootMetadataReader(this.objectMapper, this.restTemplate, url).getBootVersions();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
logger.warn("Failed to fetch Spring Boot metadata", ex);
|
||||
|
||||
@@ -44,10 +44,8 @@ class SpringBootMetadataReader {
|
||||
* @param url the metadata URL
|
||||
* @throws IOException on load error
|
||||
*/
|
||||
SpringBootMetadataReader(ObjectMapper objectMapper, RestTemplate restTemplate,
|
||||
String url) throws IOException {
|
||||
this.content = objectMapper
|
||||
.readTree(restTemplate.getForObject(url, String.class));
|
||||
SpringBootMetadataReader(ObjectMapper objectMapper, RestTemplate restTemplate, String url) throws IOException {
|
||||
this.content = objectMapper.readTree(restTemplate.getForObject(url, String.class));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,8 +59,7 @@ class SpringBootMetadataReader {
|
||||
DefaultMetadataElement version = new DefaultMetadataElement();
|
||||
version.setId(node.get("version").textValue());
|
||||
String name = node.get("versionDisplayName").textValue();
|
||||
version.setName(
|
||||
node.get("snapshot").booleanValue() ? name + " (SNAPSHOT)" : name);
|
||||
version.setName(node.get("snapshot").booleanValue() ? name + " (SNAPSHOT)" : name);
|
||||
version.setDefault(node.get("current").booleanValue());
|
||||
list.add(version);
|
||||
}
|
||||
|
||||
@@ -27,8 +27,7 @@ import org.springframework.boot.web.server.LocalServerPort;
|
||||
* @author Dave Syer
|
||||
*/
|
||||
@SpringBootTest(classes = Config.class, webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||
public abstract class AbstractFullStackInitializrIntegrationTests
|
||||
extends AbstractInitializrIntegrationTests {
|
||||
public abstract class AbstractFullStackInitializrIntegrationTests extends AbstractInitializrIntegrationTests {
|
||||
|
||||
@LocalServerPort
|
||||
protected int port;
|
||||
@@ -37,8 +36,7 @@ public abstract class AbstractFullStackInitializrIntegrationTests
|
||||
|
||||
@Override
|
||||
protected String createUrl(String context) {
|
||||
return "http://" + this.host + ":" + this.port
|
||||
+ (context.startsWith("/") ? context : "/" + context);
|
||||
return "http://" + this.host + ":" + this.port + (context.startsWith("/") ? context : "/" + context);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -38,10 +38,8 @@ import org.springframework.test.context.TestExecutionListeners.MergeMode;
|
||||
@TestExecutionListeners(mergeMode = MergeMode.MERGE_WITH_DEFAULTS,
|
||||
listeners = MockMvcClientHttpRequestFactoryTestExecutionListener.class)
|
||||
@AutoConfigureMockMvc
|
||||
@AutoConfigureRestDocs(outputDir = "target/snippets", uriPort = 80,
|
||||
uriHost = "start.spring.io")
|
||||
public abstract class AbstractInitializrControllerIntegrationTests
|
||||
extends AbstractInitializrIntegrationTests {
|
||||
@AutoConfigureRestDocs(outputDir = "target/snippets", uriPort = 80, uriHost = "start.spring.io")
|
||||
public abstract class AbstractInitializrControllerIntegrationTests extends AbstractInitializrIntegrationTests {
|
||||
|
||||
protected String host = "start.spring.io";
|
||||
|
||||
@@ -62,8 +60,7 @@ public abstract class AbstractInitializrControllerIntegrationTests
|
||||
|
||||
@Bean
|
||||
RestTemplateCustomizer mockMvcCustomizer(BeanFactory beanFactory) {
|
||||
return (template) -> template.setRequestFactory(
|
||||
beanFactory.getBean(MockMvcClientHttpRequestFactory.class));
|
||||
return (template) -> template.setRequestFactory(beanFactory.getBean(MockMvcClientHttpRequestFactory.class));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -63,8 +63,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
@SpringBootTest(classes = Config.class)
|
||||
public abstract class AbstractInitializrIntegrationTests {
|
||||
|
||||
protected static final MediaType CURRENT_METADATA_MEDIA_TYPE = InitializrMetadataVersion.V2_1
|
||||
.getMediaType();
|
||||
protected static final MediaType CURRENT_METADATA_MEDIA_TYPE = InitializrMetadataVersion.V2_1.getMediaType();
|
||||
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@@ -88,13 +87,11 @@ public abstract class AbstractInitializrIntegrationTests {
|
||||
* @param response the response
|
||||
* @param expected the expected result
|
||||
*/
|
||||
protected void validateContentType(ResponseEntity<String> response,
|
||||
MediaType expected) {
|
||||
protected void validateContentType(ResponseEntity<String> response, MediaType expected) {
|
||||
MediaType actual = response.getHeaders().getContentType();
|
||||
assertThat(actual).isNotNull();
|
||||
assertThat(actual.isCompatibleWith(expected))
|
||||
.as("Non compatible media-type, expected " + expected + ", got " + actual)
|
||||
.isTrue();
|
||||
.as("Non compatible media-type, expected " + expected + ", got " + actual).isTrue();
|
||||
}
|
||||
|
||||
protected JsonNode parseJson(String text) {
|
||||
@@ -106,8 +103,8 @@ public abstract class AbstractInitializrIntegrationTests {
|
||||
}
|
||||
}
|
||||
|
||||
protected void validateMetadata(ResponseEntity<String> response, MediaType mediaType,
|
||||
String version, JSONCompareMode compareMode) {
|
||||
protected void validateMetadata(ResponseEntity<String> response, MediaType mediaType, String version,
|
||||
JSONCompareMode compareMode) {
|
||||
try {
|
||||
validateContentType(response, mediaType);
|
||||
JSONObject json = new JSONObject(response.getBody());
|
||||
@@ -127,8 +124,7 @@ public abstract class AbstractInitializrIntegrationTests {
|
||||
protected void validateCurrentMetadata(String json) {
|
||||
try {
|
||||
JSONObject expected = readMetadataJson("2.1.0");
|
||||
JSONAssert.assertEquals(expected, new JSONObject(json),
|
||||
JSONCompareMode.STRICT);
|
||||
JSONAssert.assertEquals(expected, new JSONObject(json), JSONCompareMode.STRICT);
|
||||
}
|
||||
catch (JSONException ex) {
|
||||
throw new IllegalArgumentException("Invalid json", ex);
|
||||
@@ -171,13 +167,12 @@ public abstract class AbstractInitializrIntegrationTests {
|
||||
return this.restTemplate.getForEntity(createUrl(context), byte[].class);
|
||||
}
|
||||
|
||||
protected ResponseEntity<String> invokeHome(String userAgentHeader,
|
||||
String... acceptHeaders) {
|
||||
protected ResponseEntity<String> invokeHome(String userAgentHeader, String... acceptHeaders) {
|
||||
return execute("/", String.class, userAgentHeader, acceptHeaders);
|
||||
}
|
||||
|
||||
protected <T> ResponseEntity<T> execute(String contextPath, Class<T> responseType,
|
||||
String userAgentHeader, String... acceptHeaders) {
|
||||
protected <T> ResponseEntity<T> execute(String contextPath, Class<T> responseType, String userAgentHeader,
|
||||
String... acceptHeaders) {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
if (userAgentHeader != null) {
|
||||
headers.set("User-Agent", userAgentHeader);
|
||||
@@ -192,8 +187,8 @@ public abstract class AbstractInitializrIntegrationTests {
|
||||
else {
|
||||
headers.setAccept(Collections.emptyList());
|
||||
}
|
||||
return this.restTemplate.exchange(createUrl(contextPath), HttpMethod.GET,
|
||||
new HttpEntity<Void>(headers), responseType);
|
||||
return this.restTemplate.exchange(createUrl(contextPath), HttpMethod.GET, new HttpEntity<Void>(headers),
|
||||
responseType);
|
||||
}
|
||||
|
||||
protected ProjectAssert projectAssert(byte[] content, ArchiveType archiveType) {
|
||||
|
||||
@@ -42,10 +42,8 @@ class CloudfoundryEnvironmentPostProcessorTests {
|
||||
|
||||
assertThat(this.environment.getProperty("initializr.stats.elastic.uri"))
|
||||
.isEqualTo("https://user:pass@example.com/bar/biz?param=one");
|
||||
assertThat(this.environment.getProperty("initializr.stats.elastic.username"))
|
||||
.isNull();
|
||||
assertThat(this.environment.getProperty("initializr.stats.elastic.password"))
|
||||
.isNull();
|
||||
assertThat(this.environment.getProperty("initializr.stats.elastic.username")).isNull();
|
||||
assertThat(this.environment.getProperty("initializr.stats.elastic.password")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -56,10 +54,8 @@ class CloudfoundryEnvironmentPostProcessorTests {
|
||||
|
||||
assertThat(this.environment.getProperty("initializr.stats.elastic.uri"))
|
||||
.isEqualTo("http://example.com/bar/biz?param=one");
|
||||
assertThat(this.environment.getProperty("initializr.stats.elastic.username"))
|
||||
.isNull();
|
||||
assertThat(this.environment.getProperty("initializr.stats.elastic.password"))
|
||||
.isNull();
|
||||
assertThat(this.environment.getProperty("initializr.stats.elastic.username")).isNull();
|
||||
assertThat(this.environment.getProperty("initializr.stats.elastic.password")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -67,10 +63,8 @@ class CloudfoundryEnvironmentPostProcessorTests {
|
||||
this.postProcessor.postProcessEnvironment(this.environment, this.application);
|
||||
|
||||
assertThat(this.environment.getProperty("initializr.stats.elastic.uri")).isNull();
|
||||
assertThat(this.environment.getProperty("initializr.stats.elastic.username"))
|
||||
.isNull();
|
||||
assertThat(this.environment.getProperty("initializr.stats.elastic.password"))
|
||||
.isNull();
|
||||
assertThat(this.environment.getProperty("initializr.stats.elastic.username")).isNull();
|
||||
assertThat(this.environment.getProperty("initializr.stats.elastic.password")).isNull();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -60,96 +60,73 @@ class InitializrAutoConfigurationTests {
|
||||
|
||||
@Test
|
||||
void autoConfigRegistersTemplateRenderer() {
|
||||
this.contextRunner.run(
|
||||
(context) -> assertThat(context).hasSingleBean(TemplateRenderer.class));
|
||||
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(TemplateRenderer.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void autoConfigWhenTemplateRendererBeanPresentDoesNotRegisterTemplateRenderer() {
|
||||
this.contextRunner
|
||||
.withUserConfiguration(CustomTemplateRendererConfiguration.class)
|
||||
.run((context) -> {
|
||||
assertThat(context).hasSingleBean(TemplateRenderer.class);
|
||||
assertThat(context).hasBean("testTemplateRenderer");
|
||||
});
|
||||
this.contextRunner.withUserConfiguration(CustomTemplateRendererConfiguration.class).run((context) -> {
|
||||
assertThat(context).hasSingleBean(TemplateRenderer.class);
|
||||
assertThat(context).hasBean("testTemplateRenderer");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void autoConfigRegistersInitializrMetadataUpdateStrategy() {
|
||||
this.contextRunner.run((context) -> assertThat(context)
|
||||
.hasSingleBean(InitializrMetadataUpdateStrategy.class));
|
||||
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(InitializrMetadataUpdateStrategy.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void autoConfigWhenInitializrMetadataUpdateStrategyPresentDoesNotRegisterInitializrMetadataUpdateStrategy() {
|
||||
this.contextRunner
|
||||
.withUserConfiguration(
|
||||
CustomInitializrMetadataUpdateStrategyConfiguration.class)
|
||||
this.contextRunner.withUserConfiguration(CustomInitializrMetadataUpdateStrategyConfiguration.class)
|
||||
.run((context) -> {
|
||||
assertThat(context)
|
||||
.hasSingleBean(InitializrMetadataUpdateStrategy.class);
|
||||
assertThat(context).hasSingleBean(InitializrMetadataUpdateStrategy.class);
|
||||
assertThat(context).hasBean("testInitializrMetadataUpdateStrategy");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void autoConfigRegistersInitializrMetadataProvider() {
|
||||
this.contextRunner.run((context) -> assertThat(context)
|
||||
.hasSingleBean(InitializrMetadataProvider.class));
|
||||
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(InitializrMetadataProvider.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void autoConfigWhenInitializrMetadataProviderBeanPresentDoesNotRegisterInitializrMetadataProvider() {
|
||||
this.contextRunner
|
||||
.withUserConfiguration(
|
||||
CustomInitializrMetadataProviderConfiguration.class)
|
||||
.run((context) -> {
|
||||
assertThat(context).hasSingleBean(InitializrMetadataProvider.class);
|
||||
assertThat(context).hasBean("testInitializrMetadataProvider");
|
||||
});
|
||||
this.contextRunner.withUserConfiguration(CustomInitializrMetadataProviderConfiguration.class).run((context) -> {
|
||||
assertThat(context).hasSingleBean(InitializrMetadataProvider.class);
|
||||
assertThat(context).hasBean("testInitializrMetadataProvider");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void autoConfigRegistersDependencyMetadataProvider() {
|
||||
this.contextRunner.run((context) -> assertThat(context)
|
||||
.hasSingleBean(DependencyMetadataProvider.class));
|
||||
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(DependencyMetadataProvider.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void autoConfigWhenDependencyMetadataProviderBeanPresentDoesNotRegisterDependencyMetadataProvider() {
|
||||
this.contextRunner
|
||||
.withUserConfiguration(
|
||||
CustomDependencyMetadataProviderConfiguration.class)
|
||||
.run((context) -> {
|
||||
assertThat(context).hasSingleBean(DependencyMetadataProvider.class);
|
||||
assertThat(context).hasBean("testDependencyMetadataProvider");
|
||||
});
|
||||
this.contextRunner.withUserConfiguration(CustomDependencyMetadataProviderConfiguration.class).run((context) -> {
|
||||
assertThat(context).hasSingleBean(DependencyMetadataProvider.class);
|
||||
assertThat(context).hasBean("testDependencyMetadataProvider");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void customRestTemplateBuilderIsUsed() {
|
||||
this.contextRunner.withUserConfiguration(CustomRestTemplateConfiguration.class)
|
||||
.run((context) -> {
|
||||
assertThat(context)
|
||||
.hasSingleBean(DefaultInitializrMetadataUpdateStrategy.class);
|
||||
RestTemplate restTemplate = (RestTemplate) new DirectFieldAccessor(
|
||||
context.getBean(
|
||||
DefaultInitializrMetadataUpdateStrategy.class))
|
||||
.getPropertyValue("restTemplate");
|
||||
assertThat(restTemplate.getErrorHandler())
|
||||
.isSameAs(CustomRestTemplateConfiguration.errorHandler);
|
||||
});
|
||||
this.contextRunner.withUserConfiguration(CustomRestTemplateConfiguration.class).run((context) -> {
|
||||
assertThat(context).hasSingleBean(DefaultInitializrMetadataUpdateStrategy.class);
|
||||
RestTemplate restTemplate = (RestTemplate) new DirectFieldAccessor(
|
||||
context.getBean(DefaultInitializrMetadataUpdateStrategy.class)).getPropertyValue("restTemplate");
|
||||
assertThat(restTemplate.getErrorHandler()).isSameAs(CustomRestTemplateConfiguration.errorHandler);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void webConfiguration() {
|
||||
WebApplicationContextRunner webContextRunner = new WebApplicationContextRunner()
|
||||
.withConfiguration(
|
||||
AutoConfigurations.of(RestTemplateAutoConfiguration.class,
|
||||
JacksonAutoConfiguration.class,
|
||||
HttpMessageConvertersAutoConfiguration.class,
|
||||
WebMvcAutoConfiguration.class,
|
||||
InitializrAutoConfiguration.class));
|
||||
.withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class,
|
||||
JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
|
||||
WebMvcAutoConfiguration.class, InitializrAutoConfiguration.class));
|
||||
webContextRunner.run((context) -> {
|
||||
assertThat(context).hasSingleBean(InitializrWebConfig.class);
|
||||
assertThat(context).hasSingleBean(ProjectGenerationInvoker.class);
|
||||
@@ -168,23 +145,19 @@ class InitializrAutoConfigurationTests {
|
||||
|
||||
@Test
|
||||
void cacheConfiguration() {
|
||||
this.contextRunner.run((context) -> assertThat(context)
|
||||
.hasSingleBean(JCacheManagerCustomizer.class));
|
||||
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(JCacheManagerCustomizer.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void cacheConfigurationConditionalOnClass() {
|
||||
this.contextRunner
|
||||
.withClassLoader(new FilteredClassLoader("javax.cache.CacheManager"))
|
||||
.run((context) -> assertThat(context)
|
||||
.doesNotHaveBean(JCacheManagerCustomizer.class));
|
||||
this.contextRunner.withClassLoader(new FilteredClassLoader("javax.cache.CacheManager"))
|
||||
.run((context) -> assertThat(context).doesNotHaveBean(JCacheManagerCustomizer.class));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class CustomRestTemplateConfiguration {
|
||||
|
||||
private static final ResponseErrorHandler errorHandler = mock(
|
||||
ResponseErrorHandler.class);
|
||||
private static final ResponseErrorHandler errorHandler = mock(ResponseErrorHandler.class);
|
||||
|
||||
@Bean
|
||||
public RestTemplateCustomizer testRestTemplateCustomizer() {
|
||||
|
||||
@@ -44,23 +44,19 @@ class DependencyMetadataJsonMapperTests {
|
||||
Repository repository = new Repository();
|
||||
repository.setName("foo-repo");
|
||||
repository.setUrl(new URL("http://example.com/foo"));
|
||||
BillOfMaterials bom = BillOfMaterials.create("org.foo", "foo-bom",
|
||||
"1.0.0.RELEASE");
|
||||
DependencyMetadata metadata = new DependencyMetadata(
|
||||
Version.parse("1.2.0.RELEASE"), Collections.singletonMap(d.getId(), d),
|
||||
Collections.singletonMap("repo-id", repository),
|
||||
BillOfMaterials bom = BillOfMaterials.create("org.foo", "foo-bom", "1.0.0.RELEASE");
|
||||
DependencyMetadata metadata = new DependencyMetadata(Version.parse("1.2.0.RELEASE"),
|
||||
Collections.singletonMap(d.getId(), d), Collections.singletonMap("repo-id", repository),
|
||||
Collections.singletonMap("bom-id", bom));
|
||||
JSONObject content = new JSONObject(this.mapper.write(metadata));
|
||||
assertThat(content.getJSONObject("dependencies").getJSONObject("foo")
|
||||
.getString("bom")).isEqualTo("my-bom");
|
||||
assertThat(content.getJSONObject("dependencies").getJSONObject("foo")
|
||||
.getString("repository")).isEqualTo("my-repo");
|
||||
assertThat(content.getJSONObject("repositories").getJSONObject("repo-id")
|
||||
.getString("name")).isEqualTo("foo-repo");
|
||||
assertThat(content.getJSONObject("boms").getJSONObject("bom-id")
|
||||
.getString("artifactId")).isEqualTo("foo-bom");
|
||||
assertThat(content.getJSONObject("boms").getJSONObject("bom-id")
|
||||
.getString("version")).isEqualTo("1.0.0.RELEASE");
|
||||
assertThat(content.getJSONObject("dependencies").getJSONObject("foo").getString("bom")).isEqualTo("my-bom");
|
||||
assertThat(content.getJSONObject("dependencies").getJSONObject("foo").getString("repository"))
|
||||
.isEqualTo("my-repo");
|
||||
assertThat(content.getJSONObject("repositories").getJSONObject("repo-id").getString("name"))
|
||||
.isEqualTo("foo-repo");
|
||||
assertThat(content.getJSONObject("boms").getJSONObject("bom-id").getString("artifactId")).isEqualTo("foo-bom");
|
||||
assertThat(content.getJSONObject("boms").getJSONObject("bom-id").getString("version"))
|
||||
.isEqualTo("1.0.0.RELEASE");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -40,24 +40,22 @@ class InitializrMetadataJsonMapperTests {
|
||||
@Test
|
||||
void withNoAppUrl() throws IOException {
|
||||
InitializrMetadata metadata = new InitializrMetadataTestBuilder()
|
||||
.addType("foo", true, "/foo.zip", "none", "test")
|
||||
.addDependencyGroup("foo", "one", "two").build();
|
||||
.addType("foo", true, "/foo.zip", "none", "test").addDependencyGroup("foo", "one", "two").build();
|
||||
String json = this.jsonMapper.write(metadata, null);
|
||||
JsonNode result = objectMapper.readTree(json);
|
||||
assertThat(get(result, "_links.foo.href")).isEqualTo(
|
||||
"/foo.zip?type=foo{&dependencies,packaging,javaVersion,language,bootVersion,"
|
||||
assertThat(get(result, "_links.foo.href"))
|
||||
.isEqualTo("/foo.zip?type=foo{&dependencies,packaging,javaVersion,language,bootVersion,"
|
||||
+ "groupId,artifactId,version,name,description,packageName}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void withAppUrl() throws IOException {
|
||||
InitializrMetadata metadata = new InitializrMetadataTestBuilder()
|
||||
.addType("foo", true, "/foo.zip", "none", "test")
|
||||
.addDependencyGroup("foo", "one", "two").build();
|
||||
.addType("foo", true, "/foo.zip", "none", "test").addDependencyGroup("foo", "one", "two").build();
|
||||
String json = this.jsonMapper.write(metadata, "http://server:8080/my-app");
|
||||
JsonNode result = objectMapper.readTree(json);
|
||||
assertThat(get(result, "_links.foo.href")).isEqualTo(
|
||||
"http://server:8080/my-app/foo.zip?type=foo{&dependencies,packaging,javaVersion,"
|
||||
assertThat(get(result, "_links.foo.href"))
|
||||
.isEqualTo("http://server:8080/my-app/foo.zip?type=foo{&dependencies,packaging,javaVersion,"
|
||||
+ "language,bootVersion,groupId,artifactId,version,name,description,packageName}");
|
||||
}
|
||||
|
||||
|
||||
@@ -55,8 +55,7 @@ class LinkMapperTests {
|
||||
assertThat(model.has("a")).isTrue();
|
||||
ObjectNode linkModel = (ObjectNode) model.get("a");
|
||||
assertThat(linkModel).hasSize(2);
|
||||
assertThat(linkModel.get("href").textValue())
|
||||
.isEqualTo("https://example.com/{bootVersion}/a");
|
||||
assertThat(linkModel.get("href").textValue()).isEqualTo("https://example.com/{bootVersion}/a");
|
||||
assertThat(linkModel.get("templated").booleanValue()).isEqualTo(true);
|
||||
}
|
||||
|
||||
@@ -70,10 +69,8 @@ class LinkMapperTests {
|
||||
assertThat(model.has("a")).isTrue();
|
||||
ArrayNode linksModel = (ArrayNode) model.get("a");
|
||||
assertThat(linksModel).hasSize(2);
|
||||
assertThat(linksModel.get(0).get("href").textValue())
|
||||
.isEqualTo("https://example.com");
|
||||
assertThat(linksModel.get(1).get("href").textValue())
|
||||
.isEqualTo("https://example.com/2");
|
||||
assertThat(linksModel.get(0).get("href").textValue()).isEqualTo("https://example.com");
|
||||
assertThat(linksModel.get(1).get("href").textValue()).isEqualTo("https://example.com/2");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -32,39 +32,32 @@ import org.springframework.test.context.ActiveProfiles;
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
@ActiveProfiles("test-default")
|
||||
class CommandLineExampleIntegrationTests
|
||||
extends AbstractInitializrControllerIntegrationTests {
|
||||
class CommandLineExampleIntegrationTests extends AbstractInitializrControllerIntegrationTests {
|
||||
|
||||
@Test
|
||||
void generateDefaultProject() {
|
||||
downloadZip("/starter.zip").isJavaProject().isMavenProject()
|
||||
.hasStaticAndTemplatesResources(false).pomAssert()
|
||||
.hasSpringBootStarterRootDependency().hasSpringBootStarterTest()
|
||||
.hasDependenciesCount(2);
|
||||
downloadZip("/starter.zip").isJavaProject().isMavenProject().hasStaticAndTemplatesResources(false).pomAssert()
|
||||
.hasSpringBootStarterRootDependency().hasSpringBootStarterTest().hasDependenciesCount(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateWebProjectWithJava8() {
|
||||
downloadZip("/starter.zip?dependencies=web&javaVersion=1.8").isJavaProject()
|
||||
.isMavenProject().hasStaticAndTemplatesResources(true).pomAssert()
|
||||
.hasJavaVersion("1.8").hasSpringBootStarterDependency("web")
|
||||
.hasSpringBootStarterTest().hasDependenciesCount(2);
|
||||
downloadZip("/starter.zip?dependencies=web&javaVersion=1.8").isJavaProject().isMavenProject()
|
||||
.hasStaticAndTemplatesResources(true).pomAssert().hasJavaVersion("1.8")
|
||||
.hasSpringBootStarterDependency("web").hasSpringBootStarterTest().hasDependenciesCount(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateWebDataJpaGradleProject() {
|
||||
downloadTgz(
|
||||
"/starter.tgz?dependencies=web,data-jpa&type=gradle-project&baseDir=my-dir")
|
||||
.hasBaseDir("my-dir").isJavaProject().isGradleProject()
|
||||
.hasStaticAndTemplatesResources(true).gradleBuildAssert()
|
||||
.contains("spring-boot-starter-web")
|
||||
.contains("spring-boot-starter-data-jpa");
|
||||
downloadTgz("/starter.tgz?dependencies=web,data-jpa&type=gradle-project&baseDir=my-dir").hasBaseDir("my-dir")
|
||||
.isJavaProject().isGradleProject().hasStaticAndTemplatesResources(true).gradleBuildAssert()
|
||||
.contains("spring-boot-starter-web").contains("spring-boot-starter-data-jpa");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateMavenPomWithWarPackaging() {
|
||||
ResponseEntity<String> response = getRestTemplate()
|
||||
.getForEntity(createUrl("/pom.xml?packaging=war"), String.class);
|
||||
ResponseEntity<String> response = getRestTemplate().getForEntity(createUrl("/pom.xml?packaging=war"),
|
||||
String.class);
|
||||
PomAssert pomAssert = new PomAssert(response.getBody());
|
||||
pomAssert.hasPackaging("war");
|
||||
}
|
||||
|
||||
@@ -26,19 +26,16 @@ import org.springframework.test.context.ActiveProfiles;
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
@ActiveProfiles({ "test-default", "test-custom-defaults" })
|
||||
class MainControllerDefaultsIntegrationTests
|
||||
extends AbstractInitializrControllerIntegrationTests {
|
||||
class MainControllerDefaultsIntegrationTests extends AbstractInitializrControllerIntegrationTests {
|
||||
|
||||
// see defaults customization
|
||||
|
||||
@Test
|
||||
void generateDefaultPom() {
|
||||
String content = getRestTemplate().getForObject(createUrl("/pom.xml?style=web"),
|
||||
String.class);
|
||||
String content = getRestTemplate().getForObject(createUrl("/pom.xml?style=web"), String.class);
|
||||
PomAssert pomAssert = new PomAssert(content);
|
||||
pomAssert.hasGroupId("org.foo").hasArtifactId("foo-bar")
|
||||
.hasVersion("1.2.4-SNAPSHOT").doesNotHaveNode("/project/packaging")
|
||||
.hasName("FooBar").hasDescription("FooBar Project");
|
||||
pomAssert.hasGroupId("org.foo").hasArtifactId("foo-bar").hasVersion("1.2.4-SNAPSHOT")
|
||||
.doesNotHaveNode("/project/packaging").hasName("FooBar").hasDescription("FooBar Project");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -33,13 +33,11 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
@ActiveProfiles("test-default")
|
||||
class MainControllerDependenciesTests
|
||||
extends AbstractInitializrControllerIntegrationTests {
|
||||
class MainControllerDependenciesTests extends AbstractInitializrControllerIntegrationTests {
|
||||
|
||||
@Test
|
||||
void noBootVersion() throws JSONException {
|
||||
ResponseEntity<String> response = execute("/dependencies", String.class, null,
|
||||
"application/json");
|
||||
ResponseEntity<String> response = execute("/dependencies", String.class, null, "application/json");
|
||||
assertThat(response.getHeaders().getFirst(HttpHeaders.ETAG)).isNotNull();
|
||||
validateContentType(response, CURRENT_METADATA_MEDIA_TYPE);
|
||||
validateDependenciesOutput("2.1.4", response.getBody());
|
||||
@@ -47,18 +45,15 @@ class MainControllerDependenciesTests
|
||||
|
||||
@Test
|
||||
void filteredDependencies() throws JSONException {
|
||||
ResponseEntity<String> response = execute(
|
||||
"/dependencies?bootVersion=2.2.1.RELEASE", String.class, null,
|
||||
ResponseEntity<String> response = execute("/dependencies?bootVersion=2.2.1.RELEASE", String.class, null,
|
||||
"application/json");
|
||||
assertThat(response.getHeaders().getFirst(HttpHeaders.ETAG)).isNotNull();
|
||||
validateContentType(response, CURRENT_METADATA_MEDIA_TYPE);
|
||||
validateDependenciesOutput("2.2.1", response.getBody());
|
||||
}
|
||||
|
||||
protected void validateDependenciesOutput(String version, String actual)
|
||||
throws JSONException {
|
||||
JSONObject expected = readJsonFrom(
|
||||
"metadata/dependencies/test-dependencies-" + version + ".json");
|
||||
protected void validateDependenciesOutput(String version, String actual) throws JSONException {
|
||||
JSONObject expected = readJsonFrom("metadata/dependencies/test-dependencies-" + version + ".json");
|
||||
JSONAssert.assertEquals(expected, new JSONObject(actual), JSONCompareMode.STRICT);
|
||||
}
|
||||
|
||||
|
||||
@@ -34,13 +34,11 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
@ActiveProfiles({ "test-default", "test-custom-env" })
|
||||
class MainControllerEnvIntegrationTests
|
||||
extends AbstractInitializrControllerIntegrationTests {
|
||||
class MainControllerEnvIntegrationTests extends AbstractInitializrControllerIntegrationTests {
|
||||
|
||||
@Test
|
||||
void downloadCliWithCustomRepository() throws Exception {
|
||||
ResponseEntity<?> entity = getRestTemplate().getForEntity(createUrl("/spring"),
|
||||
String.class);
|
||||
ResponseEntity<?> entity = getRestTemplate().getForEntity(createUrl("/spring"), String.class);
|
||||
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND);
|
||||
String expected = "https://repo.spring.io/lib-release/org/springframework/boot/spring-boot-cli/2.1.4.RELEASE/spring-boot-cli-2.1.4.RELEASE-bin.zip";
|
||||
assertThat(entity.getHeaders().getLocation()).isEqualTo(new URI(expected));
|
||||
@@ -49,10 +47,9 @@ class MainControllerEnvIntegrationTests
|
||||
@Test
|
||||
void generateProjectWithInvalidName() {
|
||||
downloadZip("/starter.zip?style=data-jpa&name=Invalid")
|
||||
.isJavaProject(ProjectAssert.DEFAULT_PACKAGE_NAME, "FooBarApplication")
|
||||
.isMavenProject().hasStaticAndTemplatesResources(false).pomAssert()
|
||||
.hasDependenciesCount(2).hasSpringBootStarterDependency("data-jpa")
|
||||
.hasSpringBootStarterTest();
|
||||
.isJavaProject(ProjectAssert.DEFAULT_PACKAGE_NAME, "FooBarApplication").isMavenProject()
|
||||
.hasStaticAndTemplatesResources(false).pomAssert().hasDependenciesCount(2)
|
||||
.hasSpringBootStarterDependency("data-jpa").hasSpringBootStarterTest();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -43,56 +43,47 @@ import static org.assertj.core.api.Assertions.fail;
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
@ActiveProfiles("test-default")
|
||||
class MainControllerIntegrationTests
|
||||
extends AbstractInitializrControllerIntegrationTests {
|
||||
class MainControllerIntegrationTests extends AbstractInitializrControllerIntegrationTests {
|
||||
|
||||
@Test
|
||||
void simpleZipProject() {
|
||||
ResponseEntity<byte[]> entity = downloadArchive(
|
||||
"/starter.zip?style=web&style=jpa");
|
||||
assertArchiveResponseHeaders(entity, MediaType.valueOf("application/zip"),
|
||||
"demo.zip");
|
||||
zipProjectAssert(entity.getBody()).isJavaProject().hasFile(".gitignore")
|
||||
.hasExecutableFile("mvnw").isMavenProject()
|
||||
.hasStaticAndTemplatesResources(true).pomAssert().hasDependenciesCount(3)
|
||||
.hasSpringBootStarterDependency("web")
|
||||
.hasSpringBootStarterDependency("data-jpa") // alias jpa -> data-jpa
|
||||
ResponseEntity<byte[]> entity = downloadArchive("/starter.zip?style=web&style=jpa");
|
||||
assertArchiveResponseHeaders(entity, MediaType.valueOf("application/zip"), "demo.zip");
|
||||
zipProjectAssert(entity.getBody()).isJavaProject().hasFile(".gitignore").hasExecutableFile("mvnw")
|
||||
.isMavenProject().hasStaticAndTemplatesResources(true).pomAssert().hasDependenciesCount(3)
|
||||
.hasSpringBootStarterDependency("web").hasSpringBootStarterDependency("data-jpa") // alias
|
||||
// jpa
|
||||
// ->
|
||||
// data-jpa
|
||||
.hasSpringBootStarterTest();
|
||||
}
|
||||
|
||||
@Test
|
||||
void simpleTgzProject() {
|
||||
ResponseEntity<byte[]> entity = downloadArchive(
|
||||
"/starter.tgz?style=org.acme:foo");
|
||||
assertArchiveResponseHeaders(entity, MediaType.valueOf("application/x-compress"),
|
||||
"demo.tar.gz");
|
||||
tgzProjectAssert(entity.getBody()).isJavaProject().hasFile(".gitignore")
|
||||
.hasExecutableFile("mvnw").isMavenProject()
|
||||
.hasStaticAndTemplatesResources(false).pomAssert().hasDependenciesCount(2)
|
||||
ResponseEntity<byte[]> entity = downloadArchive("/starter.tgz?style=org.acme:foo");
|
||||
assertArchiveResponseHeaders(entity, MediaType.valueOf("application/x-compress"), "demo.tar.gz");
|
||||
tgzProjectAssert(entity.getBody()).isJavaProject().hasFile(".gitignore").hasExecutableFile("mvnw")
|
||||
.isMavenProject().hasStaticAndTemplatesResources(false).pomAssert().hasDependenciesCount(2)
|
||||
.hasDependency("org.acme", "foo", "1.3.5");
|
||||
}
|
||||
|
||||
private void assertArchiveResponseHeaders(ResponseEntity<byte[]> entity,
|
||||
MediaType contentType, String fileName) {
|
||||
private void assertArchiveResponseHeaders(ResponseEntity<byte[]> entity, MediaType contentType, String fileName) {
|
||||
assertThat(entity.getHeaders().getContentType()).isEqualTo(contentType);
|
||||
assertThat(entity.getHeaders().getContentDisposition()).isNotNull();
|
||||
assertThat(entity.getHeaders().getContentDisposition().getFilename())
|
||||
.isEqualTo(fileName);
|
||||
assertThat(entity.getHeaders().getContentDisposition().getFilename()).isEqualTo(fileName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void dependencyInRange() {
|
||||
Dependency biz = Dependency.create("org.acme", "biz", "1.3.5", "runtime");
|
||||
downloadTgz("/starter.tgz?style=org.acme:biz&bootVersion=2.2.1.RELEASE")
|
||||
.isJavaProject().isMavenProject().hasStaticAndTemplatesResources(false)
|
||||
.pomAssert().hasDependenciesCount(3).hasDependency(biz);
|
||||
downloadTgz("/starter.tgz?style=org.acme:biz&bootVersion=2.2.1.RELEASE").isJavaProject().isMavenProject()
|
||||
.hasStaticAndTemplatesResources(false).pomAssert().hasDependenciesCount(3).hasDependency(biz);
|
||||
}
|
||||
|
||||
@Test
|
||||
void dependencyNotInRange() {
|
||||
try {
|
||||
execute("/starter.tgz?style=org.acme:bur", byte[].class, null,
|
||||
(String[]) null);
|
||||
execute("/starter.tgz?style=org.acme:bur", byte[].class, null, (String[]) null);
|
||||
}
|
||||
catch (HttpClientErrorException ex) {
|
||||
assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.NOT_ACCEPTABLE);
|
||||
@@ -101,18 +92,20 @@ class MainControllerIntegrationTests
|
||||
|
||||
@Test
|
||||
void noDependencyProject() {
|
||||
downloadZip("/starter.zip").isJavaProject().isMavenProject()
|
||||
.hasStaticAndTemplatesResources(false).pomAssert().hasDependenciesCount(2)
|
||||
downloadZip("/starter.zip").isJavaProject().isMavenProject().hasStaticAndTemplatesResources(false).pomAssert()
|
||||
.hasDependenciesCount(2)
|
||||
// the root dep is added if none is specified
|
||||
.hasSpringBootStarterRootDependency().hasSpringBootStarterTest();
|
||||
}
|
||||
|
||||
@Test
|
||||
void dependenciesIsAnAliasOfStyle() {
|
||||
downloadZip("/starter.zip?dependencies=web&dependencies=jpa").isJavaProject()
|
||||
.isMavenProject().hasStaticAndTemplatesResources(true).pomAssert()
|
||||
.hasDependenciesCount(3).hasSpringBootStarterDependency("web")
|
||||
.hasSpringBootStarterDependency("data-jpa") // alias jpa -> data-jpa
|
||||
downloadZip("/starter.zip?dependencies=web&dependencies=jpa").isJavaProject().isMavenProject()
|
||||
.hasStaticAndTemplatesResources(true).pomAssert().hasDependenciesCount(3)
|
||||
.hasSpringBootStarterDependency("web").hasSpringBootStarterDependency("data-jpa") // alias
|
||||
// jpa
|
||||
// ->
|
||||
// data-jpa
|
||||
.hasSpringBootStarterTest();
|
||||
}
|
||||
|
||||
@@ -120,23 +113,23 @@ class MainControllerIntegrationTests
|
||||
void dependenciesIsAnAliasOfStyleCommaSeparated() {
|
||||
downloadZip("/starter.zip?dependencies=web,jpa").isJavaProject().isMavenProject()
|
||||
.hasStaticAndTemplatesResources(true).pomAssert().hasDependenciesCount(3)
|
||||
.hasSpringBootStarterDependency("web")
|
||||
.hasSpringBootStarterDependency("data-jpa") // alias jpa -> data-jpa
|
||||
.hasSpringBootStarterDependency("web").hasSpringBootStarterDependency("data-jpa") // alias
|
||||
// jpa
|
||||
// ->
|
||||
// data-jpa
|
||||
.hasSpringBootStarterTest();
|
||||
}
|
||||
|
||||
@Test
|
||||
void kotlinRange() {
|
||||
downloadZip("/starter.zip?style=web&language=kotlin&bootVersion=2.0.1.RELEASE")
|
||||
.isKotlinProject().isMavenProject().pomAssert().hasDependenciesCount(4)
|
||||
.hasProperty("kotlin.version", "1.1");
|
||||
downloadZip("/starter.zip?style=web&language=kotlin&bootVersion=2.0.1.RELEASE").isKotlinProject()
|
||||
.isMavenProject().pomAssert().hasDependenciesCount(4).hasProperty("kotlin.version", "1.1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void gradleWarProject() {
|
||||
downloadZip(
|
||||
"/starter.zip?style=web&style=security&packaging=war&type=gradle-project")
|
||||
.isJavaWarProject().isGradleProject();
|
||||
downloadZip("/starter.zip?style=web&style=security&packaging=war&type=gradle-project").isJavaWarProject()
|
||||
.isGradleProject();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -159,10 +152,8 @@ class MainControllerIntegrationTests
|
||||
assertSpringCliRedirect("/spring.tgz", "tar.gz");
|
||||
}
|
||||
|
||||
private void assertSpringCliRedirect(String context, String extension)
|
||||
throws URISyntaxException {
|
||||
ResponseEntity<?> entity = getRestTemplate().getForEntity(createUrl(context),
|
||||
ResponseEntity.class);
|
||||
private void assertSpringCliRedirect(String context, String extension) throws URISyntaxException {
|
||||
ResponseEntity<?> entity = getRestTemplate().getForEntity(createUrl(context), ResponseEntity.class);
|
||||
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND);
|
||||
String expected = "https://repo.spring.io/release/org/springframework/boot/spring-boot-cli/2.1.4.RELEASE/spring-boot-cli-2.1.4.RELEASE-bin."
|
||||
+ extension;
|
||||
@@ -180,39 +171,31 @@ class MainControllerIntegrationTests
|
||||
@Disabled("Need a comparator that does not care about the number of elements in an array")
|
||||
public void currentMetadataCompatibleWithV2() {
|
||||
ResponseEntity<String> response = invokeHome(null, "*/*");
|
||||
validateMetadata(response,
|
||||
AbstractInitializrIntegrationTests.CURRENT_METADATA_MEDIA_TYPE, "2.0.0",
|
||||
validateMetadata(response, AbstractInitializrIntegrationTests.CURRENT_METADATA_MEDIA_TYPE, "2.0.0",
|
||||
JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void metadataWithV2AcceptHeader() {
|
||||
ResponseEntity<String> response = invokeHome(null,
|
||||
"application/vnd.initializr.v2+json");
|
||||
validateMetadata(response, InitializrMetadataVersion.V2.getMediaType(), "2.0.0",
|
||||
JSONCompareMode.STRICT);
|
||||
ResponseEntity<String> response = invokeHome(null, "application/vnd.initializr.v2+json");
|
||||
validateMetadata(response, InitializrMetadataVersion.V2.getMediaType(), "2.0.0", JSONCompareMode.STRICT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void metadataWithCurrentAcceptHeader() {
|
||||
getRequests().setFields("_links.maven-project", "dependencies.values[0]",
|
||||
"type.values[0]", "javaVersion.values[0]", "packaging.values[0]",
|
||||
"bootVersion.values[0]", "language.values[0]");
|
||||
ResponseEntity<String> response = invokeHome(null,
|
||||
"application/vnd.initializr.v2.1+json");
|
||||
getRequests().setFields("_links.maven-project", "dependencies.values[0]", "type.values[0]",
|
||||
"javaVersion.values[0]", "packaging.values[0]", "bootVersion.values[0]", "language.values[0]");
|
||||
ResponseEntity<String> response = invokeHome(null, "application/vnd.initializr.v2.1+json");
|
||||
assertThat(response.getHeaders().getFirst(HttpHeaders.ETAG)).isNotNull();
|
||||
validateContentType(response,
|
||||
AbstractInitializrIntegrationTests.CURRENT_METADATA_MEDIA_TYPE);
|
||||
validateContentType(response, AbstractInitializrIntegrationTests.CURRENT_METADATA_MEDIA_TYPE);
|
||||
validateCurrentMetadata(response.getBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
void metadataWithSeveralAcceptHeader() {
|
||||
ResponseEntity<String> response = invokeHome(null,
|
||||
"application/vnd.initializr.v2.1+json",
|
||||
ResponseEntity<String> response = invokeHome(null, "application/vnd.initializr.v2.1+json",
|
||||
"application/vnd.initializr.v2+json");
|
||||
validateContentType(response,
|
||||
AbstractInitializrIntegrationTests.CURRENT_METADATA_MEDIA_TYPE);
|
||||
validateContentType(response, AbstractInitializrIntegrationTests.CURRENT_METADATA_MEDIA_TYPE);
|
||||
validateCurrentMetadata(response.getBody());
|
||||
}
|
||||
|
||||
@@ -242,15 +225,13 @@ class MainControllerIntegrationTests
|
||||
|
||||
@Test
|
||||
void curlCanStillDownloadZipArchive() {
|
||||
ResponseEntity<byte[]> response = execute("/starter.zip", byte[].class,
|
||||
"curl/1.2.4", "*/*");
|
||||
ResponseEntity<byte[]> response = execute("/starter.zip", byte[].class, "curl/1.2.4", "*/*");
|
||||
zipProjectAssert(response.getBody()).isMavenProject().isJavaProject();
|
||||
}
|
||||
|
||||
@Test
|
||||
void curlCanStillDownloadTgzArchive() {
|
||||
ResponseEntity<byte[]> response = execute("/starter.tgz", byte[].class,
|
||||
"curl/1.2.4", "*/*");
|
||||
ResponseEntity<byte[]> response = execute("/starter.tgz", byte[].class, "curl/1.2.4", "*/*");
|
||||
tgzProjectAssert(response.getBody()).isMavenProject().isJavaProject();
|
||||
}
|
||||
|
||||
@@ -258,8 +239,7 @@ class MainControllerIntegrationTests
|
||||
// make sure curl can still receive metadata with json
|
||||
public void curlWithAcceptHeaderJson() {
|
||||
ResponseEntity<String> response = invokeHome("curl/1.2.4", "application/json");
|
||||
validateContentType(response,
|
||||
AbstractInitializrIntegrationTests.CURRENT_METADATA_MEDIA_TYPE);
|
||||
validateContentType(response, AbstractInitializrIntegrationTests.CURRENT_METADATA_MEDIA_TYPE);
|
||||
validateCurrentMetadata(response.getBody());
|
||||
}
|
||||
|
||||
@@ -285,8 +265,7 @@ class MainControllerIntegrationTests
|
||||
// make sure curl can still receive metadata with json
|
||||
public void httpieWithAcceptHeaderJson() {
|
||||
ResponseEntity<String> response = invokeHome("HTTPie/0.8.0", "application/json");
|
||||
validateContentType(response,
|
||||
AbstractInitializrIntegrationTests.CURRENT_METADATA_MEDIA_TYPE);
|
||||
validateContentType(response, AbstractInitializrIntegrationTests.CURRENT_METADATA_MEDIA_TYPE);
|
||||
validateCurrentMetadata(response.getBody());
|
||||
}
|
||||
|
||||
@@ -305,8 +284,7 @@ class MainControllerIntegrationTests
|
||||
@Test
|
||||
void springBootCliReceivesJsonByDefault() {
|
||||
ResponseEntity<String> response = invokeHome("SpringBootCli/1.2.0", "*/*");
|
||||
validateContentType(response,
|
||||
AbstractInitializrIntegrationTests.CURRENT_METADATA_MEDIA_TYPE);
|
||||
validateContentType(response, AbstractInitializrIntegrationTests.CURRENT_METADATA_MEDIA_TYPE);
|
||||
validateCurrentMetadata(response.getBody());
|
||||
}
|
||||
|
||||
@@ -339,22 +317,19 @@ class MainControllerIntegrationTests
|
||||
private void validateHttpIeHelpContent(ResponseEntity<String> response) {
|
||||
validateContentType(response, MediaType.TEXT_PLAIN);
|
||||
assertThat(response.getHeaders().getFirst(HttpHeaders.ETAG)).isNotNull();
|
||||
assertThat(response.getBody()).contains("Spring Initializr", "Examples:", "http")
|
||||
.doesNotContain("curl");
|
||||
assertThat(response.getBody()).contains("Spring Initializr", "Examples:", "http").doesNotContain("curl");
|
||||
}
|
||||
|
||||
private void validateGenericHelpContent(ResponseEntity<String> response) {
|
||||
validateContentType(response, MediaType.TEXT_PLAIN);
|
||||
assertThat(response.getHeaders().getFirst(HttpHeaders.ETAG)).isNotNull();
|
||||
assertThat(response.getBody()).contains("Spring Initializr")
|
||||
.doesNotContain("Examples:", "curl");
|
||||
assertThat(response.getBody()).contains("Spring Initializr").doesNotContain("Examples:", "curl");
|
||||
}
|
||||
|
||||
private void validateSpringBootHelpContent(ResponseEntity<String> response) {
|
||||
validateContentType(response, MediaType.TEXT_PLAIN);
|
||||
assertThat(response.getHeaders().getFirst(HttpHeaders.ETAG)).isNotNull();
|
||||
assertThat(response.getBody())
|
||||
.contains("Service capabilities", "Supported dependencies")
|
||||
assertThat(response.getBody()).contains("Service capabilities", "Supported dependencies")
|
||||
.doesNotContain("Examples:", "curl");
|
||||
}
|
||||
|
||||
@@ -379,8 +354,7 @@ class MainControllerIntegrationTests
|
||||
}
|
||||
catch (HttpClientErrorException ex) {
|
||||
assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
assertStandardErrorBody(ex.getResponseBodyAsString(),
|
||||
"Unknown dependency 'foo' check project metadata");
|
||||
assertStandardErrorBody(ex.getResponseBodyAsString(), "Unknown dependency 'foo' check project metadata");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -392,32 +366,28 @@ class MainControllerIntegrationTests
|
||||
|
||||
@Test
|
||||
void webIsAddedPom() {
|
||||
String body = getRestTemplate().getForObject(createUrl("/pom.xml?packaging=war"),
|
||||
String.class);
|
||||
String body = getRestTemplate().getForObject(createUrl("/pom.xml?packaging=war"), String.class);
|
||||
assertThat(body).contains("spring-boot-starter-web");
|
||||
assertThat(body).contains("provided");
|
||||
}
|
||||
|
||||
@Test
|
||||
void webIsAddedGradle() {
|
||||
String body = getRestTemplate()
|
||||
.getForObject(createUrl("/build.gradle?packaging=war"), String.class);
|
||||
String body = getRestTemplate().getForObject(createUrl("/build.gradle?packaging=war"), String.class);
|
||||
assertThat(body).contains("spring-boot-starter-web");
|
||||
assertThat(body).contains("providedRuntime");
|
||||
}
|
||||
|
||||
@Test
|
||||
void downloadStarter() {
|
||||
byte[] body = getRestTemplate().getForObject(createUrl("starter.zip"),
|
||||
byte[].class);
|
||||
byte[] body = getRestTemplate().getForObject(createUrl("starter.zip"), byte[].class);
|
||||
assertThat(body).isNotNull();
|
||||
assertThat(body.length).isGreaterThan(100);
|
||||
}
|
||||
|
||||
@Test
|
||||
void installer() {
|
||||
ResponseEntity<String> response = getRestTemplate()
|
||||
.getForEntity(createUrl("install.sh"), String.class);
|
||||
ResponseEntity<String> response = getRestTemplate().getForEntity(createUrl("install.sh"), String.class);
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getBody()).isNotNull();
|
||||
}
|
||||
|
||||
@@ -40,8 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
@ActiveProfiles("test-default")
|
||||
class MainControllerServiceMetadataIntegrationTests
|
||||
extends AbstractFullStackInitializrIntegrationTests {
|
||||
class MainControllerServiceMetadataIntegrationTests extends AbstractFullStackInitializrIntegrationTests {
|
||||
|
||||
@Autowired
|
||||
private InitializrMetadataProvider metadataProvider;
|
||||
@@ -50,21 +49,14 @@ class MainControllerServiceMetadataIntegrationTests
|
||||
void initializeRemoteConfig() throws Exception {
|
||||
InitializrMetadata localMetadata = this.metadataProvider.get();
|
||||
InitializrMetadata metadata = InitializrMetadataBuilder.create()
|
||||
.withInitializrMetadata(new UrlResource(createUrl("/metadata/config")))
|
||||
.build();
|
||||
.withInitializrMetadata(new UrlResource(createUrl("/metadata/config"))).build();
|
||||
// Basic assertions
|
||||
assertThat(metadata.getDependencies().getContent())
|
||||
.hasSameSizeAs(localMetadata.getDependencies().getContent());
|
||||
assertThat(metadata.getTypes().getContent())
|
||||
.hasSameSizeAs(localMetadata.getTypes().getContent());
|
||||
assertThat(metadata.getBootVersions().getContent())
|
||||
.hasSameSizeAs(localMetadata.getBootVersions().getContent());
|
||||
assertThat(metadata.getPackagings().getContent())
|
||||
.hasSameSizeAs(localMetadata.getPackagings().getContent());
|
||||
assertThat(metadata.getJavaVersions().getContent())
|
||||
.hasSameSizeAs(localMetadata.getJavaVersions().getContent());
|
||||
assertThat(metadata.getLanguages().getContent())
|
||||
.hasSameSizeAs(localMetadata.getLanguages().getContent());
|
||||
assertThat(metadata.getDependencies().getContent()).hasSameSizeAs(localMetadata.getDependencies().getContent());
|
||||
assertThat(metadata.getTypes().getContent()).hasSameSizeAs(localMetadata.getTypes().getContent());
|
||||
assertThat(metadata.getBootVersions().getContent()).hasSameSizeAs(localMetadata.getBootVersions().getContent());
|
||||
assertThat(metadata.getPackagings().getContent()).hasSameSizeAs(localMetadata.getPackagings().getContent());
|
||||
assertThat(metadata.getJavaVersions().getContent()).hasSameSizeAs(localMetadata.getJavaVersions().getContent());
|
||||
assertThat(metadata.getLanguages().getContent()).hasSameSizeAs(localMetadata.getLanguages().getContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -79,8 +71,7 @@ class MainControllerServiceMetadataIntegrationTests
|
||||
|
||||
@Test
|
||||
void validateJson() throws JSONException {
|
||||
ResponseEntity<String> response = execute("/metadata/config", String.class, null,
|
||||
"application/json");
|
||||
ResponseEntity<String> response = execute("/metadata/config", String.class, null, "application/json");
|
||||
validateContentType(response, MediaType.APPLICATION_JSON);
|
||||
JSONObject json = new JSONObject(response.getBody());
|
||||
JSONObject expected = readJsonFrom("metadata/config/test-default.json");
|
||||
@@ -89,8 +80,7 @@ class MainControllerServiceMetadataIntegrationTests
|
||||
|
||||
@Test
|
||||
void metadataClientEndpoint() {
|
||||
ResponseEntity<String> response = execute("/metadata/client", String.class, null,
|
||||
"application/json");
|
||||
ResponseEntity<String> response = execute("/metadata/client", String.class, null, "application/json");
|
||||
validateCurrentMetadata(response);
|
||||
}
|
||||
|
||||
|
||||
@@ -32,8 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
@ActiveProfiles({ "test-default", "test-ssl" })
|
||||
class MainControllerSslIntegrationTests
|
||||
extends AbstractInitializrControllerIntegrationTests {
|
||||
class MainControllerSslIntegrationTests extends AbstractInitializrControllerIntegrationTests {
|
||||
|
||||
@Test
|
||||
void forceSsl() {
|
||||
@@ -45,18 +44,14 @@ class MainControllerSslIntegrationTests
|
||||
|
||||
@Test
|
||||
void forceSslInMetadata() {
|
||||
ResponseEntity<String> response = invokeHome(null,
|
||||
"application/vnd.initializr.v2.1+json");
|
||||
validateMetadata(response, InitializrMetadataVersion.V2_1.getMediaType(),
|
||||
"2.1.0-ssl", JSONCompareMode.STRICT);
|
||||
ResponseEntity<String> response = invokeHome(null, "application/vnd.initializr.v2.1+json");
|
||||
validateMetadata(response, InitializrMetadataVersion.V2_1.getMediaType(), "2.1.0-ssl", JSONCompareMode.STRICT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void forceSslInMetadataV2() {
|
||||
ResponseEntity<String> response = invokeHome(null,
|
||||
"application/vnd.initializr.v2+json");
|
||||
validateMetadata(response, InitializrMetadataVersion.V2.getMediaType(),
|
||||
"2.0.0-ssl", JSONCompareMode.STRICT);
|
||||
ResponseEntity<String> response = invokeHome(null, "application/vnd.initializr.v2+json");
|
||||
validateMetadata(response, InitializrMetadataVersion.V2.getMediaType(), "2.0.0-ssl", JSONCompareMode.STRICT);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -31,14 +31,12 @@ import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
@ActiveProfiles("test-default")
|
||||
@Import(ProjectDescriptionCustomizerConfiguration.class)
|
||||
class ProjectGenerationDescriptionCustomizerTests
|
||||
extends AbstractInitializrControllerIntegrationTests {
|
||||
class ProjectGenerationDescriptionCustomizerTests extends AbstractInitializrControllerIntegrationTests {
|
||||
|
||||
@Test
|
||||
void projectDescriptionCustomizersAreInvoked() {
|
||||
downloadZip("/starter.zip?bootVersion=2.0.4.RELEASE&javaVersion=1.8")
|
||||
.isJavaProject().isMavenProject().pomAssert()
|
||||
.hasSpringBootParent("2.2.3.RELEASE").hasProperty("java.version", "1.7");
|
||||
downloadZip("/starter.zip?bootVersion=2.0.4.RELEASE&javaVersion=1.8").isJavaProject().isMavenProject()
|
||||
.pomAssert().hasSpringBootParent("2.2.3.RELEASE").hasProperty("java.version", "1.7");
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -58,22 +58,19 @@ import static org.mockito.Mockito.verify;
|
||||
*/
|
||||
public class ProjectGenerationInvokerTests {
|
||||
|
||||
private static final InitializrMetadata metadata = InitializrMetadataTestBuilder
|
||||
.withDefaults().build();
|
||||
private static final InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().build();
|
||||
|
||||
private ProjectGenerationInvoker invoker;
|
||||
|
||||
private AnnotationConfigApplicationContext context;
|
||||
|
||||
private final ApplicationEventPublisher eventPublisher = mock(
|
||||
ApplicationEventPublisher.class);
|
||||
private final ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
setupContext();
|
||||
ProjectRequestToDescriptionConverter converter = new ProjectRequestToDescriptionConverter();
|
||||
this.invoker = new ProjectGenerationInvoker(this.context, this.eventPublisher,
|
||||
converter);
|
||||
this.invoker = new ProjectGenerationInvoker(this.context, this.eventPublisher, converter);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -89,12 +86,11 @@ public class ProjectGenerationInvokerTests {
|
||||
WebProjectRequest request = new WebProjectRequest();
|
||||
request.setType("maven-project");
|
||||
request.initialize(metadata);
|
||||
ProjectGenerationResult result = this.invoker
|
||||
.invokeProjectStructureGeneration(request);
|
||||
ProjectGenerationResult result = this.invoker.invokeProjectStructureGeneration(request);
|
||||
new ProjectAssert(result.getRootDirectory()).isJavaProject();
|
||||
File file = result.getRootDirectory().toFile();
|
||||
Map<String, List<File>> tempFiles = (Map<String, List<File>>) ReflectionTestUtils
|
||||
.getField(this.invoker, "temporaryFiles");
|
||||
Map<String, List<File>> tempFiles = (Map<String, List<File>>) ReflectionTestUtils.getField(this.invoker,
|
||||
"temporaryFiles");
|
||||
assertThat(tempFiles.get(file.getName())).contains(file);
|
||||
verifyProjectSuccessfulEventFor(request);
|
||||
}
|
||||
@@ -119,11 +115,9 @@ public class ProjectGenerationInvokerTests {
|
||||
request.initialize(metadata);
|
||||
byte[] bytes = this.invoker.invokeBuildGeneration(request);
|
||||
String content = new String(bytes);
|
||||
new PomAssert(content).hasGroupId(request.getGroupId())
|
||||
.hasArtifactId(request.getArtifactId()).hasVersion(request.getVersion())
|
||||
.doesNotHaveNode("/project/packaging").hasName(request.getName())
|
||||
.hasDescription(request.getDescription())
|
||||
.hasJavaVersion(request.getJavaVersion())
|
||||
new PomAssert(content).hasGroupId(request.getGroupId()).hasArtifactId(request.getArtifactId())
|
||||
.hasVersion(request.getVersion()).doesNotHaveNode("/project/packaging").hasName(request.getName())
|
||||
.hasDescription(request.getDescription()).hasJavaVersion(request.getJavaVersion())
|
||||
.hasSpringBootParent(request.getBootVersion());
|
||||
verifyProjectSuccessfulEventFor(request);
|
||||
}
|
||||
@@ -135,8 +129,7 @@ public class ProjectGenerationInvokerTests {
|
||||
request.setType("gradle-project");
|
||||
byte[] bytes = this.invoker.invokeBuildGeneration(request);
|
||||
String content = new String(bytes);
|
||||
new GradleBuildAssert(content).hasVersion(request.getVersion())
|
||||
.hasSpringBootPlugin(request.getBootVersion())
|
||||
new GradleBuildAssert(content).hasVersion(request.getVersion()).hasSpringBootPlugin(request.getBootVersion())
|
||||
.hasJavaVersion(request.getJavaVersion());
|
||||
verifyProjectSuccessfulEventFor(request);
|
||||
}
|
||||
@@ -162,8 +155,8 @@ public class ProjectGenerationInvokerTests {
|
||||
File dir = tempDir.toFile();
|
||||
File distributionFile = this.invoker.createDistributionFile(dir, ".zip");
|
||||
assertThat(distributionFile.toString()).isEqualTo(dir.toString() + ".zip");
|
||||
Map<String, List<File>> tempFiles = (Map<String, List<File>>) ReflectionTestUtils
|
||||
.getField(this.invoker, "temporaryFiles");
|
||||
Map<String, List<File>> tempFiles = (Map<String, List<File>>) ReflectionTestUtils.getField(this.invoker,
|
||||
"temporaryFiles");
|
||||
assertThat(tempFiles.get(dir.getName())).contains(distributionFile);
|
||||
}
|
||||
|
||||
@@ -172,31 +165,26 @@ public class ProjectGenerationInvokerTests {
|
||||
WebProjectRequest request = new WebProjectRequest();
|
||||
request.initialize(metadata);
|
||||
request.setType("gradle-project");
|
||||
ProjectGenerationResult result = this.invoker
|
||||
.invokeProjectStructureGeneration(request);
|
||||
ProjectGenerationResult result = this.invoker.invokeProjectStructureGeneration(request);
|
||||
File file = result.getRootDirectory().toFile();
|
||||
this.invoker.cleanTempFiles(file);
|
||||
assertThat(file.listFiles()).isNull();
|
||||
}
|
||||
|
||||
private void setupContext() {
|
||||
InitializrMetadataProvider metadataProvider = mock(
|
||||
InitializrMetadataProvider.class);
|
||||
given(metadataProvider.get())
|
||||
.willReturn(InitializrMetadataTestBuilder.withDefaults().build());
|
||||
InitializrMetadataProvider metadataProvider = mock(InitializrMetadataProvider.class);
|
||||
given(metadataProvider.get()).willReturn(InitializrMetadataTestBuilder.withDefaults().build());
|
||||
this.context = new AnnotationConfigApplicationContext();
|
||||
this.context.register(TestConfiguration.class);
|
||||
this.context.refresh();
|
||||
}
|
||||
|
||||
protected void verifyProjectSuccessfulEventFor(ProjectRequest request) {
|
||||
verify(this.eventPublisher, times(1))
|
||||
.publishEvent(argThat(new ProjectGeneratedEventMatcher(request)));
|
||||
verify(this.eventPublisher, times(1)).publishEvent(argThat(new ProjectGeneratedEventMatcher(request)));
|
||||
}
|
||||
|
||||
protected void verifyProjectFailedEventFor(ProjectRequest request, Exception ex) {
|
||||
verify(this.eventPublisher, times(1))
|
||||
.publishEvent(argThat(new ProjectFailedEventMatcher(request, ex)));
|
||||
verify(this.eventPublisher, times(1)).publishEvent(argThat(new ProjectFailedEventMatcher(request, ex)));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -224,8 +212,7 @@ public class ProjectGenerationInvokerTests {
|
||||
|
||||
}
|
||||
|
||||
private static class ProjectFailedEventMatcher
|
||||
implements ArgumentMatcher<ProjectFailedEvent> {
|
||||
private static class ProjectFailedEventMatcher implements ArgumentMatcher<ProjectFailedEvent> {
|
||||
|
||||
private final ProjectRequest request;
|
||||
|
||||
@@ -238,14 +225,12 @@ public class ProjectGenerationInvokerTests {
|
||||
|
||||
@Override
|
||||
public boolean matches(ProjectFailedEvent event) {
|
||||
return this.request.equals(event.getProjectRequest())
|
||||
&& this.cause.equals(event.getCause());
|
||||
return this.request.equals(event.getProjectRequest()) && this.cause.equals(event.getCause());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static class ProjectGeneratedEventMatcher
|
||||
implements ArgumentMatcher<ProjectGeneratedEvent> {
|
||||
private static class ProjectGeneratedEventMatcher implements ArgumentMatcher<ProjectGeneratedEvent> {
|
||||
|
||||
private final ProjectRequest request;
|
||||
|
||||
|
||||
@@ -39,8 +39,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
*/
|
||||
public class ProjectRequestToDescriptionConverterTests {
|
||||
|
||||
private InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
|
||||
.build();
|
||||
private InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().build();
|
||||
|
||||
private final ProjectRequestToDescriptionConverter converter = new ProjectRequestToDescriptionConverter();
|
||||
|
||||
@@ -57,14 +56,12 @@ public class ProjectRequestToDescriptionConverterTests {
|
||||
public void convertWhenTypeDoesNotDefineBuildTagShouldThrowException() {
|
||||
Type type = new Type();
|
||||
type.setId("example-project");
|
||||
InitializrMetadata testMetadata = InitializrMetadataTestBuilder.withDefaults()
|
||||
.addType(type).build();
|
||||
InitializrMetadata testMetadata = InitializrMetadataTestBuilder.withDefaults().addType(type).build();
|
||||
ProjectRequest request = createProjectRequest();
|
||||
request.setType("example-project");
|
||||
assertThatExceptionOfType(InvalidProjectRequestException.class)
|
||||
.isThrownBy(() -> this.converter.convert(request, testMetadata))
|
||||
.withMessage(
|
||||
"Invalid type 'example-project' (missing build tag) check project metadata");
|
||||
.withMessage("Invalid type 'example-project' (missing build tag) check project metadata");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -73,8 +70,7 @@ public class ProjectRequestToDescriptionConverterTests {
|
||||
request.setBootVersion("1.2.3.M4");
|
||||
assertThatExceptionOfType(InvalidProjectRequestException.class)
|
||||
.isThrownBy(() -> this.converter.convert(request, this.metadata))
|
||||
.withMessage(
|
||||
"Invalid Spring Boot version 1.2.3.M4 must be 1.5.0 or higher");
|
||||
.withMessage("Invalid Spring Boot version 1.2.3.M4 must be 1.5.0 or higher");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -108,14 +104,13 @@ public class ProjectRequestToDescriptionConverterTests {
|
||||
void convertWhenDependencyOutOfRangeShouldThrowException() {
|
||||
Dependency dependency = Dependency.withId("foo");
|
||||
dependency.setRange(new VersionRange(Version.parse("2.2.0.M1")));
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
|
||||
.addDependencyGroup("foo", dependency).build();
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().addDependencyGroup("foo", dependency)
|
||||
.build();
|
||||
ProjectRequest request = createProjectRequest();
|
||||
request.setDependencies(Collections.singletonList("foo"));
|
||||
assertThatExceptionOfType(InvalidProjectRequestException.class)
|
||||
.isThrownBy(() -> this.converter.convert(request, metadata))
|
||||
.withMessage("Dependency 'foo' is not compatible "
|
||||
+ "with Spring Boot 2.1.1.RELEASE");
|
||||
.withMessage("Dependency 'foo' is not compatible " + "with Spring Boot 2.1.1.RELEASE");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -172,8 +167,7 @@ public class ProjectRequestToDescriptionConverterTests {
|
||||
Type type = new Type();
|
||||
type.setId("example-type");
|
||||
type.getTags().put("build", "gradle");
|
||||
InitializrMetadata testMetadata = InitializrMetadataTestBuilder.withDefaults()
|
||||
.addType(type).build();
|
||||
InitializrMetadata testMetadata = InitializrMetadataTestBuilder.withDefaults().addType(type).build();
|
||||
ProjectRequest request = createProjectRequest();
|
||||
request.setType("example-type");
|
||||
ProjectDescription description = this.converter.convert(request, testMetadata);
|
||||
@@ -208,8 +202,7 @@ public class ProjectRequestToDescriptionConverterTests {
|
||||
void convertShouldUseDefaultPlatformVersionFromMetadata() {
|
||||
ProjectRequest request = createProjectRequest();
|
||||
ProjectDescription description = this.converter.convert(request, this.metadata);
|
||||
assertThat(description.getPlatformVersion())
|
||||
.isEqualTo(Version.parse("2.1.1.RELEASE"));
|
||||
assertThat(description.getPlatformVersion()).isEqualTo(Version.parse("2.1.1.RELEASE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -250,8 +243,7 @@ public class ProjectRequestToDescriptionConverterTests {
|
||||
ProjectRequest request = createProjectRequest();
|
||||
request.setDescription(" ");
|
||||
ProjectDescription description = this.converter.convert(request, this.metadata);
|
||||
assertThat(description.getDescription())
|
||||
.isEqualTo("Demo project for Spring Boot");
|
||||
assertThat(description.getDescription()).isEqualTo("Demo project for Spring Boot");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -71,8 +71,7 @@ class AgentTests {
|
||||
|
||||
@Test
|
||||
void checkIntelliJIDEAWithVersion() {
|
||||
Agent agent = Agent
|
||||
.fromUserAgent("IntelliJ IDEA/144.2 (Community edition; en-us)");
|
||||
Agent agent = Agent.fromUserAgent("IntelliJ IDEA/144.2 (Community edition; en-us)");
|
||||
assertThat(agent.getId()).isEqualTo(Agent.AgentId.INTELLIJ_IDEA);
|
||||
assertThat(agent.getVersion()).isEqualTo("144.2");
|
||||
}
|
||||
@@ -100,8 +99,7 @@ class AgentTests {
|
||||
|
||||
@Test
|
||||
void checkGenericBrowser() {
|
||||
Agent agent = Agent.fromUserAgent(
|
||||
"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5 Build/MMB29K) ");
|
||||
Agent agent = Agent.fromUserAgent("Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5 Build/MMB29K) ");
|
||||
assertThat(agent.getId()).isEqualTo(Agent.AgentId.BROWSER);
|
||||
assertThat(agent.getVersion()).isNull();
|
||||
}
|
||||
|
||||
@@ -40,18 +40,14 @@ class CommandLineHelpGeneratorTests {
|
||||
|
||||
@BeforeEach
|
||||
public void init() {
|
||||
this.generator = new CommandLineHelpGenerator(
|
||||
new MustacheTemplateRenderer("classpath:/templates"));
|
||||
this.generator = new CommandLineHelpGenerator(new MustacheTemplateRenderer("classpath:/templates"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateGenericCapabilities() throws IOException {
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
|
||||
.addDependencyGroup("test", createDependency("id-b", "depB"),
|
||||
createDependency("id-a", "depA", "and some description"))
|
||||
.build();
|
||||
String content = this.generator.generateGenericCapabilities(metadata,
|
||||
"https://fake-service");
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().addDependencyGroup("test",
|
||||
createDependency("id-b", "depB"), createDependency("id-a", "depA", "and some description")).build();
|
||||
String content = this.generator.generateGenericCapabilities(metadata, "https://fake-service");
|
||||
assertCommandLineCapabilities(content);
|
||||
assertThat(content).contains("id-a | and some description |");
|
||||
assertThat(content).contains("id-b | depB");
|
||||
@@ -66,10 +62,8 @@ class CommandLineHelpGeneratorTests {
|
||||
type.setId("foo");
|
||||
type.setName("foo-name");
|
||||
type.setDescription("foo-desc");
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
|
||||
.addType(type).build();
|
||||
String content = this.generator.generateGenericCapabilities(metadata,
|
||||
"https://fake-service");
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().addType(type).build();
|
||||
String content = this.generator.generateGenericCapabilities(metadata, "https://fake-service");
|
||||
assertCommandLineCapabilities(content);
|
||||
assertThat(content).contains("| foo");
|
||||
assertThat(content).contains("| foo-desc");
|
||||
@@ -81,8 +75,7 @@ class CommandLineHelpGeneratorTests {
|
||||
dependency.setAliases(Arrays.asList("legacy", "another"));
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
|
||||
.addDependencyGroup("test", dependency).build();
|
||||
String content = this.generator.generateGenericCapabilities(metadata,
|
||||
"https://fake-service");
|
||||
String content = this.generator.generateGenericCapabilities(metadata, "https://fake-service");
|
||||
assertCommandLineCapabilities(content);
|
||||
assertThat(content).contains("dep | some description |");
|
||||
assertThat(content).doesNotContain("legacy").doesNotContain("another");
|
||||
@@ -90,12 +83,9 @@ class CommandLineHelpGeneratorTests {
|
||||
|
||||
@Test
|
||||
void generateCurlCapabilities() throws IOException {
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
|
||||
.addDependencyGroup("test", createDependency("id-b", "depB"),
|
||||
createDependency("id-a", "depA", "and some description"))
|
||||
.build();
|
||||
String content = this.generator.generateCurlCapabilities(metadata,
|
||||
"https://fake-service");
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().addDependencyGroup("test",
|
||||
createDependency("id-b", "depB"), createDependency("id-a", "depA", "and some description")).build();
|
||||
String content = this.generator.generateCurlCapabilities(metadata, "https://fake-service");
|
||||
assertCommandLineCapabilities(content);
|
||||
assertThat(content).contains("id-a | and some description |");
|
||||
assertThat(content).contains("id-b | depB");
|
||||
@@ -106,12 +96,9 @@ class CommandLineHelpGeneratorTests {
|
||||
|
||||
@Test
|
||||
void generateHttpCapabilities() throws IOException {
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
|
||||
.addDependencyGroup("test", createDependency("id-b", "depB"),
|
||||
createDependency("id-a", "depA", "and some description"))
|
||||
.build();
|
||||
String content = this.generator.generateHttpieCapabilities(metadata,
|
||||
"https://fake-service");
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().addDependencyGroup("test",
|
||||
createDependency("id-b", "depB"), createDependency("id-a", "depA", "and some description")).build();
|
||||
String content = this.generator.generateHttpieCapabilities(metadata, "https://fake-service");
|
||||
assertCommandLineCapabilities(content);
|
||||
assertThat(content).contains("id-a | and some description |");
|
||||
assertThat(content).contains("id-b | depB");
|
||||
@@ -123,12 +110,9 @@ class CommandLineHelpGeneratorTests {
|
||||
|
||||
@Test
|
||||
void generateSpringBootCliCapabilities() throws IOException {
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
|
||||
.addDependencyGroup("test", createDependency("id-b", "depB"),
|
||||
createDependency("id-a", "depA", "and some description"))
|
||||
.build();
|
||||
String content = this.generator.generateSpringBootCliCapabilities(metadata,
|
||||
"https://fake-service");
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().addDependencyGroup("test",
|
||||
createDependency("id-b", "depB"), createDependency("id-a", "depA", "and some description")).build();
|
||||
String content = this.generator.generateSpringBootCliCapabilities(metadata, "https://fake-service");
|
||||
assertThat(content).contains("| Id");
|
||||
assertThat(content).contains("| Tags");
|
||||
assertThat(content).contains("id-a | and some description |");
|
||||
@@ -152,12 +136,9 @@ class CommandLineHelpGeneratorTests {
|
||||
second.setVersionRange(" [1.2.0.RELEASE,1.3.0.M1) ");
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
|
||||
.addDependencyGroup("test", first, second).build();
|
||||
String content = this.generator.generateSpringBootCliCapabilities(metadata,
|
||||
"https://fake-service");
|
||||
assertThat(content)
|
||||
.contains("| first | first desc | >=1.2.0.RELEASE |");
|
||||
assertThat(content)
|
||||
.contains("| second | second desc | >=1.2.0.RELEASE and <1.3.0.M1 |");
|
||||
String content = this.generator.generateSpringBootCliCapabilities(metadata, "https://fake-service");
|
||||
assertThat(content).contains("| first | first desc | >=1.2.0.RELEASE |");
|
||||
assertThat(content).contains("| second | second desc | >=1.2.0.RELEASE and <1.3.0.M1 |");
|
||||
}
|
||||
|
||||
private static void assertCommandLineCapabilities(String content) {
|
||||
@@ -172,8 +153,7 @@ class CommandLineHelpGeneratorTests {
|
||||
return createDependency(id, name, null);
|
||||
}
|
||||
|
||||
private static Dependency createDependency(String id, String name,
|
||||
String description) {
|
||||
private static Dependency createDependency(String id, String name, String description) {
|
||||
Dependency dependency = Dependency.withId(id);
|
||||
dependency.setDescription(description);
|
||||
dependency.setName(name);
|
||||
|
||||
@@ -43,8 +43,7 @@ class DefaultDependencyMetadataProviderTests {
|
||||
third.setVersionRange("2.1.8.RELEASE");
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
|
||||
.addDependencyGroup("test", first, second, third).build();
|
||||
DependencyMetadata dependencyMetadata = this.provider.get(metadata,
|
||||
Version.parse("2.1.5.RELEASE"));
|
||||
DependencyMetadata dependencyMetadata = this.provider.get(metadata, Version.parse("2.1.5.RELEASE"));
|
||||
assertThat(dependencyMetadata.getDependencies()).hasSize(2);
|
||||
assertThat(dependencyMetadata.getRepositories()).isEmpty();
|
||||
assertThat(dependencyMetadata.getBoms()).isEmpty();
|
||||
@@ -55,34 +54,24 @@ class DefaultDependencyMetadataProviderTests {
|
||||
@Test
|
||||
void resolveDependencies() {
|
||||
Dependency first = Dependency.withId("first", "org.foo", "first");
|
||||
first.getMappings().add(Dependency.Mapping.create(
|
||||
"[1.0.0.RELEASE, 1.1.0.RELEASE)", "org.bar", "second", "0.1.0.RELEASE"));
|
||||
first.getMappings().add(Dependency.Mapping.create("1.1.0.RELEASE", "org.biz",
|
||||
"third", "0.2.0.RELEASE"));
|
||||
first.getMappings()
|
||||
.add(Dependency.Mapping.create("[1.0.0.RELEASE, 1.1.0.RELEASE)", "org.bar", "second", "0.1.0.RELEASE"));
|
||||
first.getMappings().add(Dependency.Mapping.create("1.1.0.RELEASE", "org.biz", "third", "0.2.0.RELEASE"));
|
||||
Dependency second = Dependency.withId("second", "org.foo", "second");
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
|
||||
.addDependencyGroup("test", first, second).build();
|
||||
|
||||
DependencyMetadata dependencyMetadata = this.provider.get(metadata,
|
||||
Version.parse("1.0.5.RELEASE"));
|
||||
DependencyMetadata dependencyMetadata = this.provider.get(metadata, Version.parse("1.0.5.RELEASE"));
|
||||
assertThat(dependencyMetadata.getDependencies()).hasSize(2);
|
||||
assertThat(dependencyMetadata.getDependencies().get("first").getGroupId())
|
||||
.isEqualTo("org.bar");
|
||||
assertThat(dependencyMetadata.getDependencies().get("first").getArtifactId())
|
||||
.isEqualTo("second");
|
||||
assertThat(dependencyMetadata.getDependencies().get("first").getVersion())
|
||||
.isEqualTo("0.1.0.RELEASE");
|
||||
assertThat(dependencyMetadata.getDependencies().get("first").getGroupId()).isEqualTo("org.bar");
|
||||
assertThat(dependencyMetadata.getDependencies().get("first").getArtifactId()).isEqualTo("second");
|
||||
assertThat(dependencyMetadata.getDependencies().get("first").getVersion()).isEqualTo("0.1.0.RELEASE");
|
||||
|
||||
DependencyMetadata anotherDependencyMetadata = this.provider.get(metadata,
|
||||
Version.parse("1.1.0.RELEASE"));
|
||||
DependencyMetadata anotherDependencyMetadata = this.provider.get(metadata, Version.parse("1.1.0.RELEASE"));
|
||||
assertThat(anotherDependencyMetadata.getDependencies()).hasSize(2);
|
||||
assertThat(anotherDependencyMetadata.getDependencies().get("first").getGroupId())
|
||||
.isEqualTo("org.biz");
|
||||
assertThat(
|
||||
anotherDependencyMetadata.getDependencies().get("first").getArtifactId())
|
||||
.isEqualTo("third");
|
||||
assertThat(anotherDependencyMetadata.getDependencies().get("first").getVersion())
|
||||
.isEqualTo("0.2.0.RELEASE");
|
||||
assertThat(anotherDependencyMetadata.getDependencies().get("first").getGroupId()).isEqualTo("org.biz");
|
||||
assertThat(anotherDependencyMetadata.getDependencies().get("first").getArtifactId()).isEqualTo("third");
|
||||
assertThat(anotherDependencyMetadata.getDependencies().get("first").getVersion()).isEqualTo("0.2.0.RELEASE");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -95,13 +84,12 @@ class DefaultDependencyMetadataProviderTests {
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
|
||||
.addRepository("repo-foo", "my-repo", "http://localhost", false)
|
||||
.addDependencyGroup("test", first, second, third).build();
|
||||
DependencyMetadata dependencyMetadata = this.provider.get(metadata,
|
||||
Version.parse("1.1.5.RELEASE"));
|
||||
DependencyMetadata dependencyMetadata = this.provider.get(metadata, Version.parse("1.1.5.RELEASE"));
|
||||
assertThat(dependencyMetadata.getDependencies()).hasSize(3);
|
||||
assertThat(dependencyMetadata.getRepositories()).hasSize(1);
|
||||
assertThat(dependencyMetadata.getBoms()).isEmpty();
|
||||
assertThat(dependencyMetadata.getRepositories().get("repo-foo")).isSameAs(
|
||||
metadata.getConfiguration().getEnv().getRepositories().get("repo-foo"));
|
||||
assertThat(dependencyMetadata.getRepositories().get("repo-foo"))
|
||||
.isSameAs(metadata.getConfiguration().getEnv().getRepositories().get("repo-foo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -113,66 +101,45 @@ class DefaultDependencyMetadataProviderTests {
|
||||
third.setBom("bom-foo");
|
||||
|
||||
BillOfMaterials bom = BillOfMaterials.create("org.foo", "bom");
|
||||
bom.getMappings().add(BillOfMaterials.Mapping
|
||||
.create("[1.0.0.RELEASE, 1.1.8.RELEASE)", "1.0.0.RELEASE"));
|
||||
bom.getMappings()
|
||||
.add(BillOfMaterials.Mapping.create("1.1.8.RELEASE", "2.0.0.RELEASE"));
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
|
||||
.addBom("bom-foo", bom).addDependencyGroup("test", first, second, third)
|
||||
.build();
|
||||
DependencyMetadata dependencyMetadata = this.provider.get(metadata,
|
||||
Version.parse("1.1.5.RELEASE"));
|
||||
bom.getMappings().add(BillOfMaterials.Mapping.create("[1.0.0.RELEASE, 1.1.8.RELEASE)", "1.0.0.RELEASE"));
|
||||
bom.getMappings().add(BillOfMaterials.Mapping.create("1.1.8.RELEASE", "2.0.0.RELEASE"));
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().addBom("bom-foo", bom)
|
||||
.addDependencyGroup("test", first, second, third).build();
|
||||
DependencyMetadata dependencyMetadata = this.provider.get(metadata, Version.parse("1.1.5.RELEASE"));
|
||||
assertThat(dependencyMetadata.getDependencies()).hasSize(3);
|
||||
assertThat(dependencyMetadata.getRepositories()).isEmpty();
|
||||
assertThat(dependencyMetadata.getBoms()).hasSize(1);
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getGroupId())
|
||||
.isEqualTo("org.foo");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getArtifactId())
|
||||
.isEqualTo("bom");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getVersion())
|
||||
.isEqualTo("1.0.0.RELEASE");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getGroupId()).isEqualTo("org.foo");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getArtifactId()).isEqualTo("bom");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getVersion()).isEqualTo("1.0.0.RELEASE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void repoFromBomAccordingToVersion() {
|
||||
DependencyMetadata dependencyMetadata = testRepoFromBomAccordingToVersion(
|
||||
"1.0.9.RELEASE");
|
||||
assertThat(dependencyMetadata.getBootVersion())
|
||||
.isEqualTo(Version.parse("1.0.9.RELEASE"));
|
||||
DependencyMetadata dependencyMetadata = testRepoFromBomAccordingToVersion("1.0.9.RELEASE");
|
||||
assertThat(dependencyMetadata.getBootVersion()).isEqualTo(Version.parse("1.0.9.RELEASE"));
|
||||
assertThat(dependencyMetadata.getDependencies()).hasSize(3);
|
||||
assertThat(dependencyMetadata.getRepositories()).hasSize(2);
|
||||
assertThat(dependencyMetadata.getBoms()).hasSize(1);
|
||||
assertThat(dependencyMetadata.getRepositories().get("repo-foo").getName())
|
||||
.isEqualTo("foo");
|
||||
assertThat(dependencyMetadata.getRepositories().get("repo-bar").getName())
|
||||
.isEqualTo("bar");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getGroupId())
|
||||
.isEqualTo("org.foo");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getArtifactId())
|
||||
.isEqualTo("bom");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getVersion())
|
||||
.isEqualTo("2.0.0.RELEASE");
|
||||
assertThat(dependencyMetadata.getRepositories().get("repo-foo").getName()).isEqualTo("foo");
|
||||
assertThat(dependencyMetadata.getRepositories().get("repo-bar").getName()).isEqualTo("bar");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getGroupId()).isEqualTo("org.foo");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getArtifactId()).isEqualTo("bom");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getVersion()).isEqualTo("2.0.0.RELEASE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void repoFromBomAccordingToAnotherVersion() {
|
||||
DependencyMetadata dependencyMetadata = testRepoFromBomAccordingToVersion(
|
||||
"1.1.5.RELEASE");
|
||||
assertThat(dependencyMetadata.getBootVersion())
|
||||
.isEqualTo(Version.parse("1.1.5.RELEASE"));
|
||||
DependencyMetadata dependencyMetadata = testRepoFromBomAccordingToVersion("1.1.5.RELEASE");
|
||||
assertThat(dependencyMetadata.getBootVersion()).isEqualTo(Version.parse("1.1.5.RELEASE"));
|
||||
assertThat(dependencyMetadata.getDependencies()).hasSize(3);
|
||||
assertThat(dependencyMetadata.getRepositories()).hasSize(2);
|
||||
assertThat(dependencyMetadata.getBoms()).hasSize(1);
|
||||
assertThat(dependencyMetadata.getRepositories().get("repo-foo").getName())
|
||||
.isEqualTo("foo");
|
||||
assertThat(dependencyMetadata.getRepositories().get("repo-biz").getName())
|
||||
.isEqualTo("biz");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getGroupId())
|
||||
.isEqualTo("org.foo");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getArtifactId())
|
||||
.isEqualTo("bom");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getVersion())
|
||||
.isEqualTo("3.0.0.RELEASE");
|
||||
assertThat(dependencyMetadata.getRepositories().get("repo-foo").getName()).isEqualTo("foo");
|
||||
assertThat(dependencyMetadata.getRepositories().get("repo-biz").getName()).isEqualTo("biz");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getGroupId()).isEqualTo("org.foo");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getArtifactId()).isEqualTo("bom");
|
||||
assertThat(dependencyMetadata.getBoms().get("bom-foo").getVersion()).isEqualTo("3.0.0.RELEASE");
|
||||
}
|
||||
|
||||
private DependencyMetadata testRepoFromBomAccordingToVersion(String bootVersion) {
|
||||
@@ -183,13 +150,10 @@ class DefaultDependencyMetadataProviderTests {
|
||||
third.setBom("bom-foo");
|
||||
|
||||
BillOfMaterials bom = BillOfMaterials.create("org.foo", "bom");
|
||||
bom.getMappings()
|
||||
.add(BillOfMaterials.Mapping.create("[1.0.0.RELEASE, 1.1.0.RELEASE)",
|
||||
"2.0.0.RELEASE", "repo-foo", "repo-bar"));
|
||||
bom.getMappings().add(BillOfMaterials.Mapping.create("1.1.0.RELEASE",
|
||||
"3.0.0.RELEASE", "repo-biz"));
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults()
|
||||
.addBom("bom-foo", bom)
|
||||
bom.getMappings().add(BillOfMaterials.Mapping.create("[1.0.0.RELEASE, 1.1.0.RELEASE)", "2.0.0.RELEASE",
|
||||
"repo-foo", "repo-bar"));
|
||||
bom.getMappings().add(BillOfMaterials.Mapping.create("1.1.0.RELEASE", "3.0.0.RELEASE", "repo-biz"));
|
||||
InitializrMetadata metadata = InitializrMetadataTestBuilder.withDefaults().addBom("bom-foo", bom)
|
||||
.addRepository("repo-foo", "foo", "http://localhost", false)
|
||||
.addRepository("repo-bar", "bar", "http://localhost", false)
|
||||
.addRepository("repo-biz", "biz", "http://localhost", false)
|
||||
|
||||
@@ -35,11 +35,9 @@ class DefaultInitializrMetadataProviderTests {
|
||||
void strategyIsInvokedOnGet() {
|
||||
InitializrMetadata metadata = mock(InitializrMetadata.class);
|
||||
InitializrMetadata updatedMetadata = mock(InitializrMetadata.class);
|
||||
InitializrMetadataUpdateStrategy updateStrategy = mock(
|
||||
InitializrMetadataUpdateStrategy.class);
|
||||
InitializrMetadataUpdateStrategy updateStrategy = mock(InitializrMetadataUpdateStrategy.class);
|
||||
given(updateStrategy.update(metadata)).willReturn(updatedMetadata);
|
||||
DefaultInitializrMetadataProvider provider = new DefaultInitializrMetadataProvider(
|
||||
metadata, updateStrategy);
|
||||
DefaultInitializrMetadataProvider provider = new DefaultInitializrMetadataProvider(metadata, updateStrategy);
|
||||
assertThat(provider.get()).isEqualTo(updatedMetadata);
|
||||
verify(updateStrategy).update(metadata);
|
||||
}
|
||||
|
||||
@@ -59,20 +59,16 @@ class DefaultInitializrMetadataUpdateStrategyTests {
|
||||
|
||||
@Test
|
||||
void bootVersionsAreReplaced() {
|
||||
InitializrMetadata metadata = new InitializrMetadataTestBuilder()
|
||||
.addBootVersion("0.0.9.RELEASE", true)
|
||||
InitializrMetadata metadata = new InitializrMetadataTestBuilder().addBootVersion("0.0.9.RELEASE", true)
|
||||
.addBootVersion("0.0.8.RELEASE", false).build();
|
||||
assertThat(metadata.getBootVersions().getDefault().getId())
|
||||
.isEqualTo("0.0.9.RELEASE");
|
||||
assertThat(metadata.getBootVersions().getDefault().getId()).isEqualTo("0.0.9.RELEASE");
|
||||
DefaultInitializrMetadataUpdateStrategy provider = new DefaultInitializrMetadataUpdateStrategy(
|
||||
this.restTemplate, objectMapper);
|
||||
expectJson(metadata.getConfiguration().getEnv().getSpringBootMetadataUrl(),
|
||||
"metadata/sagan/spring-boot.json");
|
||||
expectJson(metadata.getConfiguration().getEnv().getSpringBootMetadataUrl(), "metadata/sagan/spring-boot.json");
|
||||
|
||||
InitializrMetadata updatedMetadata = provider.update(metadata);
|
||||
assertThat(updatedMetadata.getBootVersions()).isNotNull();
|
||||
List<DefaultMetadataElement> updatedBootVersions = updatedMetadata
|
||||
.getBootVersions().getContent();
|
||||
List<DefaultMetadataElement> updatedBootVersions = updatedMetadata.getBootVersions().getContent();
|
||||
assertThat(updatedBootVersions).hasSize(4);
|
||||
assertBootVersion(updatedBootVersions.get(0), "1.4.1 (SNAPSHOT)", false);
|
||||
assertBootVersion(updatedBootVersions.get(1), "1.4.0", true);
|
||||
@@ -82,11 +78,9 @@ class DefaultInitializrMetadataUpdateStrategyTests {
|
||||
|
||||
@Test
|
||||
void defaultBootVersionIsAlwaysSet() {
|
||||
InitializrMetadata metadata = new InitializrMetadataTestBuilder()
|
||||
.addBootVersion("0.0.9.RELEASE", true)
|
||||
InitializrMetadata metadata = new InitializrMetadataTestBuilder().addBootVersion("0.0.9.RELEASE", true)
|
||||
.addBootVersion("0.0.8.RELEASE", false).build();
|
||||
assertThat(metadata.getBootVersions().getDefault().getId())
|
||||
.isEqualTo("0.0.9.RELEASE");
|
||||
assertThat(metadata.getBootVersions().getDefault().getId()).isEqualTo("0.0.9.RELEASE");
|
||||
DefaultInitializrMetadataUpdateStrategy provider = new DefaultInitializrMetadataUpdateStrategy(
|
||||
this.restTemplate, objectMapper);
|
||||
expectJson(metadata.getConfiguration().getEnv().getSpringBootMetadataUrl(),
|
||||
@@ -94,8 +88,7 @@ class DefaultInitializrMetadataUpdateStrategyTests {
|
||||
|
||||
InitializrMetadata updatedMetadata = provider.update(metadata);
|
||||
assertThat(updatedMetadata.getBootVersions()).isNotNull();
|
||||
List<DefaultMetadataElement> updatedBootVersions = updatedMetadata
|
||||
.getBootVersions().getContent();
|
||||
List<DefaultMetadataElement> updatedBootVersions = updatedMetadata.getBootVersions().getContent();
|
||||
assertThat(updatedBootVersions).hasSize(4);
|
||||
assertBootVersion(updatedBootVersions.get(0), "1.3.1 (SNAPSHOT)", true);
|
||||
assertBootVersion(updatedBootVersions.get(1), "1.3.0", false);
|
||||
@@ -103,8 +96,7 @@ class DefaultInitializrMetadataUpdateStrategyTests {
|
||||
assertBootVersion(updatedBootVersions.get(3), "1.2.5", false);
|
||||
}
|
||||
|
||||
private static void assertBootVersion(DefaultMetadataElement actual, String name,
|
||||
boolean defaultVersion) {
|
||||
private static void assertBootVersion(DefaultMetadataElement actual, String name, boolean defaultVersion) {
|
||||
assertThat(actual.getName()).isEqualTo(name);
|
||||
assertThat(actual.isDefault()).isEqualTo(defaultVersion);
|
||||
}
|
||||
@@ -113,8 +105,7 @@ class DefaultInitializrMetadataUpdateStrategyTests {
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
|
||||
this.mockServer.expect(requestTo(url)).andExpect(method(HttpMethod.GET))
|
||||
.andRespond(withStatus(HttpStatus.OK)
|
||||
.body(new ClassPathResource(bodyPath)).headers(httpHeaders));
|
||||
.andRespond(withStatus(HttpStatus.OK).body(new ClassPathResource(bodyPath)).headers(httpHeaders));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -42,26 +42,20 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat
|
||||
*/
|
||||
class SpringBootMetadataReaderTests {
|
||||
|
||||
private final InitializrMetadata metadata = InitializrMetadataBuilder.create()
|
||||
.build();
|
||||
private final InitializrMetadata metadata = InitializrMetadataBuilder.create().build();
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
private final RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
private final MockRestServiceServer server = MockRestServiceServer
|
||||
.bindTo(this.restTemplate).build();
|
||||
private final MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate).build();
|
||||
|
||||
@Test
|
||||
void readAvailableVersions() throws IOException {
|
||||
this.server.expect(requestTo("https://spring.io/project_metadata/spring-boot"))
|
||||
.andRespond(withSuccess(
|
||||
new ClassPathResource("metadata/sagan/spring-boot.json"),
|
||||
MediaType.APPLICATION_JSON));
|
||||
List<DefaultMetadataElement> versions = new SpringBootMetadataReader(
|
||||
this.objectMapper, this.restTemplate,
|
||||
this.metadata.getConfiguration().getEnv().getSpringBootMetadataUrl())
|
||||
.getBootVersions();
|
||||
this.server.expect(requestTo("https://spring.io/project_metadata/spring-boot")).andRespond(
|
||||
withSuccess(new ClassPathResource("metadata/sagan/spring-boot.json"), MediaType.APPLICATION_JSON));
|
||||
List<DefaultMetadataElement> versions = new SpringBootMetadataReader(this.objectMapper, this.restTemplate,
|
||||
this.metadata.getConfiguration().getEnv().getSpringBootMetadataUrl()).getBootVersions();
|
||||
assertThat(versions).as("spring boot versions should not be null").isNotNull();
|
||||
AtomicBoolean defaultFound = new AtomicBoolean(false);
|
||||
versions.forEach((it) -> {
|
||||
|
||||
@@ -34,8 +34,7 @@ final class JsonFieldPath {
|
||||
private static final Pattern BRACKETS_AND_ARRAY_PATTERN = Pattern
|
||||
.compile("\\[\'(.+?)\'\\]|\\[([0-9]+|\\*){0,1}\\]");
|
||||
|
||||
private static final Pattern ARRAY_INDEX_PATTERN = Pattern
|
||||
.compile("\\[([0-9]+|\\*){0,1}\\]");
|
||||
private static final Pattern ARRAY_INDEX_PATTERN = Pattern.compile("\\[([0-9]+|\\*){0,1}\\]");
|
||||
|
||||
private final String rawPath;
|
||||
|
||||
@@ -45,8 +44,7 @@ final class JsonFieldPath {
|
||||
|
||||
private final boolean array;
|
||||
|
||||
private JsonFieldPath(String rawPath, List<String> segments, boolean precise,
|
||||
boolean array) {
|
||||
private JsonFieldPath(String rawPath, List<String> segments, boolean precise, boolean array) {
|
||||
this.rawPath = rawPath;
|
||||
this.segments = segments;
|
||||
this.precise = precise;
|
||||
@@ -98,8 +96,7 @@ final class JsonFieldPath {
|
||||
List<String> segments = new ArrayList<>();
|
||||
while (matcher.find()) {
|
||||
if (previous != matcher.start()) {
|
||||
segments.addAll(extractDotSeparatedSegments(
|
||||
path.substring(previous, matcher.start())));
|
||||
segments.addAll(extractDotSeparatedSegments(path.substring(previous, matcher.start())));
|
||||
}
|
||||
if (matcher.group(1) != null) {
|
||||
segments.add(matcher.group(1));
|
||||
|
||||
@@ -33,15 +33,13 @@ final class JsonFieldProcessor {
|
||||
|
||||
boolean hasField(JsonFieldPath fieldPath, Object payload) {
|
||||
final AtomicReference<Boolean> hasField = new AtomicReference<>(false);
|
||||
traverse(new ProcessingContext(payload, fieldPath),
|
||||
(match) -> hasField.set(true));
|
||||
traverse(new ProcessingContext(payload, fieldPath), (match) -> hasField.set(true));
|
||||
return hasField.get();
|
||||
}
|
||||
|
||||
Object extract(JsonFieldPath path, Object payload) {
|
||||
final List<Object> matches = new ArrayList<>();
|
||||
traverse(new ProcessingContext(payload, path),
|
||||
(match) -> matches.add(match.getValue()));
|
||||
traverse(new ProcessingContext(payload, path), (match) -> matches.add(match.getValue()));
|
||||
if (matches.isEmpty()) {
|
||||
throw new IllegalArgumentException("Field does not exist: " + path);
|
||||
}
|
||||
@@ -64,40 +62,32 @@ final class JsonFieldProcessor {
|
||||
handleListPayload(context, matchCallback);
|
||||
}
|
||||
}
|
||||
else if (context.getPayload() instanceof Map
|
||||
&& ((Map<?, ?>) context.getPayload()).containsKey(segment)) {
|
||||
else if (context.getPayload() instanceof Map && ((Map<?, ?>) context.getPayload()).containsKey(segment)) {
|
||||
handleMapPayload(context, matchCallback);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleListPayload(ProcessingContext context,
|
||||
MatchCallback matchCallback) {
|
||||
private void handleListPayload(ProcessingContext context, MatchCallback matchCallback) {
|
||||
List<?> list = context.getPayload();
|
||||
final Iterator<?> items = list.iterator();
|
||||
if (context.isLeaf()) {
|
||||
while (items.hasNext()) {
|
||||
Object item = items.next();
|
||||
matchCallback.foundMatch(
|
||||
new ListMatch(items, list, item, context.getParentMatch()));
|
||||
matchCallback.foundMatch(new ListMatch(items, list, item, context.getParentMatch()));
|
||||
}
|
||||
}
|
||||
else {
|
||||
while (items.hasNext()) {
|
||||
Object item = items.next();
|
||||
traverse(
|
||||
context.descend(item,
|
||||
new ListMatch(items, list, item, context.parent)),
|
||||
matchCallback);
|
||||
traverse(context.descend(item, new ListMatch(items, list, item, context.parent)), matchCallback);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void handleMapPayload(ProcessingContext context,
|
||||
MatchCallback matchCallback) {
|
||||
private void handleMapPayload(ProcessingContext context, MatchCallback matchCallback) {
|
||||
Map<?, ?> map = context.getPayload();
|
||||
Object item = map.get(context.getSegment());
|
||||
MapMatch mapMatch = new MapMatch(item, map, context.getSegment(),
|
||||
context.getParentMatch());
|
||||
MapMatch mapMatch = new MapMatch(item, map, context.getSegment(), context.getParentMatch());
|
||||
if (context.isLeaf()) {
|
||||
matchCallback.foundMatch(mapMatch);
|
||||
}
|
||||
@@ -198,8 +188,7 @@ final class JsonFieldProcessor {
|
||||
this(payload, path, null, null);
|
||||
}
|
||||
|
||||
private ProcessingContext(Object payload, JsonFieldPath path,
|
||||
List<String> segments, Match parent) {
|
||||
private ProcessingContext(Object payload, JsonFieldPath path, List<String> segments, Match parent) {
|
||||
this.payload = payload;
|
||||
this.path = path;
|
||||
this.segments = (segments != null) ? segments : path.getSegments();
|
||||
@@ -224,8 +213,7 @@ final class JsonFieldProcessor {
|
||||
}
|
||||
|
||||
private ProcessingContext descend(Object payload, Match match) {
|
||||
return new ProcessingContext(payload, this.path,
|
||||
this.segments.subList(1, this.segments.size()), match);
|
||||
return new ProcessingContext(payload, this.path, this.segments.subList(1, this.segments.size()), match);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -62,37 +62,30 @@ public class MockMvcClientHttpRequestFactory implements ClientHttpRequestFactory
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClientHttpRequest createRequest(final URI uri, final HttpMethod httpMethod)
|
||||
throws IOException {
|
||||
public ClientHttpRequest createRequest(final URI uri, final HttpMethod httpMethod) throws IOException {
|
||||
return new MockClientHttpRequest(httpMethod, uri) {
|
||||
@Override
|
||||
public ClientHttpResponse executeInternal() throws IOException {
|
||||
try {
|
||||
MockHttpServletRequestBuilder requestBuilder = request(httpMethod,
|
||||
uri.toString());
|
||||
MockHttpServletRequestBuilder requestBuilder = request(httpMethod, uri.toString());
|
||||
requestBuilder.content(getBodyAsBytes());
|
||||
requestBuilder.headers(getHeaders());
|
||||
MockHttpServletResponse servletResponse = actions(requestBuilder)
|
||||
.andReturn().getResponse();
|
||||
MockHttpServletResponse servletResponse = actions(requestBuilder).andReturn().getResponse();
|
||||
HttpStatus status = HttpStatus.valueOf(servletResponse.getStatus());
|
||||
if (status.value() >= 400) {
|
||||
requestBuilder = request(HttpMethod.GET, "/error")
|
||||
.requestAttr(RequestDispatcher.ERROR_STATUS_CODE,
|
||||
status.value())
|
||||
.requestAttr(RequestDispatcher.ERROR_REQUEST_URI,
|
||||
uri.toString());
|
||||
.requestAttr(RequestDispatcher.ERROR_STATUS_CODE, status.value())
|
||||
.requestAttr(RequestDispatcher.ERROR_REQUEST_URI, uri.toString());
|
||||
if (servletResponse.getErrorMessage() != null) {
|
||||
requestBuilder.requestAttr(RequestDispatcher.ERROR_MESSAGE,
|
||||
servletResponse.getErrorMessage());
|
||||
}
|
||||
// Overwrites the snippets from the first request
|
||||
servletResponse = actions(requestBuilder).andReturn()
|
||||
.getResponse();
|
||||
servletResponse = actions(requestBuilder).andReturn().getResponse();
|
||||
}
|
||||
byte[] body = servletResponse.getContentAsByteArray();
|
||||
HttpHeaders headers = getResponseHeaders(servletResponse);
|
||||
MockClientHttpResponse clientResponse = new MockClientHttpResponse(
|
||||
body, status);
|
||||
MockClientHttpResponse clientResponse = new MockClientHttpResponse(body, status);
|
||||
clientResponse.getHeaders().putAll(headers);
|
||||
return clientResponse;
|
||||
}
|
||||
@@ -104,16 +97,13 @@ public class MockMvcClientHttpRequestFactory implements ClientHttpRequestFactory
|
||||
};
|
||||
}
|
||||
|
||||
private ResultActions actions(MockHttpServletRequestBuilder requestBuilder)
|
||||
throws Exception {
|
||||
ResultActions actions = MockMvcClientHttpRequestFactory.this.mockMvc
|
||||
.perform(requestBuilder);
|
||||
private ResultActions actions(MockHttpServletRequestBuilder requestBuilder) throws Exception {
|
||||
ResultActions actions = MockMvcClientHttpRequestFactory.this.mockMvc.perform(requestBuilder);
|
||||
List<Snippet> snippets = new ArrayList<>();
|
||||
for (String field : this.fields) {
|
||||
snippets.add(new ResponseFieldSnippet(field));
|
||||
}
|
||||
actions.andDo(document(this.label, preprocessResponse(prettyPrint()),
|
||||
snippets.toArray(new Snippet[0])));
|
||||
actions.andDo(document(this.label, preprocessResponse(prettyPrint()), snippets.toArray(new Snippet[0])));
|
||||
this.fields = new ArrayList<>();
|
||||
return actions;
|
||||
}
|
||||
|
||||
@@ -24,20 +24,17 @@ import org.springframework.test.web.servlet.MockMvc;
|
||||
/**
|
||||
* @author Dave Syer
|
||||
*/
|
||||
public final class MockMvcClientHttpRequestFactoryTestExecutionListener
|
||||
extends AbstractTestExecutionListener {
|
||||
public final class MockMvcClientHttpRequestFactoryTestExecutionListener extends AbstractTestExecutionListener {
|
||||
|
||||
private MockMvcClientHttpRequestFactory factory;
|
||||
|
||||
@Override
|
||||
public void beforeTestClass(TestContext testContext) throws Exception {
|
||||
ConfigurableBeanFactory beanFactory = (ConfigurableBeanFactory) testContext
|
||||
.getApplicationContext().getAutowireCapableBeanFactory();
|
||||
ConfigurableBeanFactory beanFactory = (ConfigurableBeanFactory) testContext.getApplicationContext()
|
||||
.getAutowireCapableBeanFactory();
|
||||
if (!beanFactory.containsBean("mockMvcClientHttpRequestFactory")) {
|
||||
this.factory = new MockMvcClientHttpRequestFactory(
|
||||
beanFactory.getBean(MockMvc.class));
|
||||
beanFactory.registerSingleton("mockMvcClientHttpRequestFactory",
|
||||
this.factory);
|
||||
this.factory = new MockMvcClientHttpRequestFactory(beanFactory.getBean(MockMvc.class));
|
||||
beanFactory.registerSingleton("mockMvcClientHttpRequestFactory", this.factory);
|
||||
}
|
||||
else {
|
||||
this.factory = beanFactory.getBean("mockMvcClientHttpRequestFactory",
|
||||
|
||||
@@ -80,12 +80,10 @@ public class ResponseFieldSnippet extends TemplatedSnippet {
|
||||
*/
|
||||
@Override
|
||||
public void document(Operation operation) throws IOException {
|
||||
RestDocumentationContext context = (RestDocumentationContext) operation
|
||||
.getAttributes().get(RestDocumentationContext.class.getName());
|
||||
WriterResolver writerResolver = (WriterResolver) operation.getAttributes()
|
||||
.get(WriterResolver.class.getName());
|
||||
try (Writer writer = writerResolver.resolve(
|
||||
operation.getName() + "/" + getSnippetName(), this.file, context)) {
|
||||
RestDocumentationContext context = (RestDocumentationContext) operation.getAttributes()
|
||||
.get(RestDocumentationContext.class.getName());
|
||||
WriterResolver writerResolver = (WriterResolver) operation.getAttributes().get(WriterResolver.class.getName());
|
||||
try (Writer writer = writerResolver.resolve(operation.getName() + "/" + getSnippetName(), this.file, context)) {
|
||||
Map<String, Object> model = createModel(operation);
|
||||
model.putAll(getAttributes());
|
||||
TemplateEngine templateEngine = (TemplateEngine) operation.getAttributes()
|
||||
@@ -97,15 +95,12 @@ public class ResponseFieldSnippet extends TemplatedSnippet {
|
||||
@Override
|
||||
protected Map<String, Object> createModel(Operation operation) {
|
||||
try {
|
||||
Object object = this.objectMapper.readValue(
|
||||
operation.getResponse().getContentAsString(), Object.class);
|
||||
Object field = this.fieldProcessor.extract(JsonFieldPath.compile(this.path),
|
||||
object);
|
||||
Object object = this.objectMapper.readValue(operation.getResponse().getContentAsString(), Object.class);
|
||||
Object field = this.fieldProcessor.extract(JsonFieldPath.compile(this.path), object);
|
||||
if (field instanceof List && this.index != null) {
|
||||
field = ((List<?>) field).get(this.index);
|
||||
}
|
||||
return Collections.singletonMap("value",
|
||||
this.objectMapper.writeValueAsString(field));
|
||||
return Collections.singletonMap("value", this.objectMapper.writeValueAsString(field));
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
|
||||
Reference in New Issue
Block a user