Upgrade to spring-javaformat 0.0.11

This commit is contained in:
Andy Wilkinson
2019-06-07 09:44:58 +01:00
parent d548c5ed31
commit 8f1be4cded
1940 changed files with 16814 additions and 28498 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -68,8 +68,7 @@ public final class SpringCli {
}
private static void addServiceLoaderCommands(CommandRunner runner) {
ServiceLoader<CommandFactory> factories = ServiceLoader
.load(CommandFactory.class);
ServiceLoader<CommandFactory> factories = ServiceLoader.load(CommandFactory.class);
for (CommandFactory factory : factories) {
runner.addCommands(factory.getCommands());
}
@@ -81,8 +80,7 @@ public final class SpringCli {
private static URL[] getExtensionURLs() {
List<URL> urls = new ArrayList<URL>();
String home = SystemPropertyUtils
.resolvePlaceholders("${spring.home:${SPRING_HOME:.}}");
String home = SystemPropertyUtils.resolvePlaceholders("${spring.home:${SPRING_HOME:.}}");
File extDirectory = new File(new File(home, "lib"), "ext");
if (extDirectory.isDirectory()) {
for (File file : extDirectory.listFiles()) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -59,12 +59,10 @@ public class SpringApplicationLauncher {
public Object launch(Object[] sources, String[] args) throws Exception {
Map<String, Object> defaultProperties = new HashMap<String, Object>();
defaultProperties.put("spring.groovy.template.check-template-location", "false");
Class<?> applicationClass = this.classLoader
.loadClass(getSpringApplicationClassName());
Class<?> applicationClass = this.classLoader.loadClass(getSpringApplicationClassName());
Constructor<?> constructor = applicationClass.getConstructor(Object[].class);
Object application = constructor.newInstance((Object) sources);
applicationClass.getMethod("setDefaultProperties", Map.class).invoke(application,
defaultProperties);
applicationClass.getMethod("setDefaultProperties", Map.class).invoke(application, defaultProperties);
Method method = applicationClass.getMethod("run", String[].class);
return method.invoke(application, (Object) args);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,8 +32,7 @@ import org.springframework.boot.web.support.SpringBootServletInitializer;
* @author Phillip Webb
* @since 1.3.0
*/
public class SpringApplicationWebApplicationInitializer
extends SpringBootServletInitializer {
public class SpringApplicationWebApplicationInitializer extends SpringBootServletInitializer {
/**
* The entry containing the source class.
@@ -76,8 +75,7 @@ public class SpringApplicationWebApplicationInitializer
for (int i = 0; i < this.sources.length; i++) {
sourceClasses[i] = classLoader.loadClass(this.sources[i]);
}
return builder.sources(sourceClasses)
.properties("spring.groovy.template.check-template-location=false");
return builder.sources(sourceClasses).properties("spring.groovy.template.check-template-location=false");
}
catch (Exception ex) {
throw new IllegalStateException(ex);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -46,8 +46,7 @@ public final class PackagedSpringApplicationLauncher {
}
private void run(String[] args) throws Exception {
URLClassLoader classLoader = (URLClassLoader) Thread.currentThread()
.getContextClassLoader();
URLClassLoader classLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
new SpringApplicationLauncher(classLoader).launch(getSources(classLoader), args);
}
@@ -61,8 +60,7 @@ public final class PackagedSpringApplicationLauncher {
return loadClasses(classLoader, sources.split(","));
}
}
throw new IllegalStateException(
"Cannot locate " + SOURCE_ENTRY + " in MANIFEST.MF");
throw new IllegalStateException("Cannot locate " + SOURCE_ENTRY + " in MANIFEST.MF");
}
private boolean isCliPackaged(Manifest manifest) {
@@ -71,8 +69,7 @@ public final class PackagedSpringApplicationLauncher {
return getClass().getName().equals(startClass);
}
private Class<?>[] loadClasses(ClassLoader classLoader, String[] names)
throws ClassNotFoundException {
private Class<?>[] loadClasses(ClassLoader classLoader, String[] names) throws ClassNotFoundException {
Class<?>[] classes = new Class<?>[names.length];
for (int i = 0; i < names.length; i++) {
classes[i] = classLoader.loadClass(names[i]);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -148,8 +148,7 @@ public class CommandRunner implements Iterable<Command> {
public Command findCommand(String name) {
for (Command candidate : this.commands) {
String candidateName = candidate.getName();
if (candidateName.equals(name) || (isOptionCommand(candidate)
&& ("--" + candidateName).equals(name))) {
if (candidateName.equals(name) || (isOptionCommand(candidate) && ("--" + candidateName).equals(name))) {
return candidate;
}
}
@@ -252,8 +251,7 @@ public class CommandRunner implements Iterable<Command> {
if (options.contains(CommandException.Option.SHOW_USAGE)) {
showUsage();
}
if (debug || couldNotShowMessage
|| options.contains(CommandException.Option.STACK_TRACE)) {
if (debug || couldNotShowMessage || options.contains(CommandException.Option.STACK_TRACE)) {
printStackTrace(ex);
}
return 1;
@@ -280,19 +278,16 @@ public class CommandRunner implements Iterable<Command> {
String usageHelp = command.getUsageHelp();
String description = command.getDescription();
Log.info(String.format("%n %1$s %2$-15s%n %3$s", command.getName(),
(usageHelp != null) ? usageHelp : "",
(description != null) ? description : ""));
(usageHelp != null) ? usageHelp : "", (description != null) ? description : ""));
}
}
Log.info("");
Log.info("Common options:");
Log.info(String.format("%n %1$s %2$-15s%n %3$s", "-d, --debug",
"Verbose mode",
Log.info(String.format("%n %1$s %2$-15s%n %3$s", "-d, --debug", "Verbose mode",
"Print additional status information for the command you are running"));
Log.info("");
Log.info("");
Log.info("See '" + this.name
+ "help <command>' for more information on a specific command.");
Log.info("See '" + this.name + "help <command>' for more information on a specific command.");
}
protected void printStackTrace(Exception ex) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,8 +33,7 @@ public abstract class OptionParsingCommand extends AbstractCommand {
private final OptionHandler handler;
protected OptionParsingCommand(String name, String description,
OptionHandler handler) {
protected OptionParsingCommand(String name, String description, OptionHandler handler) {
super(name, description);
this.handler = handler;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -78,8 +78,7 @@ import org.springframework.util.Assert;
*/
abstract class ArchiveCommand extends OptionParsingCommand {
protected ArchiveCommand(String name, String description,
OptionHandler optionHandler) {
protected ArchiveCommand(String name, String description, OptionHandler optionHandler) {
super(name, description, optionHandler);
}
@@ -113,35 +112,28 @@ abstract class ArchiveCommand extends OptionParsingCommand {
@Override
protected void doOptions() {
this.includeOption = option("include",
"Pattern applied to directories on the classpath to find files to "
+ "include in the resulting ").withRequiredArg()
.withValuesSeparatedBy(",").defaultsTo("");
this.excludeOption = option("exclude",
"Pattern applied to directories on the classpath to find files to "
+ "exclude from the resulting " + this.type).withRequiredArg()
.withValuesSeparatedBy(",").defaultsTo("");
"Pattern applied to directories on the classpath to find files to " + "include in the resulting ")
.withRequiredArg().withValuesSeparatedBy(",").defaultsTo("");
this.excludeOption = option("exclude", "Pattern applied to directories on the classpath to find files to "
+ "exclude from the resulting " + this.type).withRequiredArg().withValuesSeparatedBy(",")
.defaultsTo("");
}
@Override
protected ExitStatus run(OptionSet options) throws Exception {
List<?> nonOptionArguments = new ArrayList<Object>(
options.nonOptionArguments());
Assert.isTrue(nonOptionArguments.size() >= 2, "The name of the resulting "
+ this.type + " and at least one source file must be specified");
List<?> nonOptionArguments = new ArrayList<Object>(options.nonOptionArguments());
Assert.isTrue(nonOptionArguments.size() >= 2,
"The name of the resulting " + this.type + " and at least one source file must be specified");
File output = new File((String) nonOptionArguments.remove(0));
Assert.isTrue(
output.getName().toLowerCase(Locale.ENGLISH)
.endsWith("." + this.type),
"The output '" + output + "' is not a "
+ this.type.toUpperCase(Locale.ENGLISH) + " file.");
Assert.isTrue(output.getName().toLowerCase(Locale.ENGLISH).endsWith("." + this.type),
"The output '" + output + "' is not a " + this.type.toUpperCase(Locale.ENGLISH) + " file.");
deleteIfExists(output);
GroovyCompiler compiler = createCompiler(options);
List<URL> classpath = getClassPathUrls(compiler);
List<MatchedResource> classpathEntries = findMatchingClasspathEntries(
classpath, options);
List<MatchedResource> classpathEntries = findMatchingClasspathEntries(classpath, options);
String[] sources = new SourceOptions(nonOptionArguments).getSourcesArray();
Class<?>[] compiledClasses = compiler.compile(sources);
@@ -155,16 +147,15 @@ abstract class ArchiveCommand extends OptionParsingCommand {
private void deleteIfExists(File file) {
if (file.exists() && !file.delete()) {
throw new IllegalStateException(
"Failed to delete existing file " + file.getPath());
throw new IllegalStateException("Failed to delete existing file " + file.getPath());
}
}
private GroovyCompiler createCompiler(OptionSet options) {
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
.createDefaultRepositoryConfiguration();
GroovyCompilerConfiguration configuration = new OptionSetGroovyCompilerConfiguration(
options, this, repositoryConfiguration);
GroovyCompilerConfiguration configuration = new OptionSetGroovyCompilerConfiguration(options, this,
repositoryConfiguration);
GroovyCompiler groovyCompiler = new GroovyCompiler(configuration);
groovyCompiler.getAstTransformations().add(0, new GrabAnnotationTransform());
return groovyCompiler;
@@ -174,10 +165,9 @@ abstract class ArchiveCommand extends OptionParsingCommand {
return new ArrayList<URL>(Arrays.asList(compiler.getLoader().getURLs()));
}
private List<MatchedResource> findMatchingClasspathEntries(List<URL> classpath,
OptionSet options) throws IOException {
ResourceMatcher matcher = new ResourceMatcher(
options.valuesOf(this.includeOption),
private List<MatchedResource> findMatchingClasspathEntries(List<URL> classpath, OptionSet options)
throws IOException {
ResourceMatcher matcher = new ResourceMatcher(options.valuesOf(this.includeOption),
options.valuesOf(this.excludeOption));
List<File> roots = new ArrayList<File>();
for (URL classpathEntry : classpath) {
@@ -186,9 +176,8 @@ abstract class ArchiveCommand extends OptionParsingCommand {
return matcher.find(roots);
}
private void writeJar(File file, Class<?>[] compiledClasses,
List<MatchedResource> classpathEntries, List<URL> dependencies)
throws FileNotFoundException, IOException, URISyntaxException {
private void writeJar(File file, Class<?>[] compiledClasses, List<MatchedResource> classpathEntries,
List<URL> dependencies) throws FileNotFoundException, IOException, URISyntaxException {
final List<Library> libraries;
JarWriter writer = new JarWriter(file);
try {
@@ -216,8 +205,7 @@ abstract class ArchiveCommand extends OptionParsingCommand {
});
}
private List<Library> createLibraries(List<URL> dependencies)
throws URISyntaxException {
private List<Library> createLibraries(List<URL> dependencies) throws URISyntaxException {
List<Library> libraries = new ArrayList<Library>();
for (URL dependency : dependencies) {
File file = new File(dependency.toURI());
@@ -226,12 +214,10 @@ abstract class ArchiveCommand extends OptionParsingCommand {
return libraries;
}
private void addManifest(JarWriter writer, Class<?>[] compiledClasses)
throws IOException {
private void addManifest(JarWriter writer, Class<?>[] compiledClasses) throws IOException {
Manifest manifest = new Manifest();
manifest.getMainAttributes().putValue("Manifest-Version", "1.0");
manifest.getMainAttributes().putValue(
PackagedSpringApplicationLauncher.SOURCE_ENTRY,
manifest.getMainAttributes().putValue(PackagedSpringApplicationLauncher.SOURCE_ENTRY,
commaDelimitedClassNames(compiledClasses));
writer.writeManifest(manifest);
}
@@ -252,18 +238,16 @@ abstract class ArchiveCommand extends OptionParsingCommand {
.getResources("org/springframework/boot/groovy/**");
for (Resource resource : resources) {
String url = resource.getURL().toString();
addResource(writer, resource,
url.substring(url.indexOf("org/springframework/boot/groovy/")));
addResource(writer, resource, url.substring(url.indexOf("org/springframework/boot/groovy/")));
}
}
protected final void addClass(JarWriter writer, Class<?> sourceClass)
throws IOException {
protected final void addClass(JarWriter writer, Class<?> sourceClass) throws IOException {
addClass(writer, sourceClass.getClassLoader(), sourceClass.getName());
}
protected final void addClass(JarWriter writer, ClassLoader classLoader,
String sourceClass) throws IOException {
protected final void addClass(JarWriter writer, ClassLoader classLoader, String sourceClass)
throws IOException {
if (classLoader == null) {
classLoader = Thread.currentThread().getContextClassLoader();
}
@@ -272,14 +256,12 @@ abstract class ArchiveCommand extends OptionParsingCommand {
writer.writeEntry(this.layout.getClassesLocation() + name, stream);
}
private void addResource(JarWriter writer, Resource resource, String name)
throws IOException {
private void addResource(JarWriter writer, Resource resource, String name) throws IOException {
InputStream stream = resource.getInputStream();
writer.writeEntry(name, stream);
}
private List<Library> addClasspathEntries(JarWriter writer,
List<MatchedResource> entries) throws IOException {
private List<Library> addClasspathEntries(JarWriter writer, List<MatchedResource> entries) throws IOException {
List<Library> libraries = new ArrayList<Library>();
for (MatchedResource entry : entries) {
if (entry.isRoot()) {
@@ -292,8 +274,7 @@ abstract class ArchiveCommand extends OptionParsingCommand {
return libraries;
}
protected void writeClasspathEntry(JarWriter writer, MatchedResource entry)
throws IOException {
protected void writeClasspathEntry(JarWriter writer, MatchedResource entry) throws IOException {
writer.writeEntry(entry.getName(), new FileInputStream(entry.getFile()));
}
@@ -333,8 +314,7 @@ abstract class ArchiveCommand extends OptionParsingCommand {
for (AnnotatedNode classNode : nodes) {
List<AnnotationNode> annotations = classNode.getAnnotations();
for (AnnotationNode node : new ArrayList<AnnotationNode>(annotations)) {
if (node.getClassNode().getNameWithoutPackage()
.equals("GrabResolver")) {
if (node.getClassNode().getNameWithoutPackage().equals("GrabResolver")) {
node.setMember("initClass", new ConstantExpression(false));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,8 +31,8 @@ import org.springframework.boot.loader.tools.LibraryScope;
public class JarCommand extends ArchiveCommand {
public JarCommand() {
super("jar", "Create a self-contained executable jar "
+ "file from a Spring Groovy script", new JarOptionHandler());
super("jar", "Create a self-contained executable jar " + "file from a Spring Groovy script",
new JarOptionHandler());
}
private static final class JarOptionHandler extends ArchiveOptionHandler {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,11 +42,11 @@ import org.springframework.util.StringUtils;
*/
class ResourceMatcher {
private static final String[] DEFAULT_INCLUDES = { "public/**", "resources/**",
"static/**", "templates/**", "META-INF/**", "*" };
private static final String[] DEFAULT_INCLUDES = { "public/**", "resources/**", "static/**", "templates/**",
"META-INF/**", "*" };
private static final String[] DEFAULT_EXCLUDES = { ".*", "repository/**", "build/**",
"target/**", "**/*.jar", "**/*.groovy" };
private static final String[] DEFAULT_EXCLUDES = { ".*", "repository/**", "build/**", "target/**", "**/*.jar",
"**/*.groovy" };
private final AntPathMatcher pathMatcher = new AntPathMatcher();
@@ -187,8 +187,8 @@ class ResourceMatcher {
}
private MatchedResource(File rootFolder, File file) {
this.name = StringUtils.cleanPath(file.getAbsolutePath()
.substring(rootFolder.getAbsolutePath().length() + 1));
this.name = StringUtils
.cleanPath(file.getAbsolutePath().substring(rootFolder.getAbsolutePath().length() + 1));
this.file = file;
this.root = false;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,8 +36,8 @@ import org.springframework.boot.loader.tools.LibraryScope;
public class WarCommand extends ArchiveCommand {
public WarCommand() {
super("war", "Create a self-contained executable war "
+ "file from a Spring Groovy script", new WarOptionHandler());
super("war", "Create a self-contained executable war " + "file from a Spring Groovy script",
new WarOptionHandler());
}
private static final class WarOptionHandler extends ArchiveOptionHandler {
@@ -49,8 +49,7 @@ public class WarCommand extends ArchiveCommand {
@Override
protected LibraryScope getLibraryScope(File file) {
String fileName = file.getName();
if (fileName.contains("tomcat-embed")
|| fileName.contains("spring-boot-starter-tomcat")) {
if (fileName.contains("tomcat-embed") || fileName.contains("spring-boot-starter-tomcat")) {
return LibraryScope.PROVIDED;
}
return LibraryScope.COMPILE;
@@ -58,16 +57,13 @@ public class WarCommand extends ArchiveCommand {
@Override
protected void addCliClasses(JarWriter writer) throws IOException {
addClass(writer, null, "org.springframework.boot."
+ "cli.app.SpringApplicationWebApplicationInitializer");
addClass(writer, null, "org.springframework.boot." + "cli.app.SpringApplicationWebApplicationInitializer");
super.addCliClasses(writer);
}
@Override
protected void writeClasspathEntry(JarWriter writer,
ResourceMatcher.MatchedResource entry) throws IOException {
writer.writeEntry(getLayout().getClassesLocation() + entry.getName(),
new FileInputStream(entry.getFile()));
protected void writeClasspathEntry(JarWriter writer, ResourceMatcher.MatchedResource entry) throws IOException {
writer.writeEntry(getLayout().getClassesLocation() + entry.getName(), new FileInputStream(entry.getFile()));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -94,12 +94,11 @@ public class HelpCommand extends AbstractCommand {
String commandName = args[0];
for (Command command : this.commandRunner) {
if (command.getName().equals(commandName)) {
Log.info(this.commandRunner.getName() + command.getName() + " - "
+ command.getDescription());
Log.info(this.commandRunner.getName() + command.getName() + " - " + command.getDescription());
Log.info("");
if (command.getUsageHelp() != null) {
Log.info("usage: " + this.commandRunner.getName() + command.getName()
+ " " + command.getUsageHelp());
Log.info("usage: " + this.commandRunner.getName() + command.getName() + " "
+ command.getUsageHelp());
Log.info("");
}
if (command.getHelp() != null) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -59,8 +59,7 @@ public class HintCommand extends AbstractCommand {
}
else if (!arguments.isEmpty() && (starting.length() > 0)) {
String command = arguments.remove(0);
showCommandOptionHints(command, Collections.unmodifiableList(arguments),
starting);
showCommandOptionHints(command, Collections.unmodifiableList(arguments), starting);
}
}
catch (Exception ex) {
@@ -83,12 +82,10 @@ public class HintCommand extends AbstractCommand {
return false;
}
return command.getName().startsWith(starting)
|| (this.commandRunner.isOptionCommand(command)
&& ("--" + command.getName()).startsWith(starting));
|| (this.commandRunner.isOptionCommand(command) && ("--" + command.getName()).startsWith(starting));
}
private void showCommandOptionHints(String commandName,
List<String> specifiedArguments, String starting) {
private void showCommandOptionHints(String commandName, List<String> specifiedArguments, String starting) {
Command command = this.commandRunner.findCommand(commandName);
if (command != null) {
for (OptionHelp help : command.getOptionsHelp()) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,8 +39,7 @@ import org.springframework.boot.cli.compiler.grape.RepositoryConfiguration;
public class GrabCommand extends OptionParsingCommand {
public GrabCommand() {
super("grab", "Download a spring groovy script's dependencies to ./repository",
new GrabOptionHandler());
super("grab", "Download a spring groovy script's dependencies to ./repository", new GrabOptionHandler());
}
private static final class GrabOptionHandler extends CompilerOptionHandler {
@@ -52,8 +51,8 @@ public class GrabCommand extends OptionParsingCommand {
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
.createDefaultRepositoryConfiguration();
GroovyCompilerConfiguration configuration = new OptionSetGroovyCompilerConfiguration(
options, this, repositoryConfiguration);
GroovyCompilerConfiguration configuration = new OptionSetGroovyCompilerConfiguration(options, this,
repositoryConfiguration);
if (System.getProperty("grape.root") == null) {
System.setProperty("grape.root", ".");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,9 +47,7 @@ public class InitCommand extends OptionParsingCommand {
}
public InitCommand(InitOptionHandler handler) {
super("init",
"Initialize a new project using Spring " + "Initializr (start.spring.io)",
handler);
super("init", "Initialize a new project using Spring " + "Initializr (start.spring.io)", handler);
}
@Override
@@ -60,11 +58,9 @@ public class InitCommand extends OptionParsingCommand {
@Override
public Collection<HelpExample> getExamples() {
List<HelpExample> examples = new ArrayList<HelpExample>();
examples.add(new HelpExample("To list all the capabilities of the service",
"spring init --list"));
examples.add(new HelpExample("To list all the capabilities of the service", "spring init --list"));
examples.add(new HelpExample("To creates a default project", "spring init"));
examples.add(new HelpExample("To create a web my-app.zip",
"spring init -d=web my-app.zip"));
examples.add(new HelpExample("To create a web my-app.zip", "spring init -d=web my-app.zip"));
examples.add(new HelpExample("To create a web/data-jpa gradle project unpacked",
"spring init -d=web,jpa --build=gradle my-dir"));
return examples;
@@ -116,16 +112,14 @@ public class InitCommand extends OptionParsingCommand {
private OptionSpec<Void> force;
InitOptionHandler(InitializrService initializrService) {
this.serviceCapabilitiesReport = new ServiceCapabilitiesReportGenerator(
initializrService);
this.serviceCapabilitiesReport = new ServiceCapabilitiesReportGenerator(initializrService);
this.projectGenerator = new ProjectGenerator(initializrService);
}
@Override
protected void options() {
this.target = option(Arrays.asList("target"), "URL of the service to use")
.withRequiredArg()
this.target = option(Arrays.asList("target"), "URL of the service to use").withRequiredArg()
.defaultsTo(ProjectGenerationRequest.DEFAULT_SERVICE_URL);
this.listCapabilities = option(Arrays.asList("list", "l"),
"List the capabilities of the service. Use it to discover the "
@@ -135,48 +129,40 @@ public class InitCommand extends OptionParsingCommand {
}
private void projectGenerationOptions() {
this.groupId = option(Arrays.asList("groupId", "g"),
"Project coordinates (for example 'org.test')").withRequiredArg();
this.artifactId = option(Arrays.asList("artifactId", "a"),
"Project coordinates; infer archive name (for example 'test')")
.withRequiredArg();
this.version = option(Arrays.asList("version", "v"),
"Project version (for example '0.0.1-SNAPSHOT')").withRequiredArg();
this.name = option(Arrays.asList("name", "n"),
"Project name; infer application name").withRequiredArg();
this.description = option("description", "Project description")
this.groupId = option(Arrays.asList("groupId", "g"), "Project coordinates (for example 'org.test')")
.withRequiredArg();
this.artifactId = option(Arrays.asList("artifactId", "a"),
"Project coordinates; infer archive name (for example 'test')").withRequiredArg();
this.version = option(Arrays.asList("version", "v"), "Project version (for example '0.0.1-SNAPSHOT')")
.withRequiredArg();
this.name = option(Arrays.asList("name", "n"), "Project name; infer application name").withRequiredArg();
this.description = option("description", "Project description").withRequiredArg();
this.packageName = option("package-name", "Package name").withRequiredArg();
this.type = option(Arrays.asList("type", "t"),
"Project type. Not normally needed if you use --build "
+ "and/or --format. Check the capabilities of the service "
+ "(--list) for more details").withRequiredArg();
this.packaging = option(Arrays.asList("packaging", "p"),
"Project packaging (for example 'jar')").withRequiredArg();
this.build = option("build",
"Build system to use (for example 'maven' or 'gradle')")
.withRequiredArg().defaultsTo("maven");
this.format = option("format",
"Format of the generated content (for example 'build' for a build file, "
+ "'project' for a project archive)").withRequiredArg()
.defaultsTo("project");
this.javaVersion = option(Arrays.asList("java-version", "j"),
"Language level (for example '1.8')").withRequiredArg();
this.language = option(Arrays.asList("language", "l"),
"Programming language (for example 'java')").withRequiredArg();
+ "and/or --format. Check the capabilities of the service " + "(--list) for more details")
.withRequiredArg();
this.packaging = option(Arrays.asList("packaging", "p"), "Project packaging (for example 'jar')")
.withRequiredArg();
this.build = option("build", "Build system to use (for example 'maven' or 'gradle')").withRequiredArg()
.defaultsTo("maven");
this.format = option("format", "Format of the generated content (for example 'build' for a build file, "
+ "'project' for a project archive)").withRequiredArg().defaultsTo("project");
this.javaVersion = option(Arrays.asList("java-version", "j"), "Language level (for example '1.8')")
.withRequiredArg();
this.language = option(Arrays.asList("language", "l"), "Programming language (for example 'java')")
.withRequiredArg();
this.bootVersion = option(Arrays.asList("boot-version", "b"),
"Spring Boot version (for example '1.2.0.RELEASE')")
.withRequiredArg();
"Spring Boot version (for example '1.2.0.RELEASE')").withRequiredArg();
this.dependencies = option(Arrays.asList("dependencies", "d"),
"Comma-separated list of dependency identifiers to include in the "
+ "generated project").withRequiredArg();
"Comma-separated list of dependency identifiers to include in the " + "generated project")
.withRequiredArg();
}
private void otherOptions() {
this.extract = option(Arrays.asList("extract", "x"),
"Extract the project archive. Inferred if a location is specified without an extension");
this.force = option(Arrays.asList("force", "f"),
"Force overwrite of existing files");
this.force = option(Arrays.asList("force", "f"), "Force overwrite of existing files");
}
@Override
@@ -201,8 +187,7 @@ public class InitCommand extends OptionParsingCommand {
}
private void generateReport(OptionSet options) throws IOException {
Log.info(this.serviceCapabilitiesReport
.generate(options.valueOf(this.target)));
Log.info(this.serviceCapabilitiesReport.generate(options.valueOf(this.target)));
}
protected void generateProject(OptionSet options) throws IOException {
@@ -210,13 +195,10 @@ public class InitCommand extends OptionParsingCommand {
this.projectGenerator.generateProject(request, options.has(this.force));
}
protected ProjectGenerationRequest createProjectGenerationRequest(
OptionSet options) {
protected ProjectGenerationRequest createProjectGenerationRequest(OptionSet options) {
List<?> nonOptionArguments = new ArrayList<Object>(
options.nonOptionArguments());
Assert.isTrue(nonOptionArguments.size() <= 1,
"Only the target location may be specified");
List<?> nonOptionArguments = new ArrayList<Object>(options.nonOptionArguments());
Assert.isTrue(nonOptionArguments.size() <= 1, "Only the target location may be specified");
ProjectGenerationRequest request = new ProjectGenerationRequest();
request.setServiceUrl(options.valueOf(this.target));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -59,8 +59,7 @@ class InitializrService {
* Accept header to use to retrieve the service capabilities of the service. If the
* service does not offer such feature, the json meta-data are retrieved instead.
*/
public static final String ACCEPT_SERVICE_CAPABILITIES = "text/plain,"
+ ACCEPT_META_DATA;
public static final String ACCEPT_SERVICE_CAPABILITIES = "text/plain," + ACCEPT_META_DATA;
/**
* Late binding HTTP client.
@@ -87,8 +86,7 @@ class InitializrService {
* @return an entity defining the project
* @throws IOException if generation fails
*/
public ProjectGenerationResponse generate(ProjectGenerationRequest request)
throws IOException {
public ProjectGenerationResponse generate(ProjectGenerationRequest request) throws IOException {
Log.info("Using service at " + request.getServiceUrl());
InitializrServiceMetadata metadata = loadMetadata(request.getServiceUrl());
URI url = request.generateUrl(metadata);
@@ -105,8 +103,7 @@ class InitializrService {
* @throws IOException if the service's metadata cannot be loaded
*/
public InitializrServiceMetadata loadMetadata(String serviceUrl) throws IOException {
CloseableHttpResponse httpResponse = executeInitializrMetadataRetrieval(
serviceUrl);
CloseableHttpResponse httpResponse = executeInitializrMetadataRetrieval(serviceUrl);
validateResponse(httpResponse, serviceUrl);
return parseJsonMetadata(httpResponse.getEntity());
}
@@ -122,10 +119,8 @@ class InitializrService {
*/
public Object loadServiceCapabilities(String serviceUrl) throws IOException {
HttpGet request = new HttpGet(serviceUrl);
request.setHeader(
new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_SERVICE_CAPABILITIES));
CloseableHttpResponse httpResponse = execute(request, serviceUrl,
"retrieve help");
request.setHeader(new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_SERVICE_CAPABILITIES));
CloseableHttpResponse httpResponse = execute(request, serviceUrl, "retrieve help");
validateResponse(httpResponse, serviceUrl);
HttpEntity httpEntity = httpResponse.getEntity();
ContentType contentType = ContentType.getOrDefault(httpEntity);
@@ -135,34 +130,29 @@ class InitializrService {
return parseJsonMetadata(httpEntity);
}
private InitializrServiceMetadata parseJsonMetadata(HttpEntity httpEntity)
throws IOException {
private InitializrServiceMetadata parseJsonMetadata(HttpEntity httpEntity) throws IOException {
try {
return new InitializrServiceMetadata(getContentAsJson(httpEntity));
}
catch (JSONException ex) {
throw new ReportableException(
"Invalid content received from server (" + ex.getMessage() + ")", ex);
throw new ReportableException("Invalid content received from server (" + ex.getMessage() + ")", ex);
}
}
private void validateResponse(CloseableHttpResponse httpResponse, String serviceUrl) {
if (httpResponse.getEntity() == null) {
throw new ReportableException(
"No content received from server '" + serviceUrl + "'");
throw new ReportableException("No content received from server '" + serviceUrl + "'");
}
if (httpResponse.getStatusLine().getStatusCode() != 200) {
throw createException(serviceUrl, httpResponse);
}
}
private ProjectGenerationResponse createResponse(CloseableHttpResponse httpResponse,
HttpEntity httpEntity) throws IOException {
ProjectGenerationResponse response = new ProjectGenerationResponse(
ContentType.getOrDefault(httpEntity));
private ProjectGenerationResponse createResponse(CloseableHttpResponse httpResponse, HttpEntity httpEntity)
throws IOException {
ProjectGenerationResponse response = new ProjectGenerationResponse(ContentType.getOrDefault(httpEntity));
response.setContent(FileCopyUtils.copyToByteArray(httpEntity.getContent()));
String fileName = extractFileName(
httpResponse.getFirstHeader("Content-Disposition"));
String fileName = extractFileName(httpResponse.getFirstHeader("Content-Disposition"));
if (fileName != null) {
response.setFileName(fileName);
}
@@ -189,23 +179,19 @@ class InitializrService {
return execute(request, url, "retrieve metadata");
}
private CloseableHttpResponse execute(HttpUriRequest request, Object url,
String description) {
private CloseableHttpResponse execute(HttpUriRequest request, Object url, String description) {
try {
request.addHeader("User-Agent", "SpringBootCli/"
+ getClass().getPackage().getImplementationVersion());
request.addHeader("User-Agent", "SpringBootCli/" + getClass().getPackage().getImplementationVersion());
return getHttp().execute(request);
}
catch (IOException ex) {
throw new ReportableException("Failed to " + description
+ " from service at '" + url + "' (" + ex.getMessage() + ")");
throw new ReportableException(
"Failed to " + description + " from service at '" + url + "' (" + ex.getMessage() + ")");
}
}
private ReportableException createException(String url,
CloseableHttpResponse httpResponse) {
String message = "Initializr service call failed using '" + url
+ "' - service returned "
private ReportableException createException(String url, CloseableHttpResponse httpResponse) {
String message = "Initializr service call failed using '" + url + "' - service returned "
+ httpResponse.getStatusLine().getReasonPhrase();
String error = extractMessage(httpResponse.getEntity());
if (StringUtils.hasText(error)) {
@@ -233,8 +219,7 @@ class InitializrService {
return null;
}
private JSONObject getContentAsJson(HttpEntity entity)
throws IOException, JSONException {
private JSONObject getContentAsJson(HttpEntity entity) throws IOException, JSONException {
return new JSONObject(getContent(entity));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -70,8 +70,7 @@ class InitializrServiceMetadata {
InitializrServiceMetadata(ProjectType defaultProjectType) {
this.dependencies = new HashMap<String, Dependency>();
this.projectTypes = new MetadataHolder<String, ProjectType>();
this.projectTypes.getContent().put(defaultProjectType.getId(),
defaultProjectType);
this.projectTypes.getContent().put(defaultProjectType.getId(), defaultProjectType);
this.projectTypes.setDefaultItem(defaultProjectType);
this.defaults = new HashMap<String, String>();
}
@@ -126,8 +125,7 @@ class InitializrServiceMetadata {
return this.defaults;
}
private Map<String, Dependency> parseDependencies(JSONObject root)
throws JSONException {
private Map<String, Dependency> parseDependencies(JSONObject root) throws JSONException {
Map<String, Dependency> result = new HashMap<String, Dependency>();
if (!root.has(DEPENDENCIES_EL)) {
return result;
@@ -141,16 +139,14 @@ class InitializrServiceMetadata {
return result;
}
private MetadataHolder<String, ProjectType> parseProjectTypes(JSONObject root)
throws JSONException {
private MetadataHolder<String, ProjectType> parseProjectTypes(JSONObject root) throws JSONException {
MetadataHolder<String, ProjectType> result = new MetadataHolder<String, ProjectType>();
if (!root.has(TYPE_EL)) {
return result;
}
JSONObject type = root.getJSONObject(TYPE_EL);
JSONArray array = type.getJSONArray(VALUES_EL);
String defaultType = (type.has(DEFAULT_ATTRIBUTE)
? type.getString(DEFAULT_ATTRIBUTE) : null);
String defaultType = (type.has(DEFAULT_ATTRIBUTE) ? type.getString(DEFAULT_ATTRIBUTE) : null);
for (int i = 0; i < array.length(); i++) {
JSONObject typeJson = array.getJSONObject(i);
ProjectType projectType = parseType(typeJson, defaultType);
@@ -178,8 +174,7 @@ class InitializrServiceMetadata {
return result;
}
private void parseGroup(JSONObject group, Map<String, Dependency> dependencies)
throws JSONException {
private void parseGroup(JSONObject group, Map<String, Dependency> dependencies) throws JSONException {
if (group.has(VALUES_EL)) {
JSONArray content = group.getJSONArray(VALUES_EL);
for (int i = 0; i < content.length(); i++) {
@@ -196,8 +191,7 @@ class InitializrServiceMetadata {
return new Dependency(id, name, description);
}
private ProjectType parseType(JSONObject object, String defaultId)
throws JSONException {
private ProjectType parseType(JSONObject object, String defaultId) throws JSONException {
String id = getStringValue(object, ID_ATTRIBUTE, null);
String name = getStringValue(object, NAME_ATTRIBUTE, null);
String action = getStringValue(object, ACTION_ATTRIBUTE, null);
@@ -210,8 +204,7 @@ class InitializrServiceMetadata {
return new ProjectType(id, name, action, defaultType, tags);
}
private String getStringValue(JSONObject object, String name, String defaultValue)
throws JSONException {
private String getStringValue(JSONObject object, String name, String defaultValue) throws JSONException {
return (object.has(name) ? object.getString(name) : defaultValue);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -318,8 +318,7 @@ class ProjectGenerationRequest {
builder.setPath(sb.toString());
if (!this.dependencies.isEmpty()) {
builder.setParameter("dependencies",
StringUtils.collectionToCommaDelimitedString(this.dependencies));
builder.setParameter("dependencies", StringUtils.collectionToCommaDelimitedString(this.dependencies));
}
if (this.groupId != null) {
@@ -360,8 +359,7 @@ class ProjectGenerationRequest {
return builder.build();
}
catch (URISyntaxException ex) {
throw new ReportableException(
"Invalid service URL (" + ex.getMessage() + ")");
throw new ReportableException("Invalid service URL (" + ex.getMessage() + ")");
}
}
@@ -369,14 +367,13 @@ class ProjectGenerationRequest {
if (this.type != null) {
ProjectType result = metadata.getProjectTypes().get(this.type);
if (result == null) {
throw new ReportableException(("No project type with id '" + this.type
+ "' - check the service capabilities (--list)"));
throw new ReportableException(
("No project type with id '" + this.type + "' - check the service capabilities (--list)"));
}
return result;
}
else if (isDetectType()) {
Map<String, ProjectType> types = new HashMap<String, ProjectType>(
metadata.getProjectTypes());
Map<String, ProjectType> types = new HashMap<String, ProjectType>(metadata.getProjectTypes());
if (this.build != null) {
filter(types, "build", this.build);
}
@@ -387,22 +384,19 @@ class ProjectGenerationRequest {
return types.values().iterator().next();
}
else if (types.isEmpty()) {
throw new ReportableException("No type found with build '" + this.build
+ "' and format '" + this.format
throw new ReportableException("No type found with build '" + this.build + "' and format '" + this.format
+ "' check the service capabilities (--list)");
}
else {
throw new ReportableException("Multiple types found with build '"
+ this.build + "' and format '" + this.format
+ "' use --type with a more specific value " + types.keySet());
throw new ReportableException("Multiple types found with build '" + this.build + "' and format '"
+ this.format + "' use --type with a more specific value " + types.keySet());
}
}
else {
ProjectType defaultType = metadata.getDefaultType();
if (defaultType == null) {
throw new ReportableException(
("No project type is set and no default is defined. "
+ "Check the service capabilities (--list)"));
throw new ReportableException(("No project type is set and no default is defined. "
+ "Check the service capabilities (--list)"));
}
return defaultType;
}
@@ -423,10 +417,8 @@ class ProjectGenerationRequest {
return null;
}
private static void filter(Map<String, ProjectType> projects, String tag,
String tagValue) {
for (Iterator<Map.Entry<String, ProjectType>> it = projects.entrySet()
.iterator(); it.hasNext();) {
private static void filter(Map<String, ProjectType> projects, String tag, String tagValue) {
for (Iterator<Map.Entry<String, ProjectType>> it = projects.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, ProjectType> entry = it.next();
String value = entry.getValue().getTags().get(tag);
if (!tagValue.equals(value)) {

View File

@@ -43,11 +43,9 @@ class ProjectGenerator {
this.initializrService = initializrService;
}
public void generateProject(ProjectGenerationRequest request, boolean force)
throws IOException {
public void generateProject(ProjectGenerationRequest request, boolean force) throws IOException {
ProjectGenerationResponse response = this.initializrService.generate(request);
String fileName = (request.getOutput() != null) ? request.getOutput()
: response.getFileName();
String fileName = (request.getOutput() != null) ? request.getOutput() : response.getFileName();
if (shouldExtract(request, response)) {
if (isZipArchive(response)) {
extractProject(response, request.getOutput(), force);
@@ -60,10 +58,8 @@ class ProjectGenerator {
}
}
if (fileName == null) {
throw new ReportableException(
"Could not save the project, the server did not set a preferred "
+ "file name and no location was set. Specify the output location "
+ "for the project.");
throw new ReportableException("Could not save the project, the server did not set a preferred "
+ "file name and no location was set. Specify the output location " + "for the project.");
}
writeProject(response, fileName, force);
}
@@ -74,14 +70,12 @@ class ProjectGenerator {
* @param response the generation response
* @return if the project should be extracted
*/
private boolean shouldExtract(ProjectGenerationRequest request,
ProjectGenerationResponse response) {
private boolean shouldExtract(ProjectGenerationRequest request, ProjectGenerationResponse response) {
if (request.isExtract()) {
return true;
}
// explicit name hasn't been provided for an archive and there is no extension
if (isZipArchive(response) && request.getOutput() != null
&& !request.getOutput().contains(".")) {
if (isZipArchive(response) && request.getOutput() != null && !request.getOutput().contains(".")) {
return true;
}
return false;
@@ -99,15 +93,12 @@ class ProjectGenerator {
return false;
}
private void extractProject(ProjectGenerationResponse entity, String output,
boolean overwrite) throws IOException {
File outputFolder = (output != null) ? new File(output)
: new File(System.getProperty("user.dir"));
private void extractProject(ProjectGenerationResponse entity, String output, boolean overwrite) throws IOException {
File outputFolder = (output != null) ? new File(output) : new File(System.getProperty("user.dir"));
if (!outputFolder.exists()) {
outputFolder.mkdirs();
}
ZipInputStream zipStream = new ZipInputStream(
new ByteArrayInputStream(entity.getContent()));
ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(entity.getContent()));
try {
extractFromStream(zipStream, overwrite, outputFolder);
fixExecutableFlag(outputFolder, "mvnw");
@@ -119,29 +110,24 @@ class ProjectGenerator {
}
}
private void extractFromStream(ZipInputStream zipStream, boolean overwrite,
File outputFolder) throws IOException {
private void extractFromStream(ZipInputStream zipStream, boolean overwrite, File outputFolder) throws IOException {
ZipEntry entry = zipStream.getNextEntry();
String canonicalOutputPath = outputFolder.getCanonicalPath() + File.separator;
while (entry != null) {
File file = new File(outputFolder, entry.getName());
String canonicalEntryPath = file.getCanonicalPath();
if (!canonicalEntryPath.startsWith(canonicalOutputPath)) {
throw new ReportableException("Entry '" + entry.getName()
+ "' would be written to '" + canonicalEntryPath
+ "'. This is outside the output location of '"
+ canonicalOutputPath
throw new ReportableException("Entry '" + entry.getName() + "' would be written to '"
+ canonicalEntryPath + "'. This is outside the output location of '" + canonicalOutputPath
+ "'. Verify your target server configuration.");
}
if (file.exists() && !overwrite) {
throw new ReportableException((file.isDirectory() ? "Directory" : "File")
+ " '" + file.getName()
throw new ReportableException((file.isDirectory() ? "Directory" : "File") + " '" + file.getName()
+ "' already exists. Use --force if you want to overwrite or "
+ "specify an alternate location.");
}
if (!entry.isDirectory()) {
FileCopyUtils.copy(StreamUtils.nonClosing(zipStream),
new FileOutputStream(file));
FileCopyUtils.copy(StreamUtils.nonClosing(zipStream), new FileOutputStream(file));
}
else {
file.mkdir();
@@ -151,18 +137,16 @@ class ProjectGenerator {
}
}
private void writeProject(ProjectGenerationResponse entity, String output,
boolean overwrite) throws IOException {
private void writeProject(ProjectGenerationResponse entity, String output, boolean overwrite) throws IOException {
File outputFile = new File(output);
if (outputFile.exists()) {
if (!overwrite) {
throw new ReportableException("File '" + outputFile.getName()
+ "' already exists. Use --force if you want to "
+ "overwrite or specify an alternate location.");
throw new ReportableException(
"File '" + outputFile.getName() + "' already exists. Use --force if you want to "
+ "overwrite or specify an alternate location.");
}
if (!outputFile.delete()) {
throw new ReportableException(
"Failed to delete existing file " + outputFile.getPath());
throw new ReportableException("Failed to delete existing file " + outputFile.getPath());
}
}
FileCopyUtils.copy(entity.getContent(), outputFile);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,8 +38,7 @@ class ProjectType {
private final Map<String, String> tags = new HashMap<String, String>();
ProjectType(String id, String name, String action, boolean defaultType,
Map<String, String> tags) {
ProjectType(String id, String name, String action, boolean defaultType, Map<String, String> tags) {
this.id = id;
this.name = name;
this.action = action;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -78,8 +78,7 @@ class ServiceCapabilitiesReportGenerator {
return report.toString();
}
private void reportAvailableDependencies(InitializrServiceMetadata metadata,
StringBuilder report) {
private void reportAvailableDependencies(InitializrServiceMetadata metadata, StringBuilder report) {
report.append("Available dependencies:" + NEW_LINE);
report.append("-----------------------" + NEW_LINE);
List<Dependency> dependencies = getSortedDependencies(metadata);
@@ -93,8 +92,7 @@ class ServiceCapabilitiesReportGenerator {
}
private List<Dependency> getSortedDependencies(InitializrServiceMetadata metadata) {
ArrayList<Dependency> dependencies = new ArrayList<Dependency>(
metadata.getDependencies());
ArrayList<Dependency> dependencies = new ArrayList<Dependency>(metadata.getDependencies());
Collections.sort(dependencies, new Comparator<Dependency>() {
@Override
public int compare(Dependency o1, Dependency o2) {
@@ -104,16 +102,14 @@ class ServiceCapabilitiesReportGenerator {
return dependencies;
}
private void reportAvailableProjectTypes(InitializrServiceMetadata metadata,
StringBuilder report) {
private void reportAvailableProjectTypes(InitializrServiceMetadata metadata, StringBuilder report) {
report.append("Available project types:" + NEW_LINE);
report.append("------------------------" + NEW_LINE);
SortedSet<Entry<String, ProjectType>> entries = new TreeSet<Entry<String, ProjectType>>(
new Comparator<Entry<String, ProjectType>>() {
@Override
public int compare(Entry<String, ProjectType> o1,
Entry<String, ProjectType> o2) {
public int compare(Entry<String, ProjectType> o1, Entry<String, ProjectType> o2) {
return o1.getKey().compareTo(o2.getKey());
}
@@ -146,12 +142,10 @@ class ServiceCapabilitiesReportGenerator {
report.append("]");
}
private void reportDefaults(StringBuilder report,
InitializrServiceMetadata metadata) {
private void reportDefaults(StringBuilder report, InitializrServiceMetadata metadata) {
report.append("Defaults:" + NEW_LINE);
report.append("---------" + NEW_LINE);
List<String> defaultsKeys = new ArrayList<String>(
metadata.getDefaults().keySet());
List<String> defaultsKeys = new ArrayList<String>(metadata.getDefaults().keySet());
Collections.sort(defaultsKeys);
for (String defaultsKey : defaultsKeys) {
String defaultsValue = metadata.getDefaults().get(defaultsKey);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,8 +47,7 @@ class GroovyGrabDependencyResolver implements DependencyResolver {
}
@Override
public List<File> resolve(List<String> artifactIdentifiers)
throws CompilationFailedException, IOException {
public List<File> resolve(List<String> artifactIdentifiers) throws CompilationFailedException, IOException {
GroovyCompiler groovyCompiler = new GroovyCompiler(this.configuration);
List<File> artifactFiles = new ArrayList<File>();
if (!artifactIdentifiers.isEmpty()) {
@@ -70,8 +69,7 @@ class GroovyGrabDependencyResolver implements DependencyResolver {
private String createSources(List<String> artifactIdentifiers) throws IOException {
File file = File.createTempFile("SpringCLIDependency", ".groovy");
file.deleteOnExit();
OutputStreamWriter stream = new OutputStreamWriter(new FileOutputStream(file),
"UTF-8");
OutputStreamWriter stream = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
try {
for (String artifactIdentifier : artifactIdentifiers) {
stream.write("@Grab('" + artifactIdentifier + "')");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -37,8 +37,7 @@ import org.springframework.util.Assert;
public class InstallCommand extends OptionParsingCommand {
public InstallCommand() {
super("install", "Install dependencies to the lib/ext directory",
new InstallOptionHandler());
super("install", "Install dependencies to the lib/ext directory", new InstallOptionHandler());
}
@Override
@@ -52,8 +51,8 @@ public class InstallCommand extends OptionParsingCommand {
@SuppressWarnings("unchecked")
protected ExitStatus run(OptionSet options) throws Exception {
List<String> args = (List<String>) options.nonOptionArguments();
Assert.notEmpty(args, "Please specify at least one "
+ "dependency, in the form group:artifact:version, to install");
Assert.notEmpty(args,
"Please specify at least one " + "dependency, in the form group:artifact:version, to install");
try {
new Installer(options, this).install(args);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -46,10 +46,8 @@ class Installer {
private final Properties installCounts;
Installer(OptionSet options, CompilerOptionHandler compilerOptionHandler)
throws IOException {
this(new GroovyGrabDependencyResolver(
createCompilerConfiguration(options, compilerOptionHandler)));
Installer(OptionSet options, CompilerOptionHandler compilerOptionHandler) throws IOException {
this(new GroovyGrabDependencyResolver(createCompilerConfiguration(options, compilerOptionHandler)));
}
Installer(DependencyResolver resolver) throws IOException {
@@ -57,12 +55,11 @@ class Installer {
this.installCounts = loadInstallCounts();
}
private static GroovyCompilerConfiguration createCompilerConfiguration(
OptionSet options, CompilerOptionHandler compilerOptionHandler) {
private static GroovyCompilerConfiguration createCompilerConfiguration(OptionSet options,
CompilerOptionHandler compilerOptionHandler) {
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
.createDefaultRepositoryConfiguration();
return new OptionSetGroovyCompilerConfiguration(options, compilerOptionHandler,
repositoryConfiguration) {
return new OptionSetGroovyCompilerConfiguration(options, compilerOptionHandler, repositoryConfiguration) {
@Override
public boolean isAutoconfigure() {
return false;
@@ -99,8 +96,7 @@ class Installer {
for (File artifactFile : artifactFiles) {
int installCount = getInstallCount(artifactFile);
if (installCount == 0) {
FileCopyUtils.copy(artifactFile,
new File(extDirectory, artifactFile.getName()));
FileCopyUtils.copy(artifactFile, new File(extDirectory, artifactFile.getName()));
}
setInstallCount(artifactFile, installCount + 1);
}
@@ -149,13 +145,11 @@ class Installer {
}
private File getDefaultExtDirectory() {
String home = SystemPropertyUtils
.resolvePlaceholders("${spring.home:${SPRING_HOME:.}}");
String home = SystemPropertyUtils.resolvePlaceholders("${spring.home:${SPRING_HOME:.}}");
File extDirectory = new File(new File(home, "lib"), "ext");
if (!extDirectory.isDirectory()) {
if (!extDirectory.mkdirs()) {
throw new IllegalStateException(
"Failed to create ext directory " + extDirectory);
throw new IllegalStateException("Failed to create ext directory " + extDirectory);
}
}
return extDirectory;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -37,8 +37,7 @@ import org.springframework.boot.cli.util.Log;
public class UninstallCommand extends OptionParsingCommand {
public UninstallCommand() {
super("uninstall", "Uninstall dependencies from the lib/ext directory",
new UninstallOptionHandler());
super("uninstall", "Uninstall dependencies from the lib/ext directory", new UninstallOptionHandler());
}
@Override
@@ -62,8 +61,7 @@ public class UninstallCommand extends OptionParsingCommand {
try {
if (options.has(this.allOption)) {
if (!args.isEmpty()) {
throw new IllegalArgumentException(
"Please use --all without specifying any dependencies");
throw new IllegalArgumentException("Please use --all without specifying any dependencies");
}
new Installer(options, this).uninstallAll();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2013 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,15 +39,12 @@ public class CompilerOptionHandler extends OptionHandler {
@Override
protected final void options() {
this.noGuessImportsOption = option("no-guess-imports",
"Do not attempt to guess imports");
this.noGuessDependenciesOption = option("no-guess-dependencies",
"Do not attempt to guess dependencies");
this.autoconfigureOption = option("autoconfigure",
"Add autoconfigure compiler transformations").withOptionalArg()
.ofType(Boolean.class).defaultsTo(true);
this.classpathOption = option(Arrays.asList("classpath", "cp"),
"Additional classpath entries").withRequiredArg();
this.noGuessImportsOption = option("no-guess-imports", "Do not attempt to guess imports");
this.noGuessDependenciesOption = option("no-guess-dependencies", "Do not attempt to guess dependencies");
this.autoconfigureOption = option("autoconfigure", "Add autoconfigure compiler transformations")
.withOptionalArg().ofType(Boolean.class).defaultsTo(true);
this.classpathOption = option(Arrays.asList("classpath", "cp"), "Additional classpath entries")
.withRequiredArg();
doOptions();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -133,8 +133,7 @@ public class OptionHandler {
Comparator<OptionDescriptor> comparator = new Comparator<OptionDescriptor>() {
@Override
public int compare(OptionDescriptor first, OptionDescriptor second) {
return first.options().iterator().next()
.compareTo(second.options().iterator().next());
return first.options().iterator().next().compareTo(second.options().iterator().next());
}
};

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,14 +40,11 @@ public class OptionSetGroovyCompilerConfiguration implements GroovyCompilerConfi
private final List<RepositoryConfiguration> repositoryConfiguration;
protected OptionSetGroovyCompilerConfiguration(OptionSet optionSet,
CompilerOptionHandler compilerOptionHandler) {
this(optionSet, compilerOptionHandler,
RepositoryConfigurationFactory.createDefaultRepositoryConfiguration());
protected OptionSetGroovyCompilerConfiguration(OptionSet optionSet, CompilerOptionHandler compilerOptionHandler) {
this(optionSet, compilerOptionHandler, RepositoryConfigurationFactory.createDefaultRepositoryConfiguration());
}
public OptionSetGroovyCompilerConfiguration(OptionSet optionSet,
CompilerOptionHandler compilerOptionHandler,
public OptionSetGroovyCompilerConfiguration(OptionSet optionSet, CompilerOptionHandler compilerOptionHandler,
List<RepositoryConfiguration> repositoryConfiguration) {
this.options = optionSet;
this.optionHandler = compilerOptionHandler;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -102,8 +102,7 @@ public class SourceOptions {
}
}
}
this.args = Collections.unmodifiableList(
nonOptionArguments.subList(sourceArgCount, nonOptionArguments.size()));
this.args = Collections.unmodifiableList(nonOptionArguments.subList(sourceArgCount, nonOptionArguments.size()));
Assert.isTrue(!sources.isEmpty(), "Please specify at least one file");
this.sources = Collections.unmodifiableList(sources);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -74,8 +74,7 @@ public class RunCommand extends OptionParsingCommand {
@Override
protected void doOptions() {
this.watchOption = option("watch", "Watch the specified file for changes");
this.verboseOption = option(Arrays.asList("verbose", "v"),
"Verbose logging of dependency resolution");
this.verboseOption = option(Arrays.asList("verbose", "v"), "Verbose logging of dependency resolution");
this.quietOption = option(Arrays.asList("quiet", "q"), "Quiet logging");
}
@@ -100,14 +99,14 @@ public class RunCommand extends OptionParsingCommand {
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
.createDefaultRepositoryConfiguration();
repositoryConfiguration.add(0, new RepositoryConfiguration("local",
new File("repository").toURI(), true));
repositoryConfiguration.add(0,
new RepositoryConfiguration("local", new File("repository").toURI(), true));
SpringApplicationRunnerConfiguration configuration = new SpringApplicationRunnerConfigurationAdapter(
options, this, repositoryConfiguration);
this.runner = new SpringApplicationRunner(configuration,
sourceOptions.getSourcesArray(), sourceOptions.getArgsArray());
this.runner = new SpringApplicationRunner(configuration, sourceOptions.getSourcesArray(),
sourceOptions.getArgsArray());
this.runner.compileAndRun();
return ExitStatus.OK;
@@ -118,12 +117,10 @@ public class RunCommand extends OptionParsingCommand {
* Simple adapter class to present the {@link OptionSet} as a
* {@link SpringApplicationRunnerConfiguration}.
*/
private class SpringApplicationRunnerConfigurationAdapter
extends OptionSetGroovyCompilerConfiguration
private class SpringApplicationRunnerConfigurationAdapter extends OptionSetGroovyCompilerConfiguration
implements SpringApplicationRunnerConfiguration {
SpringApplicationRunnerConfigurationAdapter(OptionSet options,
CompilerOptionHandler optionHandler,
SpringApplicationRunnerConfigurationAdapter(OptionSet options, CompilerOptionHandler optionHandler,
List<RepositoryConfiguration> repositoryConfiguration) {
super(options, optionHandler, repositoryConfiguration);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -65,17 +65,15 @@ public class SpringApplicationRunner {
* @param sources the files to compile/watch
* @param args input arguments
*/
SpringApplicationRunner(final SpringApplicationRunnerConfiguration configuration,
String[] sources, String... args) {
SpringApplicationRunner(final SpringApplicationRunnerConfiguration configuration, String[] sources,
String... args) {
this.configuration = configuration;
this.sources = sources.clone();
this.args = args.clone();
this.compiler = new GroovyCompiler(configuration);
int level = configuration.getLogLevel().intValue();
if (level <= Level.FINER.intValue()) {
System.setProperty(
"org.springframework.boot.cli.compiler.grape.ProgressReporter",
"detail");
System.setProperty("org.springframework.boot.cli.compiler.grape.ProgressReporter", "detail");
System.setProperty("trace", "true");
}
else if (level <= Level.FINE.intValue()) {
@@ -84,9 +82,7 @@ public class SpringApplicationRunner {
else if (level == Level.OFF.intValue()) {
System.setProperty("spring.main.banner-mode", "OFF");
System.setProperty("logging.level.ROOT", "OFF");
System.setProperty(
"org.springframework.boot.cli.compiler.grape.ProgressReporter",
"none");
System.setProperty("org.springframework.boot.cli.compiler.grape.ProgressReporter", "none");
}
}
@@ -128,8 +124,7 @@ public class SpringApplicationRunner {
private Object[] compile() throws IOException {
Object[] compiledSources = this.compiler.compile(this.sources);
if (compiledSources.length == 0) {
throw new RuntimeException(
"No classes found in '" + Arrays.toString(this.sources) + "'");
throw new RuntimeException("No classes found in '" + Arrays.toString(this.sources) + "'");
}
return compiledSources;
}
@@ -169,9 +164,8 @@ public class SpringApplicationRunner {
public void run() {
synchronized (this.monitor) {
try {
this.applicationContext = new SpringApplicationLauncher(
getContextClassLoader()).launch(this.compiledSources,
SpringApplicationRunner.this.args);
this.applicationContext = new SpringApplicationLauncher(getContextClassLoader())
.launch(this.compiledSources, SpringApplicationRunner.this.args);
}
catch (Exception ex) {
ex.printStackTrace();
@@ -186,8 +180,7 @@ public class SpringApplicationRunner {
synchronized (this.monitor) {
if (this.applicationContext != null) {
try {
Method method = this.applicationContext.getClass()
.getMethod("close");
Method method = this.applicationContext.getClass().getMethod("close");
method.invoke(this.applicationContext);
}
catch (NoSuchMethodException ex) {
@@ -232,8 +225,7 @@ public class SpringApplicationRunner {
private List<File> getSourceFiles() {
List<File> sources = new ArrayList<File>();
for (String source : SpringApplicationRunner.this.sources) {
List<String> paths = ResourceUtils.getUrls(source,
SpringApplicationRunner.this.compiler.getLoader());
List<String> paths = ResourceUtils.getUrls(source, SpringApplicationRunner.this.compiler.getLoader());
for (String path : paths) {
try {
URL url = new URL(path);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,8 +25,7 @@ import org.springframework.boot.cli.compiler.GroovyCompilerConfiguration;
*
* @author Phillip Webb
*/
public interface SpringApplicationRunnerConfiguration
extends GroovyCompilerConfiguration {
public interface SpringApplicationRunnerConfiguration extends GroovyCompilerConfiguration {
/**
* Returns {@code true} if the source file should be monitored for changes and

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -48,8 +48,8 @@ public class CommandCompleter extends StringsCompleter {
private final ConsoleReader console;
public CommandCompleter(ConsoleReader consoleReader,
ArgumentDelimiter argumentDelimiter, Iterable<Command> commands) {
public CommandCompleter(ConsoleReader consoleReader, ArgumentDelimiter argumentDelimiter,
Iterable<Command> commands) {
this.console = consoleReader;
List<String> names = new ArrayList<String>();
for (Command command : commands) {
@@ -59,10 +59,9 @@ public class CommandCompleter extends StringsCompleter {
for (OptionHelp optionHelp : command.getOptionsHelp()) {
options.addAll(optionHelp.getOptions());
}
AggregateCompleter argumentCompleters = new AggregateCompleter(
new StringsCompleter(options), new FileNameCompleter());
ArgumentCompleter argumentCompleter = new ArgumentCompleter(argumentDelimiter,
argumentCompleters);
AggregateCompleter argumentCompleters = new AggregateCompleter(new StringsCompleter(options),
new FileNameCompleter());
ArgumentCompleter argumentCompleter = new ArgumentCompleter(argumentDelimiter, argumentCompleters);
argumentCompleter.setStrict(false);
this.commandCompleters.put(command.getName(), argumentCompleter);
}
@@ -99,16 +98,15 @@ public class CommandCompleter extends StringsCompleter {
for (OptionHelp optionHelp : command.getOptionsHelp()) {
OptionHelpLine optionHelpLine = new OptionHelpLine(optionHelp);
optionHelpLines.add(optionHelpLine);
maxOptionsLength = Math.max(maxOptionsLength,
optionHelpLine.getOptions().length());
maxOptionsLength = Math.max(maxOptionsLength, optionHelpLine.getOptions().length());
}
this.console.println();
this.console.println("Usage:");
this.console.println(command.getName() + " " + command.getUsageHelp());
for (OptionHelpLine optionHelpLine : optionHelpLines) {
this.console.println(String.format("\t%" + maxOptionsLength + "s: %s",
optionHelpLine.getOptions(), optionHelpLine.getUsage()));
this.console.println(String.format("\t%" + maxOptionsLength + "s: %s", optionHelpLine.getOptions(),
optionHelpLine.getUsage()));
}
this.console.drawLine();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -48,8 +48,7 @@ class EscapeAwareWhiteSpaceArgumentDelimiter extends WhitespaceArgumentDelimiter
if (closingQuote == -1) {
return false;
}
int openingQuote = searchBackwards(buffer, closingQuote - 1,
buffer.charAt(closingQuote));
int openingQuote = searchBackwards(buffer, closingQuote - 1, buffer.charAt(closingQuote));
if (openingQuote == -1) {
return true;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -87,8 +87,7 @@ public class Shell {
private Iterable<Command> getCommands() {
List<Command> commands = new ArrayList<Command>();
ServiceLoader<CommandFactory> factories = ServiceLoader.load(CommandFactory.class,
getClass().getClassLoader());
ServiceLoader<CommandFactory> factories = ServiceLoader.load(CommandFactory.class, getClass().getClassLoader());
for (CommandFactory factory : factories) {
for (Command command : factory.getCommands()) {
commands.add(convertToForkCommand(command));
@@ -113,8 +112,8 @@ public class Shell {
this.consoleReader.setHistoryEnabled(true);
this.consoleReader.setBellEnabled(false);
this.consoleReader.setExpandEvents(false);
this.consoleReader.addCompleter(new CommandCompleter(this.consoleReader,
this.argumentDelimiter, this.commandRunner));
this.consoleReader
.addCompleter(new CommandCompleter(this.consoleReader, this.argumentDelimiter, this.commandRunner));
this.consoleReader.setCompletionHandler(new CandidateListCompletionHandler());
}
@@ -147,8 +146,7 @@ public class Shell {
String version = getClass().getPackage().getImplementationVersion();
version = (version != null) ? " (v" + version + ")" : "";
System.out.println(ansi("Spring Boot", Code.BOLD).append(version, Code.FAINT));
System.out.println(ansi("Hit TAB to complete. Type 'help' and hit "
+ "RETURN for help, and 'exit' to quit."));
System.out.println(ansi("Hit TAB to complete. Type 'help' and hit " + "RETURN for help, and 'exit' to quit."));
}
private void runInputLoop() throws Exception {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -49,8 +49,7 @@ public class TestCommand extends OptionParsingCommand {
@Override
protected ExitStatus run(OptionSet options) throws Exception {
SourceOptions sourceOptions = new SourceOptions(options);
TestRunnerConfiguration configuration = new TestRunnerConfigurationAdapter(
options, this);
TestRunnerConfiguration configuration = new TestRunnerConfigurationAdapter(options, this);
this.runner = new TestRunner(configuration, sourceOptions.getSourcesArray());
this.runner.compileAndRunTests();
return ExitStatus.OK.hangup();
@@ -60,11 +59,10 @@ public class TestCommand extends OptionParsingCommand {
* Simple adapter class to present the {@link OptionSet} as a
* {@link TestRunnerConfiguration}.
*/
private class TestRunnerConfigurationAdapter extends
OptionSetGroovyCompilerConfiguration implements TestRunnerConfiguration {
private class TestRunnerConfigurationAdapter extends OptionSetGroovyCompilerConfiguration
implements TestRunnerConfiguration {
TestRunnerConfigurationAdapter(OptionSet options,
CompilerOptionHandler optionHandler) {
TestRunnerConfigurationAdapter(OptionSet options, CompilerOptionHandler optionHandler) {
super(options, optionHandler);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -55,8 +55,7 @@ public class TestRunner {
public void compileAndRunTests() throws Exception {
Object[] sources = this.compiler.compile(this.sources);
if (sources.length == 0) {
throw new RuntimeException(
"No classes found in '" + Arrays.toString(this.sources) + "'");
throw new RuntimeException("No classes found in '" + Arrays.toString(this.sources) + "'");
}
// Run in new thread to ensure that the context classloader is setup
@@ -126,8 +125,7 @@ public class TestRunner {
private boolean isJunitTest(Class<?> sourceClass) {
for (Method method : sourceClass.getMethods()) {
for (Annotation annotation : method.getAnnotations()) {
if (annotation.annotationType().getName()
.equals(JUNIT_TEST_ANNOTATION)) {
if (annotation.annotationType().getName().equals(JUNIT_TEST_ANNOTATION)) {
return true;
}
}
@@ -136,8 +134,7 @@ public class TestRunner {
}
private boolean isSpockTest(Class<?> sourceClass) {
return (this.spockSpecificationClass != null
&& this.spockSpecificationClass.isAssignableFrom(sourceClass));
return (this.spockSpecificationClass != null && this.spockSpecificationClass.isAssignableFrom(sourceClass));
}
@Override
@@ -147,18 +144,13 @@ public class TestRunner {
System.out.println("No tests found");
}
else {
ClassLoader contextClassLoader = Thread.currentThread()
.getContextClassLoader();
Class<?> delegateClass = contextClassLoader
.loadClass(DelegateTestRunner.class.getName());
Class<?> resultClass = contextClassLoader
.loadClass("org.junit.runner.Result");
Method runMethod = delegateClass.getMethod("run", Class[].class,
resultClass);
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
Class<?> delegateClass = contextClassLoader.loadClass(DelegateTestRunner.class.getName());
Class<?> resultClass = contextClassLoader.loadClass("org.junit.runner.Result");
Method runMethod = delegateClass.getMethod("run", Class[].class, resultClass);
Object result = resultClass.newInstance();
runMethod.invoke(null, this.testClasses, result);
boolean wasSuccessful = (Boolean) resultClass
.getMethod("wasSuccessful").invoke(result);
boolean wasSuccessful = (Boolean) resultClass.getMethod("wasSuccessful").invoke(result);
if (!wasSuccessful) {
throw new RuntimeException("Tests Failed.");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,8 +47,7 @@ public abstract class AnnotatedNodeASTTransformation implements ASTTransformatio
private SourceUnit sourceUnit;
protected AnnotatedNodeASTTransformation(Set<String> interestingAnnotationNames,
boolean removeAnnotations) {
protected AnnotatedNodeASTTransformation(Set<String> interestingAnnotationNames, boolean removeAnnotations) {
this.interestingAnnotationNames = interestingAnnotationNames;
this.removeAnnotations = removeAnnotations;
}
@@ -68,12 +67,10 @@ public abstract class AnnotatedNodeASTTransformation implements ASTTransformatio
for (ImportNode importNode : module.getStarImports()) {
visitAnnotatedNode(importNode, annotationNodes);
}
for (Map.Entry<String, ImportNode> entry : module.getStaticImports()
.entrySet()) {
for (Map.Entry<String, ImportNode> entry : module.getStaticImports().entrySet()) {
visitAnnotatedNode(entry.getValue(), annotationNodes);
}
for (Map.Entry<String, ImportNode> entry : module.getStaticStarImports()
.entrySet()) {
for (Map.Entry<String, ImportNode> entry : module.getStaticStarImports().entrySet()) {
visitAnnotatedNode(entry.getValue(), annotationNodes);
}
for (ClassNode classNode : module.getClasses()) {
@@ -91,15 +88,12 @@ public abstract class AnnotatedNodeASTTransformation implements ASTTransformatio
protected abstract void processAnnotationNodes(List<AnnotationNode> annotationNodes);
private void visitAnnotatedNode(AnnotatedNode annotatedNode,
List<AnnotationNode> annotatedNodes) {
private void visitAnnotatedNode(AnnotatedNode annotatedNode, List<AnnotationNode> annotatedNodes) {
if (annotatedNode != null) {
Iterator<AnnotationNode> annotationNodes = annotatedNode.getAnnotations()
.iterator();
Iterator<AnnotationNode> annotationNodes = annotatedNode.getAnnotations().iterator();
while (annotationNodes.hasNext()) {
AnnotationNode annotationNode = annotationNodes.next();
if (this.interestingAnnotationNames
.contains(annotationNode.getClassNode().getName())) {
if (this.interestingAnnotationNames.contains(annotationNode.getClassNode().getName())) {
annotatedNodes.add(annotationNode);
if (this.removeAnnotations) {
annotationNodes.remove();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -76,12 +76,10 @@ public abstract class AstUtils {
* @return {@code true} if at least one of the annotations is found, otherwise
* {@code false}
*/
public static boolean hasAtLeastOneAnnotation(AnnotatedNode node,
String... annotations) {
public static boolean hasAtLeastOneAnnotation(AnnotatedNode node, String... annotations) {
for (AnnotationNode annotationNode : node.getAnnotations()) {
for (String annotation : annotations) {
if (PatternMatchUtils.simpleMatch(annotation,
annotationNode.getClassNode().getName())) {
if (PatternMatchUtils.simpleMatch(annotation, annotationNode.getClassNode().getName())) {
return true;
}
}
@@ -147,13 +145,11 @@ public abstract class AstUtils {
* @param remove whether or not the extracted closure should be removed
* @return a beans Closure if one can be found, null otherwise
*/
public static ClosureExpression getClosure(BlockStatement block, String name,
boolean remove) {
public static ClosureExpression getClosure(BlockStatement block, String name, boolean remove) {
for (ExpressionStatement statement : getExpressionStatements(block)) {
Expression expression = statement.getExpression();
if (expression instanceof MethodCallExpression) {
ClosureExpression closure = getClosure(name,
(MethodCallExpression) expression);
ClosureExpression closure = getClosure(name, (MethodCallExpression) expression);
if (closure != null) {
if (remove) {
block.getStatements().remove(statement);
@@ -165,8 +161,7 @@ public abstract class AstUtils {
return null;
}
private static List<ExpressionStatement> getExpressionStatements(
BlockStatement block) {
private static List<ExpressionStatement> getExpressionStatements(BlockStatement block) {
ArrayList<ExpressionStatement> statements = new ArrayList<ExpressionStatement>();
for (Statement statement : block.getStatements()) {
if (statement instanceof ExpressionStatement) {
@@ -176,13 +171,11 @@ public abstract class AstUtils {
return statements;
}
private static ClosureExpression getClosure(String name,
MethodCallExpression expression) {
private static ClosureExpression getClosure(String name, MethodCallExpression expression) {
Expression method = expression.getMethod();
if (method instanceof ConstantExpression) {
if (name.equals(((ConstantExpression) method).getValue())) {
return (ClosureExpression) ((ArgumentListExpression) expression
.getArguments()).getExpression(0);
return (ClosureExpression) ((ArgumentListExpression) expression.getArguments()).getExpression(0);
}
}
return null;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -49,8 +49,7 @@ public abstract class CompilerAutoConfiguration {
* @param dependencies dependency customizer
* @throws CompilationFailedException if the dependencies cannot be applied
*/
public void applyDependencies(DependencyCustomizer dependencies)
throws CompilationFailedException {
public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException {
}
/**
@@ -73,9 +72,9 @@ public abstract class CompilerAutoConfiguration {
* @param classNode the main class
* @throws CompilationFailedException if the customizations cannot be applied
*/
public void applyToMainClass(GroovyClassLoader loader,
GroovyCompilerConfiguration configuration, GeneratorContext generatorContext,
SourceUnit source, ClassNode classNode) throws CompilationFailedException {
public void applyToMainClass(GroovyClassLoader loader, GroovyCompilerConfiguration configuration,
GeneratorContext generatorContext, SourceUnit source, ClassNode classNode)
throws CompilationFailedException {
}
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -74,8 +74,7 @@ public class DependencyCustomizer {
}
public String getVersion(String artifactId, String defaultVersion) {
String version = this.dependencyResolutionContext.getArtifactCoordinatesResolver()
.getVersion(artifactId);
String version = this.dependencyResolutionContext.getArtifactCoordinatesResolver().getVersion(artifactId);
if (version == null) {
version = defaultVersion;
}
@@ -219,22 +218,19 @@ public class DependencyCustomizer {
* otherwise {@code false}.
* @return this {@link DependencyCustomizer} for continued use
*/
public DependencyCustomizer add(String module, String classifier, String type,
boolean transitive) {
public DependencyCustomizer add(String module, String classifier, String type, boolean transitive) {
if (canAdd()) {
ArtifactCoordinatesResolver artifactCoordinatesResolver = this.dependencyResolutionContext
.getArtifactCoordinatesResolver();
this.classNode.addAnnotation(
createGrabAnnotation(artifactCoordinatesResolver.getGroupId(module),
artifactCoordinatesResolver.getArtifactId(module),
artifactCoordinatesResolver.getVersion(module), classifier,
type, transitive));
this.classNode.addAnnotation(createGrabAnnotation(artifactCoordinatesResolver.getGroupId(module),
artifactCoordinatesResolver.getArtifactId(module), artifactCoordinatesResolver.getVersion(module),
classifier, type, transitive));
}
return this;
}
private AnnotationNode createGrabAnnotation(String group, String module,
String version, String classifier, String type, boolean transitive) {
private AnnotationNode createGrabAnnotation(String group, String module, String version, String classifier,
String type, boolean transitive) {
AnnotationNode annotationNode = new AnnotationNode(new ClassNode(Grab.class));
annotationNode.addMember("group", new ConstantExpression(group));
annotationNode.addMember("module", new ConstantExpression(module));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -61,8 +61,7 @@ import org.springframework.core.annotation.Order;
* @since 1.3.0
*/
@Order(DependencyManagementBomTransformation.ORDER)
public class DependencyManagementBomTransformation
extends AnnotatedNodeASTTransformation {
public class DependencyManagementBomTransformation extends AnnotatedNodeASTTransformation {
/**
* The order of the transformation.
@@ -70,14 +69,12 @@ public class DependencyManagementBomTransformation
public static final int ORDER = Ordered.HIGHEST_PRECEDENCE + 100;
private static final Set<String> DEPENDENCY_MANAGEMENT_BOM_ANNOTATION_NAMES = Collections
.unmodifiableSet(new HashSet<String>(
Arrays.asList(DependencyManagementBom.class.getName(),
DependencyManagementBom.class.getSimpleName())));
.unmodifiableSet(new HashSet<String>(Arrays.asList(DependencyManagementBom.class.getName(),
DependencyManagementBom.class.getSimpleName())));
private final DependencyResolutionContext resolutionContext;
public DependencyManagementBomTransformation(
DependencyResolutionContext resolutionContext) {
public DependencyManagementBomTransformation(DependencyResolutionContext resolutionContext) {
super(DEPENDENCY_MANAGEMENT_BOM_ANNOTATION_NAMES, true);
this.resolutionContext = resolutionContext;
}
@@ -104,10 +101,8 @@ public class DependencyManagementBomTransformation
private List<Map<String, String>> createDependencyMaps(Expression valueExpression) {
Map<String, String> dependency = null;
List<ConstantExpression> constantExpressions = getConstantExpressions(
valueExpression);
List<Map<String, String>> dependencies = new ArrayList<Map<String, String>>(
constantExpressions.size());
List<ConstantExpression> constantExpressions = getConstantExpressions(valueExpression);
List<Map<String, String>> dependencies = new ArrayList<Map<String, String>>(constantExpressions.size());
for (ConstantExpression expression : constantExpressions) {
Object value = expression.getValue();
if (value instanceof String) {
@@ -136,13 +131,12 @@ public class DependencyManagementBomTransformation
&& ((ConstantExpression) valueExpression).getValue() instanceof String) {
return Arrays.asList((ConstantExpression) valueExpression);
}
reportError("@DependencyManagementBom requires an inline constant that is a "
+ "string or a string array", valueExpression);
reportError("@DependencyManagementBom requires an inline constant that is a " + "string or a string array",
valueExpression);
return Collections.emptyList();
}
private List<ConstantExpression> getConstantExpressions(
ListExpression valueExpression) {
private List<ConstantExpression> getConstantExpressions(ListExpression valueExpression) {
List<ConstantExpression> expressions = new ArrayList<ConstantExpression>();
for (Expression expression : valueExpression.getExpressions()) {
if (expression instanceof ConstantExpression
@@ -150,9 +144,7 @@ public class DependencyManagementBomTransformation
expressions.add((ConstantExpression) expression);
}
else {
reportError(
"Each entry in the array must be an " + "inline string constant",
expression);
reportError("Each entry in the array must be an " + "inline string constant", expression);
}
}
return expressions;
@@ -160,16 +152,12 @@ public class DependencyManagementBomTransformation
private void handleMalformedDependency(Expression expression) {
Message message = createSyntaxErrorMessage(
String.format(
"The string must be of the form \"group:module:version\"%n"),
expression);
String.format("The string must be of the form \"group:module:version\"%n"), expression);
getSourceUnit().getErrorCollector().addErrorAndContinue(message);
}
private void updateDependencyResolutionContext(
List<Map<String, String>> bomDependencies) {
URI[] uris = Grape.getInstance().resolve(null,
bomDependencies.toArray(new Map[bomDependencies.size()]));
private void updateDependencyResolutionContext(List<Map<String, String>> bomDependencies) {
URI[] uris = Grape.getInstance().resolve(null, bomDependencies.toArray(new Map[bomDependencies.size()]));
DefaultModelBuilder modelBuilder = new DefaultModelBuilderFactory().newInstance();
for (URI uri : uris) {
try {
@@ -178,34 +166,28 @@ public class DependencyManagementBomTransformation
request.setModelSource(new UrlModelSource(uri.toURL()));
request.setSystemProperties(System.getProperties());
Model model = modelBuilder.build(request).getEffectiveModel();
this.resolutionContext.addDependencyManagement(
new MavenModelDependencyManagement(model));
this.resolutionContext.addDependencyManagement(new MavenModelDependencyManagement(model));
}
catch (Exception ex) {
throw new IllegalStateException("Failed to build model for '" + uri
+ "'. Is it a valid Maven bom?", ex);
throw new IllegalStateException("Failed to build model for '" + uri + "'. Is it a valid Maven bom?",
ex);
}
}
}
private void handleDuplicateDependencyManagementBomAnnotation(
AnnotationNode annotationNode) {
private void handleDuplicateDependencyManagementBomAnnotation(AnnotationNode annotationNode) {
Message message = createSyntaxErrorMessage(
"Duplicate @DependencyManagementBom annotation. It must be declared at most once.",
annotationNode);
"Duplicate @DependencyManagementBom annotation. It must be declared at most once.", annotationNode);
getSourceUnit().getErrorCollector().addErrorAndContinue(message);
}
private void reportError(String message, ASTNode node) {
getSourceUnit().getErrorCollector()
.addErrorAndContinue(createSyntaxErrorMessage(message, node));
getSourceUnit().getErrorCollector().addErrorAndContinue(createSyntaxErrorMessage(message, node));
}
private Message createSyntaxErrorMessage(String message, ASTNode node) {
return new SyntaxErrorMessage(
new SyntaxException(message, node.getLineNumber(), node.getColumnNumber(),
node.getLastLineNumber(), node.getLastColumnNumber()),
getSourceUnit());
return new SyntaxErrorMessage(new SyntaxException(message, node.getLineNumber(), node.getColumnNumber(),
node.getLastLineNumber(), node.getLastColumnNumber()), getSourceUnit());
}
private static class GrapeModelResolver implements ModelResolver {
@@ -219,18 +201,15 @@ public class DependencyManagementBomTransformation
dependency.put("version", version);
dependency.put("type", "pom");
try {
return new UrlModelSource(
Grape.getInstance().resolve(null, dependency)[0].toURL());
return new UrlModelSource(Grape.getInstance().resolve(null, dependency)[0].toURL());
}
catch (MalformedURLException ex) {
throw new UnresolvableModelException(ex.getMessage(), groupId, artifactId,
version);
throw new UnresolvableModelException(ex.getMessage(), groupId, artifactId, version);
}
}
@Override
public void addRepository(Repository repository)
throws InvalidRepositoryException {
public void addRepository(Repository repository) throws InvalidRepositoryException {
}
@Override

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -84,8 +84,7 @@ public class ExtendedGroovyClassLoader extends GroovyClassLoader {
return super.findClass(name);
}
catch (ClassNotFoundException ex) {
if (this.scope == GroovyCompilerScope.DEFAULT
&& name.startsWith(SHARED_PACKAGE)) {
if (this.scope == GroovyCompilerScope.DEFAULT && name.startsWith(SHARED_PACKAGE)) {
Class<?> sharedClass = findSharedClass(name);
if (sharedClass != null) {
return sharedClass;
@@ -126,20 +125,19 @@ public class ExtendedGroovyClassLoader extends GroovyClassLoader {
@Override
public ClassCollector createCollector(CompilationUnit unit, SourceUnit su) {
InnerLoader loader = AccessController
.doPrivileged(new PrivilegedAction<InnerLoader>() {
InnerLoader loader = AccessController.doPrivileged(new PrivilegedAction<InnerLoader>() {
@Override
public InnerLoader run() {
return new InnerLoader(ExtendedGroovyClassLoader.this) {
// Don't return URLs from the inner loader so that Tomcat only
// searches the parent. Fixes 'TLD skipped' issues
@Override
public InnerLoader run() {
return new InnerLoader(ExtendedGroovyClassLoader.this) {
// Don't return URLs from the inner loader so that Tomcat only
// searches the parent. Fixes 'TLD skipped' issues
@Override
public URL[] getURLs() {
return NO_URLS;
}
};
public URL[] getURLs() {
return NO_URLS;
}
});
};
}
});
return new ExtendedClassCollector(loader, unit, su);
}
@@ -152,16 +150,14 @@ public class ExtendedGroovyClassLoader extends GroovyClassLoader {
*/
protected class ExtendedClassCollector extends ClassCollector {
protected ExtendedClassCollector(InnerLoader loader, CompilationUnit unit,
SourceUnit su) {
protected ExtendedClassCollector(InnerLoader loader, CompilationUnit unit, SourceUnit su) {
super(loader, unit, su);
}
@Override
protected Class<?> createClass(byte[] code, ClassNode classNode) {
Class<?> createdClass = super.createClass(code, classNode);
ExtendedGroovyClassLoader.this.classResources
.put(classNode.getName().replace('.', '/') + ".class", code);
ExtendedGroovyClassLoader.this.classResources.put(classNode.getName().replace('.', '/') + ".class", code);
return createdClass;
}
@@ -234,8 +230,7 @@ public class ExtendedGroovyClassLoader extends GroovyClassLoader {
}
@Override
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
this.groovyOnlyClassLoader.loadClass(name);
return super.loadClass(name, resolve);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -51,8 +51,7 @@ import org.springframework.core.Ordered;
* @since 1.3.0
*/
@GroovyASTTransformation(phase = CompilePhase.CONVERSION)
public abstract class GenericBomAstTransformation
implements SpringBootAstTransformation, Ordered {
public abstract class GenericBomAstTransformation implements SpringBootAstTransformation, Ordered {
private static ClassNode BOM = ClassHelper.make(DependencyManagementBom.class);
@@ -81,8 +80,7 @@ public abstract class GenericBomAstTransformation
AnnotatedNode annotated = getAnnotatedNode(node);
if (annotated != null) {
AnnotationNode bom = getAnnotation(annotated);
List<Expression> expressions = new ArrayList<Expression>(
getConstantExpressions(bom.getMember("value")));
List<Expression> expressions = new ArrayList<Expression>(getConstantExpressions(bom.getMember("value")));
expressions.add(new ConstantExpression(module));
bom.setMember("value", new ListExpression(expressions));
}
@@ -120,8 +118,7 @@ public abstract class GenericBomAstTransformation
return Collections.emptyList();
}
private List<ConstantExpression> getConstantExpressions(
ListExpression valueExpression) {
private List<ConstantExpression> getConstantExpressions(ListExpression valueExpression) {
List<ConstantExpression> expressions = new ArrayList<ConstantExpression>();
for (Expression expression : valueExpression.getExpressions()) {
if (expression instanceof ConstantExpression

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -53,8 +53,7 @@ public class GroovyBeansTransformation implements ASTTransformation {
for (ASTNode node : nodes) {
if (node instanceof ModuleNode) {
ModuleNode module = (ModuleNode) node;
for (ClassNode classNode : new ArrayList<ClassNode>(
module.getClasses())) {
for (ClassNode classNode : new ArrayList<ClassNode>(module.getClasses())) {
if (classNode.isScript()) {
classNode.visitContents(new ClassVisitor(source, classNode));
}
@@ -97,10 +96,8 @@ public class GroovyBeansTransformation implements ASTTransformation {
// Implement the interface by adding a public read-only property with the
// same name as the method in the interface (getBeans). Make it return the
// closure.
this.classNode.addProperty(
new PropertyNode(BEANS, Modifier.PUBLIC | Modifier.FINAL,
ClassHelper.CLOSURE_TYPE.getPlainNodeReference(),
this.classNode, closure, null, null));
this.classNode.addProperty(new PropertyNode(BEANS, Modifier.PUBLIC | Modifier.FINAL,
ClassHelper.CLOSURE_TYPE.getPlainNodeReference(), this.classNode, closure, null, null));
// Only do this once per class
this.xformed = true;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -91,37 +91,30 @@ public class GroovyCompiler {
this.loader = createLoader(configuration);
DependencyResolutionContext resolutionContext = new DependencyResolutionContext();
resolutionContext.addDependencyManagement(
new SpringBootDependenciesDependencyManagement());
resolutionContext.addDependencyManagement(new SpringBootDependenciesDependencyManagement());
AetherGrapeEngine grapeEngine = AetherGrapeEngineFactory.create(this.loader,
configuration.getRepositoryConfiguration(), resolutionContext,
configuration.isQuiet());
configuration.getRepositoryConfiguration(), resolutionContext, configuration.isQuiet());
GrapeEngineInstaller.install(grapeEngine);
this.loader.getConfiguration()
.addCompilationCustomizers(new CompilerAutoConfigureCustomizer());
this.loader.getConfiguration().addCompilationCustomizers(new CompilerAutoConfigureCustomizer());
if (configuration.isAutoconfigure()) {
this.compilerAutoConfigurations = ServiceLoader
.load(CompilerAutoConfiguration.class);
this.compilerAutoConfigurations = ServiceLoader.load(CompilerAutoConfiguration.class);
}
else {
this.compilerAutoConfigurations = Collections.emptySet();
}
this.transformations = new ArrayList<ASTTransformation>();
this.transformations
.add(new DependencyManagementBomTransformation(resolutionContext));
this.transformations.add(new DependencyAutoConfigurationTransformation(
this.loader, resolutionContext, this.compilerAutoConfigurations));
this.transformations.add(new DependencyManagementBomTransformation(resolutionContext));
this.transformations.add(new DependencyAutoConfigurationTransformation(this.loader, resolutionContext,
this.compilerAutoConfigurations));
this.transformations.add(new GroovyBeansTransformation());
if (this.configuration.isGuessDependencies()) {
this.transformations.add(
new ResolveDependencyCoordinatesTransformation(resolutionContext));
this.transformations.add(new ResolveDependencyCoordinatesTransformation(resolutionContext));
}
for (ASTTransformation transformation : ServiceLoader
.load(SpringBootAstTransformation.class)) {
for (ASTTransformation transformation : ServiceLoader.load(SpringBootAstTransformation.class)) {
this.transformations.add(transformation);
}
Collections.sort(this.transformations, AnnotationAwareOrderComparator.INSTANCE);
@@ -140,11 +133,9 @@ public class GroovyCompiler {
return this.loader;
}
private ExtendedGroovyClassLoader createLoader(
GroovyCompilerConfiguration configuration) {
private ExtendedGroovyClassLoader createLoader(GroovyCompilerConfiguration configuration) {
ExtendedGroovyClassLoader loader = new ExtendedGroovyClassLoader(
configuration.getScope());
ExtendedGroovyClassLoader loader = new ExtendedGroovyClassLoader(configuration.getScope());
for (URL url : getExistingUrls()) {
loader.addURL(url);
@@ -181,16 +172,14 @@ public class GroovyCompiler {
* @throws IOException in case of I/O errors
* @throws CompilationFailedException in case of compilation errors
*/
public Class<?>[] compile(String... sources)
throws CompilationFailedException, IOException {
public Class<?>[] compile(String... sources) throws CompilationFailedException, IOException {
this.loader.clearCache();
List<Class<?>> classes = new ArrayList<Class<?>>();
CompilerConfiguration configuration = this.loader.getConfiguration();
CompilationUnit compilationUnit = new CompilationUnit(configuration, null,
this.loader);
CompilationUnit compilationUnit = new CompilationUnit(configuration, null, this.loader);
ClassCollector collector = this.loader.createCollector(compilationUnit, null);
compilationUnit.setClassgenCallback(collector);
@@ -238,8 +227,7 @@ public class GroovyCompiler {
return phaseOperations;
}
catch (Exception ex) {
throw new IllegalStateException(
"Phase operations not available from compilation unit");
throw new IllegalStateException("Phase operations not available from compilation unit");
}
}
@@ -280,8 +268,7 @@ public class GroovyCompiler {
public void call(SourceUnit source, GeneratorContext context, ClassNode classNode)
throws CompilationFailedException {
ImportCustomizer importCustomizer = new SmartImportCustomizer(source, context,
classNode);
ImportCustomizer importCustomizer = new SmartImportCustomizer(source, context, classNode);
ClassNode mainClassNode = MainClass.get(source.getAST().getClasses());
// Additional auto configuration
@@ -293,12 +280,10 @@ public class GroovyCompiler {
}
if (classNode.equals(mainClassNode)) {
autoConfiguration.applyToMainClass(GroovyCompiler.this.loader,
GroovyCompiler.this.configuration, context, source,
classNode);
GroovyCompiler.this.configuration, context, source, classNode);
}
autoConfiguration.apply(GroovyCompiler.this.loader,
GroovyCompiler.this.configuration, context, source,
classNode);
autoConfiguration.apply(GroovyCompiler.this.loader, GroovyCompiler.this.configuration, context,
source, classNode);
}
}
importCustomizer.call(source, context, classNode);
@@ -318,8 +303,8 @@ public class GroovyCompiler {
if (AstUtils.hasAtLeastOneAnnotation(node, "Enable*AutoConfiguration")) {
return null; // No need to enhance this
}
if (AstUtils.hasAtLeastOneAnnotation(node, "*Controller", "Configuration",
"Component", "*Service", "Repository", "Enable*")) {
if (AstUtils.hasAtLeastOneAnnotation(node, "*Controller", "Configuration", "Component", "*Service",
"Repository", "Enable*")) {
return node;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -41,14 +41,14 @@ import org.springframework.util.StringUtils;
*/
public final class RepositoryConfigurationFactory {
private static final RepositoryConfiguration MAVEN_CENTRAL = new RepositoryConfiguration(
"central", URI.create("https://repo.maven.apache.org/maven2/"), false);
private static final RepositoryConfiguration MAVEN_CENTRAL = new RepositoryConfiguration("central",
URI.create("https://repo.maven.apache.org/maven2/"), false);
private static final RepositoryConfiguration SPRING_MILESTONE = new RepositoryConfiguration(
"spring-milestone", URI.create("https://repo.spring.io/milestone"), false);
private static final RepositoryConfiguration SPRING_MILESTONE = new RepositoryConfiguration("spring-milestone",
URI.create("https://repo.spring.io/milestone"), false);
private static final RepositoryConfiguration SPRING_SNAPSHOT = new RepositoryConfiguration(
"spring-snapshot", URI.create("https://repo.spring.io/snapshot"), true);
private static final RepositoryConfiguration SPRING_SNAPSHOT = new RepositoryConfiguration("spring-snapshot",
URI.create("https://repo.spring.io/snapshot"), true);
private RepositoryConfigurationFactory() {
}
@@ -65,10 +65,8 @@ public final class RepositoryConfigurationFactory {
repositoryConfiguration.add(SPRING_MILESTONE);
repositoryConfiguration.add(SPRING_SNAPSHOT);
}
addDefaultCacheAsRepository(mavenSettings.getLocalRepository(),
repositoryConfiguration);
addActiveProfileRepositories(mavenSettings.getActiveProfiles(),
repositoryConfiguration);
addDefaultCacheAsRepository(mavenSettings.getLocalRepository(), repositoryConfiguration);
addActiveProfileRepositories(mavenSettings.getActiveProfiles(), repositoryConfiguration);
return repositoryConfiguration;
}
@@ -85,16 +83,15 @@ public final class RepositoryConfigurationFactory {
List<RepositoryConfiguration> configurations) {
for (Profile activeProfile : activeProfiles) {
Interpolator interpolator = new RegexBasedInterpolator();
interpolator.addValueSource(
new PropertiesBasedValueSource(activeProfile.getProperties()));
interpolator.addValueSource(new PropertiesBasedValueSource(activeProfile.getProperties()));
for (Repository repository : activeProfile.getRepositories()) {
configurations.add(getRepositoryConfiguration(interpolator, repository));
}
}
}
private static RepositoryConfiguration getRepositoryConfiguration(
Interpolator interpolator, Repository repository) {
private static RepositoryConfiguration getRepositoryConfiguration(Interpolator interpolator,
Repository repository) {
String name = interpolate(interpolator, repository.getId());
String url = interpolate(interpolator, repository.getUrl());
boolean snapshotsEnabled = false;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,8 +38,7 @@ import org.springframework.core.annotation.Order;
* @author Phillip Webb
*/
@Order(ResolveDependencyCoordinatesTransformation.ORDER)
public class ResolveDependencyCoordinatesTransformation
extends AnnotatedNodeASTTransformation {
public class ResolveDependencyCoordinatesTransformation extends AnnotatedNodeASTTransformation {
/**
* The order of the transformation.
@@ -47,13 +46,11 @@ public class ResolveDependencyCoordinatesTransformation
public static final int ORDER = DependencyManagementBomTransformation.ORDER + 300;
private static final Set<String> GRAB_ANNOTATION_NAMES = Collections
.unmodifiableSet(new HashSet<String>(
Arrays.asList(Grab.class.getName(), Grab.class.getSimpleName())));
.unmodifiableSet(new HashSet<String>(Arrays.asList(Grab.class.getName(), Grab.class.getSimpleName())));
private final DependencyResolutionContext resolutionContext;
public ResolveDependencyCoordinatesTransformation(
DependencyResolutionContext resolutionContext) {
public ResolveDependencyCoordinatesTransformation(DependencyResolutionContext resolutionContext) {
super(GRAB_ANNOTATION_NAMES, false);
this.resolutionContext = resolutionContext;
}
@@ -95,12 +92,11 @@ public class ResolveDependencyCoordinatesTransformation
module = (String) ((ConstantExpression) expression).getValue();
}
if (annotation.getMember("group") == null) {
setMember(annotation, "group", this.resolutionContext
.getArtifactCoordinatesResolver().getGroupId(module));
setMember(annotation, "group", this.resolutionContext.getArtifactCoordinatesResolver().getGroupId(module));
}
if (annotation.getMember("version") == null) {
setMember(annotation, "version", this.resolutionContext
.getArtifactCoordinatesResolver().getVersion(module));
setMember(annotation, "version",
this.resolutionContext.getArtifactCoordinatesResolver().getVersion(module));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,15 +33,13 @@ class SmartImportCustomizer extends ImportCustomizer {
private SourceUnit source;
SmartImportCustomizer(SourceUnit source, GeneratorContext context,
ClassNode classNode) {
SmartImportCustomizer(SourceUnit source, GeneratorContext context, ClassNode classNode) {
this.source = source;
}
@Override
public ImportCustomizer addImport(String alias, String className) {
if (this.source.getAST()
.getImport(ClassHelper.make(className).getNameWithoutPackage()) == null) {
if (this.source.getAST().getImport(ClassHelper.make(className).getNameWithoutPackage()) == null) {
super.addImport(alias, className);
}
return this;
@@ -50,8 +48,7 @@ class SmartImportCustomizer extends ImportCustomizer {
@Override
public ImportCustomizer addImports(String... imports) {
for (String alias : imports) {
if (this.source.getAST()
.getImport(ClassHelper.make(alias).getNameWithoutPackage()) == null) {
if (this.source.getAST().getImport(ClassHelper.make(alias).getNameWithoutPackage()) == null) {
super.addImports(alias);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,15 +38,13 @@ public class CachingCompilerAutoConfiguration extends CompilerAutoConfiguration
}
@Override
public void applyDependencies(DependencyCustomizer dependencies)
throws CompilationFailedException {
public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException {
dependencies.add("spring-context-support");
}
@Override
public void applyImports(ImportCustomizer imports) throws CompilationFailedException {
imports.addStarImports("org.springframework.cache",
"org.springframework.cache.annotation",
imports.addStarImports("org.springframework.cache", "org.springframework.cache.annotation",
"org.springframework.cache.concurrent");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,8 +40,7 @@ public class GroovyTemplatesCompilerAutoConfiguration extends CompilerAutoConfig
@Override
public void applyDependencies(DependencyCustomizer dependencies) {
dependencies.ifAnyMissingClasses("groovy.text.TemplateEngine")
.add("groovy-templates");
dependencies.ifAnyMissingClasses("groovy.text.TemplateEngine").add("groovy-templates");
}
@Override

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -37,16 +37,14 @@ public class JUnitCompilerAutoConfiguration extends CompilerAutoConfiguration {
}
@Override
public void applyDependencies(DependencyCustomizer dependencies)
throws CompilationFailedException {
public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException {
dependencies.add("spring-boot-starter-test");
}
@Override
public void applyImports(ImportCustomizer imports) throws CompilationFailedException {
imports.addStarImports("org.junit").addStaticStars("org.junit.Assert")
.addStaticStars("org.hamcrest.MatcherAssert")
.addStaticStars("org.hamcrest.Matchers");
.addStaticStars("org.hamcrest.MatcherAssert").addStaticStars("org.hamcrest.Matchers");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2013 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,20 +32,18 @@ public class JdbcCompilerAutoConfiguration extends CompilerAutoConfiguration {
@Override
public boolean matches(ClassNode classNode) {
return AstUtils.hasAtLeastOneFieldOrMethod(classNode, "JdbcTemplate",
"NamedParameterJdbcTemplate", "DataSource");
return AstUtils.hasAtLeastOneFieldOrMethod(classNode, "JdbcTemplate", "NamedParameterJdbcTemplate",
"DataSource");
}
@Override
public void applyDependencies(DependencyCustomizer dependencies) {
dependencies.ifAnyMissingClasses("org.springframework.jdbc.core.JdbcTemplate")
.add("spring-boot-starter-jdbc");
dependencies.ifAnyMissingClasses("org.springframework.jdbc.core.JdbcTemplate").add("spring-boot-starter-jdbc");
}
@Override
public void applyImports(ImportCustomizer imports) {
imports.addStarImports("org.springframework.jdbc.core",
"org.springframework.jdbc.core.namedparam");
imports.addStarImports("org.springframework.jdbc.core", "org.springframework.jdbc.core.namedparam");
imports.addImports("javax.sql.DataSource");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,16 +39,14 @@ public class JmsCompilerAutoConfiguration extends CompilerAutoConfiguration {
}
@Override
public void applyDependencies(DependencyCustomizer dependencies)
throws CompilationFailedException {
public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException {
dependencies.add("spring-jms", "jms-api");
}
@Override
public void applyImports(ImportCustomizer imports) throws CompilationFailedException {
imports.addStarImports("javax.jms", "org.springframework.jms.annotation",
"org.springframework.jms.config", "org.springframework.jms.core",
"org.springframework.jms.listener",
imports.addStarImports("javax.jms", "org.springframework.jms.annotation", "org.springframework.jms.config",
"org.springframework.jms.core", "org.springframework.jms.listener",
"org.springframework.jms.listener.adapter");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,20 +39,16 @@ public class RabbitCompilerAutoConfiguration extends CompilerAutoConfiguration {
}
@Override
public void applyDependencies(DependencyCustomizer dependencies)
throws CompilationFailedException {
public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException {
dependencies.add("spring-rabbit");
}
@Override
public void applyImports(ImportCustomizer imports) throws CompilationFailedException {
imports.addStarImports("org.springframework.amqp.rabbit.annotation",
"org.springframework.amqp.rabbit.core",
"org.springframework.amqp.rabbit.config",
"org.springframework.amqp.rabbit.connection",
"org.springframework.amqp.rabbit.listener",
"org.springframework.amqp.rabbit.listener.adapter",
imports.addStarImports("org.springframework.amqp.rabbit.annotation", "org.springframework.amqp.rabbit.core",
"org.springframework.amqp.rabbit.config", "org.springframework.amqp.rabbit.connection",
"org.springframework.amqp.rabbit.listener", "org.springframework.amqp.rabbit.listener.adapter",
"org.springframework.amqp.core");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,21 +38,17 @@ public class ReactorCompilerAutoConfiguration extends CompilerAutoConfiguration
@Override
public void applyDependencies(DependencyCustomizer dependencies) {
dependencies.ifAnyMissingClasses("reactor.bus.EventBus")
.add("reactor-spring-context", false).add("reactor-spring-core", false)
.add("reactor-bus").add("reactor-stream");
dependencies.ifAnyMissingClasses("reactor.bus.EventBus").add("reactor-spring-context", false)
.add("reactor-spring-core", false).add("reactor-bus").add("reactor-stream");
}
@Override
public void applyImports(ImportCustomizer imports) {
imports.addImports("reactor.bus.Bus", "reactor.bus.Event", "reactor.bus.EventBus",
"reactor.fn.Function", "reactor.fn.Functions", "reactor.fn.Predicate",
"reactor.fn.Predicates", "reactor.fn.Supplier", "reactor.fn.Suppliers",
"reactor.spring.context.annotation.Consumer",
"reactor.spring.context.annotation.ReplyTo",
"reactor.spring.context.annotation.Selector",
"reactor.spring.context.annotation.SelectorType",
"reactor.spring.context.config.EnableReactor")
imports.addImports("reactor.bus.Bus", "reactor.bus.Event", "reactor.bus.EventBus", "reactor.fn.Function",
"reactor.fn.Functions", "reactor.fn.Predicate", "reactor.fn.Predicates", "reactor.fn.Supplier",
"reactor.fn.Suppliers", "reactor.spring.context.annotation.Consumer",
"reactor.spring.context.annotation.ReplyTo", "reactor.spring.context.annotation.Selector",
"reactor.spring.context.annotation.SelectorType", "reactor.spring.context.config.EnableReactor")
.addStarImports("reactor.bus.selector.Selectors")
.addImport("ReactorEnvironment", "reactor.Environment");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2013 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -37,18 +37,14 @@ public class SpockCompilerAutoConfiguration extends CompilerAutoConfiguration {
}
@Override
public void applyDependencies(DependencyCustomizer dependencies)
throws CompilationFailedException {
dependencies.add("spock-core").add("junit").add("spring-test")
.add("hamcrest-library");
public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException {
dependencies.add("spock-core").add("junit").add("spring-test").add("hamcrest-library");
}
@Override
public void applyImports(ImportCustomizer imports) throws CompilationFailedException {
imports.addStarImports("spock.lang").addStarImports("org.junit")
.addStaticStars("org.junit.Assert")
.addStaticStars("org.hamcrest.MatcherAssert")
.addStaticStars("org.hamcrest.Matchers");
imports.addStarImports("spock.lang").addStarImports("org.junit").addStaticStars("org.junit.Assert")
.addStaticStars("org.hamcrest.MatcherAssert").addStaticStars("org.hamcrest.Matchers");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,10 +38,8 @@ public class SpringBatchCompilerAutoConfiguration extends CompilerAutoConfigurat
@Override
public void applyDependencies(DependencyCustomizer dependencies) {
dependencies.ifAnyMissingClasses("org.springframework.batch.core.Job")
.add("spring-boot-starter-batch");
dependencies.ifAnyMissingClasses("org.springframework.jdbc.core.JdbcTemplate")
.add("spring-jdbc");
dependencies.ifAnyMissingClasses("org.springframework.batch.core.Job").add("spring-boot-starter-batch");
dependencies.ifAnyMissingClasses("org.springframework.jdbc.core.JdbcTemplate").add("spring-jdbc");
}
@Override
@@ -53,14 +51,10 @@ public class SpringBatchCompilerAutoConfiguration extends CompilerAutoConfigurat
"org.springframework.batch.core.configuration.annotation.JobBuilderFactory",
"org.springframework.batch.core.configuration.annotation.StepBuilderFactory",
"org.springframework.batch.core.configuration.annotation.EnableBatchProcessing",
"org.springframework.batch.core.Step",
"org.springframework.batch.core.StepExecution",
"org.springframework.batch.core.StepContribution",
"org.springframework.batch.core.Job",
"org.springframework.batch.core.JobExecution",
"org.springframework.batch.core.JobParameter",
"org.springframework.batch.core.JobParameters",
"org.springframework.batch.core.launch.JobLauncher",
"org.springframework.batch.core.Step", "org.springframework.batch.core.StepExecution",
"org.springframework.batch.core.StepContribution", "org.springframework.batch.core.Job",
"org.springframework.batch.core.JobExecution", "org.springframework.batch.core.JobParameter",
"org.springframework.batch.core.JobParameters", "org.springframework.batch.core.launch.JobLauncher",
"org.springframework.batch.core.converter.JobParametersConverter",
"org.springframework.batch.core.converter.DefaultJobParametersConverter");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,32 +39,22 @@ public class SpringBootCompilerAutoConfiguration extends CompilerAutoConfigurati
@Override
public void applyDependencies(DependencyCustomizer dependencies) {
dependencies.ifAnyMissingClasses("org.springframework.boot.SpringApplication")
.add("spring-boot-starter");
dependencies.ifAnyMissingClasses("org.springframework.boot.SpringApplication").add("spring-boot-starter");
}
@Override
public void applyImports(ImportCustomizer imports) {
imports.addImports("javax.annotation.PostConstruct",
"javax.annotation.PreDestroy", "groovy.util.logging.Log",
"org.springframework.stereotype.Controller",
"org.springframework.stereotype.Service",
"org.springframework.stereotype.Component",
"org.springframework.beans.factory.annotation.Autowired",
"org.springframework.beans.factory.annotation.Value",
"org.springframework.context.annotation.Import",
imports.addImports("javax.annotation.PostConstruct", "javax.annotation.PreDestroy", "groovy.util.logging.Log",
"org.springframework.stereotype.Controller", "org.springframework.stereotype.Service",
"org.springframework.stereotype.Component", "org.springframework.beans.factory.annotation.Autowired",
"org.springframework.beans.factory.annotation.Value", "org.springframework.context.annotation.Import",
"org.springframework.context.annotation.ImportResource",
"org.springframework.context.annotation.Profile",
"org.springframework.context.annotation.Scope",
"org.springframework.context.annotation.Profile", "org.springframework.context.annotation.Scope",
"org.springframework.context.annotation.Configuration",
"org.springframework.context.annotation.ComponentScan",
"org.springframework.context.annotation.Bean",
"org.springframework.context.ApplicationContext",
"org.springframework.context.MessageSource",
"org.springframework.core.annotation.Order",
"org.springframework.core.io.ResourceLoader",
"org.springframework.boot.ApplicationRunner",
"org.springframework.boot.ApplicationArguments",
"org.springframework.context.annotation.ComponentScan", "org.springframework.context.annotation.Bean",
"org.springframework.context.ApplicationContext", "org.springframework.context.MessageSource",
"org.springframework.core.annotation.Order", "org.springframework.core.io.ResourceLoader",
"org.springframework.boot.ApplicationRunner", "org.springframework.boot.ApplicationArguments",
"org.springframework.boot.CommandLineRunner",
"org.springframework.boot.context.properties.ConfigurationProperties",
"org.springframework.boot.context.properties.EnableConfigurationProperties",
@@ -72,22 +62,19 @@ public class SpringBootCompilerAutoConfiguration extends CompilerAutoConfigurati
"org.springframework.boot.autoconfigure.SpringBootApplication",
"org.springframework.boot.context.properties.ConfigurationProperties",
"org.springframework.boot.context.properties.EnableConfigurationProperties");
imports.addStarImports("org.springframework.stereotype",
"org.springframework.scheduling.annotation");
imports.addStarImports("org.springframework.stereotype", "org.springframework.scheduling.annotation");
}
@Override
public void applyToMainClass(GroovyClassLoader loader,
GroovyCompilerConfiguration configuration, GeneratorContext generatorContext,
SourceUnit source, ClassNode classNode) throws CompilationFailedException {
public void applyToMainClass(GroovyClassLoader loader, GroovyCompilerConfiguration configuration,
GeneratorContext generatorContext, SourceUnit source, ClassNode classNode)
throws CompilationFailedException {
addEnableAutoConfigurationAnnotation(source, classNode);
}
private void addEnableAutoConfigurationAnnotation(SourceUnit source,
ClassNode classNode) {
private void addEnableAutoConfigurationAnnotation(SourceUnit source, ClassNode classNode) {
if (!hasEnableAutoConfigureAnnotation(classNode)) {
AnnotationNode annotationNode = new AnnotationNode(
ClassHelper.make("EnableAutoConfiguration"));
AnnotationNode annotationNode = new AnnotationNode(ClassHelper.make("EnableAutoConfiguration"));
classNode.addAnnotation(annotationNode);
}
}
@@ -95,8 +82,7 @@ public class SpringBootCompilerAutoConfiguration extends CompilerAutoConfigurati
private boolean hasEnableAutoConfigureAnnotation(ClassNode classNode) {
for (AnnotationNode node : classNode.getAnnotations()) {
String name = node.getClassNode().getNameWithoutPackage();
if ("EnableAutoConfiguration".equals(name)
|| "SpringBootApplication".equals(name)) {
if ("EnableAutoConfiguration".equals(name) || "SpringBootApplication".equals(name)) {
return true;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,8 +29,7 @@ import org.springframework.boot.cli.compiler.DependencyCustomizer;
* @author Dave Syer
* @author Artem Bilan
*/
public class SpringIntegrationCompilerAutoConfiguration
extends CompilerAutoConfiguration {
public class SpringIntegrationCompilerAutoConfiguration extends CompilerAutoConfiguration {
@Override
public boolean matches(ClassNode classNode) {
@@ -40,18 +39,14 @@ public class SpringIntegrationCompilerAutoConfiguration
@Override
public void applyDependencies(DependencyCustomizer dependencies) {
dependencies
.ifAnyMissingClasses(
"org.springframework.integration.config.EnableIntegration")
dependencies.ifAnyMissingClasses("org.springframework.integration.config.EnableIntegration")
.add("spring-boot-starter-integration");
}
@Override
public void applyImports(ImportCustomizer imports) {
imports.addImports("org.springframework.messaging.Message",
"org.springframework.messaging.MessageChannel",
"org.springframework.messaging.PollableChannel",
"org.springframework.messaging.SubscribableChannel",
imports.addImports("org.springframework.messaging.Message", "org.springframework.messaging.MessageChannel",
"org.springframework.messaging.PollableChannel", "org.springframework.messaging.SubscribableChannel",
"org.springframework.messaging.MessageHeaders",
"org.springframework.integration.support.MessageBuilder",
"org.springframework.integration.channel.DirectChannel",

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2013 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,8 +39,7 @@ public class SpringMobileCompilerAutoConfiguration extends CompilerAutoConfigura
}
@Override
public void applyDependencies(DependencyCustomizer dependencies)
throws CompilationFailedException {
public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException {
dependencies.add("spring-boot-starter-mobile");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2013 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,24 +34,21 @@ public class SpringMvcCompilerAutoConfiguration extends CompilerAutoConfiguratio
@Override
public boolean matches(ClassNode classNode) {
return AstUtils.hasAtLeastOneAnnotation(classNode, "Controller", "RestController",
"EnableWebMvc");
return AstUtils.hasAtLeastOneAnnotation(classNode, "Controller", "RestController", "EnableWebMvc");
}
@Override
public void applyDependencies(DependencyCustomizer dependencies) {
dependencies.ifAnyMissingClasses("org.springframework.web.servlet.mvc.Controller")
.add("spring-boot-starter-web");
dependencies.ifAnyMissingClasses("groovy.text.TemplateEngine")
.add("groovy-templates");
dependencies.ifAnyMissingClasses("groovy.text.TemplateEngine").add("groovy-templates");
}
@Override
public void applyImports(ImportCustomizer imports) {
imports.addStarImports("org.springframework.web.bind.annotation",
"org.springframework.web.servlet.config.annotation",
"org.springframework.web.servlet", "org.springframework.http",
"org.springframework.web.servlet.handler", "org.springframework.http",
"org.springframework.web.servlet.config.annotation", "org.springframework.web.servlet",
"org.springframework.http", "org.springframework.web.servlet.handler", "org.springframework.http",
"org.springframework.ui", "groovy.text");
imports.addStaticImport(GroovyTemplate.class.getName(), "template");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,15 +33,13 @@ public class SpringRetryCompilerAutoConfiguration extends CompilerAutoConfigurat
@Override
public boolean matches(ClassNode classNode) {
return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableRetry", "Retryable",
"Recover");
return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableRetry", "Retryable", "Recover");
}
@Override
public void applyDependencies(DependencyCustomizer dependencies) {
dependencies
.ifAnyMissingClasses("org.springframework.retry.annotation.EnableRetry")
.add("spring-retry", "spring-boot-starter-aop");
dependencies.ifAnyMissingClasses("org.springframework.retry.annotation.EnableRetry").add("spring-retry",
"spring-boot-starter-aop");
}
@Override

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,8 +32,7 @@ public class SpringSecurityCompilerAutoConfiguration extends CompilerAutoConfigu
@Override
public boolean matches(ClassNode classNode) {
return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableWebSecurity",
"EnableGlobalMethodSecurity");
return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableWebSecurity", "EnableGlobalMethodSecurity");
}
@Override
@@ -48,8 +47,7 @@ public class SpringSecurityCompilerAutoConfiguration extends CompilerAutoConfigu
imports.addImports("org.springframework.security.core.Authentication",
"org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity",
"org.springframework.security.core.authority.AuthorityUtils")
.addStarImports(
"org.springframework.security.config.annotation.web.configuration",
.addStarImports("org.springframework.security.config.annotation.web.configuration",
"org.springframework.security.authentication",
"org.springframework.security.config.annotation.web",
"org.springframework.security.config.annotation.web.builders");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,28 +31,23 @@ import org.springframework.boot.cli.compiler.DependencyCustomizer;
* @author Dave Syer
* @since 1.3.0
*/
public class SpringSecurityOAuth2CompilerAutoConfiguration
extends CompilerAutoConfiguration {
public class SpringSecurityOAuth2CompilerAutoConfiguration extends CompilerAutoConfiguration {
@Override
public boolean matches(ClassNode classNode) {
return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableAuthorizationServer",
"EnableResourceServer", "EnableOAuth2Client", "EnableOAuth2Sso");
return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableAuthorizationServer", "EnableResourceServer",
"EnableOAuth2Client", "EnableOAuth2Sso");
}
@Override
public void applyDependencies(DependencyCustomizer dependencies)
throws CompilationFailedException {
dependencies.add("spring-security-oauth2", "spring-boot-starter-web",
"spring-boot-starter-security");
public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException {
dependencies.add("spring-security-oauth2", "spring-boot-starter-web", "spring-boot-starter-security");
}
@Override
public void applyImports(ImportCustomizer imports) throws CompilationFailedException {
imports.addImports(
"org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso");
imports.addStarImports(
"org.springframework.security.oauth2.config.annotation.web.configuration",
imports.addImports("org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso");
imports.addStarImports("org.springframework.security.oauth2.config.annotation.web.configuration",
"org.springframework.security.access.prepost");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,8 +30,7 @@ import org.springframework.boot.cli.compiler.DependencyCustomizer;
* @author Craig Walls
* @since 1.1.0
*/
public class SpringSocialFacebookCompilerAutoConfiguration
extends CompilerAutoConfiguration {
public class SpringSocialFacebookCompilerAutoConfiguration extends CompilerAutoConfiguration {
@Override
public boolean matches(ClassNode classNode) {
@@ -39,10 +38,8 @@ public class SpringSocialFacebookCompilerAutoConfiguration
}
@Override
public void applyDependencies(DependencyCustomizer dependencies)
throws CompilationFailedException {
dependencies
.ifAnyMissingClasses("org.springframework.social.facebook.api.Facebook")
public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException {
dependencies.ifAnyMissingClasses("org.springframework.social.facebook.api.Facebook")
.add("spring-boot-starter-social-facebook");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,8 +30,7 @@ import org.springframework.boot.cli.compiler.DependencyCustomizer;
* @author Craig Walls
* @since 1.1.0
*/
public class SpringSocialLinkedInCompilerAutoConfiguration
extends CompilerAutoConfiguration {
public class SpringSocialLinkedInCompilerAutoConfiguration extends CompilerAutoConfiguration {
@Override
public boolean matches(ClassNode classNode) {
@@ -39,10 +38,8 @@ public class SpringSocialLinkedInCompilerAutoConfiguration
}
@Override
public void applyDependencies(DependencyCustomizer dependencies)
throws CompilationFailedException {
dependencies
.ifAnyMissingClasses("org.springframework.social.linkedin.api.LinkedIn")
public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException {
dependencies.ifAnyMissingClasses("org.springframework.social.linkedin.api.LinkedIn")
.add("spring-boot-starter-social-linkedin");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,8 +30,7 @@ import org.springframework.boot.cli.compiler.DependencyCustomizer;
* @author Craig Walls
* @since 1.1.0
*/
public class SpringSocialTwitterCompilerAutoConfiguration
extends CompilerAutoConfiguration {
public class SpringSocialTwitterCompilerAutoConfiguration extends CompilerAutoConfiguration {
@Override
public boolean matches(ClassNode classNode) {
@@ -39,8 +38,7 @@ public class SpringSocialTwitterCompilerAutoConfiguration
}
@Override
public void applyDependencies(DependencyCustomizer dependencies)
throws CompilationFailedException {
public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException {
dependencies.ifAnyMissingClasses("org.springframework.social.twitter.api.Twitter")
.add("spring-boot-starter-social-twitter");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -46,8 +46,7 @@ public class SpringTestCompilerAutoConfiguration extends CompilerAutoConfigurati
@Override
public void applyDependencies(DependencyCustomizer dependencies) {
dependencies.ifAnyMissingClasses("org.springframework.http.HttpHeaders")
.add("spring-boot-starter-web");
dependencies.ifAnyMissingClasses("org.springframework.http.HttpHeaders").add("spring-boot-starter-web");
}
@Override
@@ -56,8 +55,7 @@ public class SpringTestCompilerAutoConfiguration extends CompilerAutoConfigurati
throws CompilationFailedException {
if (!AstUtils.hasAtLeastOneAnnotation(classNode, "RunWith")) {
AnnotationNode runWith = new AnnotationNode(ClassHelper.make("RunWith"));
runWith.addMember("value",
new ClassExpression(ClassHelper.make("SpringRunner")));
runWith.addMember("value", new ClassExpression(ClassHelper.make("SpringRunner")));
classNode.addAnnotation(runWith);
}
}
@@ -65,11 +63,10 @@ public class SpringTestCompilerAutoConfiguration extends CompilerAutoConfigurati
@Override
public void applyImports(ImportCustomizer imports) throws CompilationFailedException {
imports.addStarImports("org.junit.runner", "org.springframework.boot.test",
"org.springframework.boot.test.context",
"org.springframework.boot.test.web.client", "org.springframework.http",
"org.springframework.test.context.junit4",
"org.springframework.test.annotation").addImports(
"org.springframework.boot.test.context.SpringBootTest.WebEnvironment",
"org.springframework.boot.test.context", "org.springframework.boot.test.web.client",
"org.springframework.http", "org.springframework.test.context.junit4",
"org.springframework.test.annotation")
.addImports("org.springframework.boot.test.context.SpringBootTest.WebEnvironment",
"org.springframework.boot.test.web.client.TestRestTemplate");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,22 +32,19 @@ public class SpringWebsocketCompilerAutoConfiguration extends CompilerAutoConfig
@Override
public boolean matches(ClassNode classNode) {
return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableWebSocket",
"EnableWebSocketMessageBroker");
return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableWebSocket", "EnableWebSocketMessageBroker");
}
@Override
public void applyDependencies(DependencyCustomizer dependencies) {
dependencies.ifAnyMissingClasses(
"org.springframework.web.socket.config.annotation.EnableWebSocket")
dependencies.ifAnyMissingClasses("org.springframework.web.socket.config.annotation.EnableWebSocket")
.add("spring-boot-starter-websocket").add("spring-messaging");
}
@Override
public void applyImports(ImportCustomizer imports) {
imports.addStarImports("org.springframework.messaging.handler.annotation",
"org.springframework.messaging.simp.config",
"org.springframework.web.socket.handler",
"org.springframework.messaging.simp.config", "org.springframework.web.socket.handler",
"org.springframework.web.socket.sockjs.transport.handler",
"org.springframework.web.socket.config.annotation")
.addImports("org.springframework.web.socket.WebSocketHandler");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2013 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,8 +29,7 @@ import org.springframework.boot.cli.compiler.DependencyCustomizer;
* @author Dave Syer
* @author Phillip Webb
*/
public class TransactionManagementCompilerAutoConfiguration
extends CompilerAutoConfiguration {
public class TransactionManagementCompilerAutoConfiguration extends CompilerAutoConfiguration {
@Override
public boolean matches(ClassNode classNode) {
@@ -39,16 +38,13 @@ public class TransactionManagementCompilerAutoConfiguration
@Override
public void applyDependencies(DependencyCustomizer dependencies) {
dependencies
.ifAnyMissingClasses(
"org.springframework.transaction.annotation.Transactional")
.add("spring-tx", "spring-boot-starter-aop");
dependencies.ifAnyMissingClasses("org.springframework.transaction.annotation.Transactional").add("spring-tx",
"spring-boot-starter-aop");
}
@Override
public void applyImports(ImportCustomizer imports) {
imports.addStarImports("org.springframework.transaction.annotation",
"org.springframework.transaction.support");
imports.addStarImports("org.springframework.transaction.annotation", "org.springframework.transaction.support");
imports.addImports("org.springframework.transaction.PlatformTransactionManager",
"org.springframework.transaction.support.AbstractPlatformTransactionManager");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -54,8 +54,7 @@ public final class Dependency {
* @param version the version
* @param exclusions the exclusions
*/
public Dependency(String groupId, String artifactId, String version,
List<Exclusion> exclusions) {
public Dependency(String groupId, String artifactId, String version, List<Exclusion> exclusions) {
Assert.notNull(groupId, "GroupId must not be null");
Assert.notNull(artifactId, "ArtifactId must not be null");
Assert.notNull(version, "Version must not be null");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,8 +25,7 @@ import org.springframework.util.StringUtils;
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class DependencyManagementArtifactCoordinatesResolver
implements ArtifactCoordinatesResolver {
public class DependencyManagementArtifactCoordinatesResolver implements ArtifactCoordinatesResolver {
private final DependencyManagement dependencyManagement;
@@ -34,8 +33,7 @@ public class DependencyManagementArtifactCoordinatesResolver
this(new SpringBootDependenciesDependencyManagement());
}
public DependencyManagementArtifactCoordinatesResolver(
DependencyManagement dependencyManagement) {
public DependencyManagementArtifactCoordinatesResolver(DependencyManagement dependencyManagement) {
this.dependencyManagement = dependencyManagement;
}
@@ -58,8 +56,7 @@ public class DependencyManagementArtifactCoordinatesResolver
}
if (id != null) {
if (id.startsWith("spring-boot")) {
return new Dependency("org.springframework.boot", id,
this.dependencyManagement.getSpringBootVersion());
return new Dependency("org.springframework.boot", id, this.dependencyManagement.getSpringBootVersion());
}
return this.dependencyManagement.find(id);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -46,17 +46,13 @@ public class MavenModelDependencyManagement implements DependencyManagement {
private static List<Dependency> extractDependenciesFromModel(Model model) {
List<Dependency> dependencies = new ArrayList<Dependency>();
for (org.apache.maven.model.Dependency mavenDependency : model
.getDependencyManagement().getDependencies()) {
for (org.apache.maven.model.Dependency mavenDependency : model.getDependencyManagement().getDependencies()) {
List<Exclusion> exclusions = new ArrayList<Exclusion>();
for (org.apache.maven.model.Exclusion mavenExclusion : mavenDependency
.getExclusions()) {
exclusions.add(new Exclusion(mavenExclusion.getGroupId(),
mavenExclusion.getArtifactId()));
for (org.apache.maven.model.Exclusion mavenExclusion : mavenDependency.getExclusions()) {
exclusions.add(new Exclusion(mavenExclusion.getGroupId(), mavenExclusion.getArtifactId()));
}
Dependency dependency = new Dependency(mavenDependency.getGroupId(),
mavenDependency.getArtifactId(), mavenDependency.getVersion(),
exclusions);
Dependency dependency = new Dependency(mavenDependency.getGroupId(), mavenDependency.getArtifactId(),
mavenDependency.getVersion(), exclusions);
dependencies.add(dependency);
}
return dependencies;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,8 +30,7 @@ import org.apache.maven.model.locator.DefaultModelLocator;
* @author Andy Wilkinson
* @since 1.3.0
*/
public class SpringBootDependenciesDependencyManagement
extends MavenModelDependencyManagement {
public class SpringBootDependenciesDependencyManagement extends MavenModelDependencyManagement {
public SpringBootDependenciesDependencyManagement() {
super(readModel());
@@ -43,12 +42,11 @@ public class SpringBootDependenciesDependencyManagement
modelProcessor.setModelReader(new DefaultModelReader());
try {
return modelProcessor.read(SpringBootDependenciesDependencyManagement.class
.getResourceAsStream("effective-pom.xml"), null);
return modelProcessor.read(
SpringBootDependenciesDependencyManagement.class.getResourceAsStream("effective-pom.xml"), null);
}
catch (IOException ex) {
throw new IllegalStateException("Failed to build model from effective pom",
ex);
throw new IllegalStateException("Failed to build model from effective pom", ex);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -73,18 +73,15 @@ public class AetherGrapeEngine implements GrapeEngine {
private final List<RemoteRepository> repositories;
public AetherGrapeEngine(GroovyClassLoader classLoader,
RepositorySystem repositorySystem,
DefaultRepositorySystemSession repositorySystemSession,
List<RemoteRepository> remoteRepositories,
public AetherGrapeEngine(GroovyClassLoader classLoader, RepositorySystem repositorySystem,
DefaultRepositorySystemSession repositorySystemSession, List<RemoteRepository> remoteRepositories,
DependencyResolutionContext resolutionContext, boolean quiet) {
this.classLoader = classLoader;
this.repositorySystem = repositorySystem;
this.session = repositorySystemSession;
this.resolutionContext = resolutionContext;
this.repositories = new ArrayList<RemoteRepository>();
List<RemoteRepository> remotes = new ArrayList<RemoteRepository>(
remoteRepositories);
List<RemoteRepository> remotes = new ArrayList<RemoteRepository>(remoteRepositories);
Collections.reverse(remotes); // priority is reversed in addRepository
for (RemoteRepository repository : remotes) {
addRepository(repository);
@@ -92,12 +89,10 @@ public class AetherGrapeEngine implements GrapeEngine {
this.progressReporter = getProgressReporter(this.session, quiet);
}
private ProgressReporter getProgressReporter(DefaultRepositorySystemSession session,
boolean quiet) {
String progressReporter = (quiet ? "none" : System.getProperty(
"org.springframework.boot.cli.compiler.grape.ProgressReporter"));
if ("detail".equals(progressReporter)
|| Boolean.getBoolean("groovy.grape.report.downloads")) {
private ProgressReporter getProgressReporter(DefaultRepositorySystemSession session, boolean quiet) {
String progressReporter = (quiet ? "none"
: System.getProperty("org.springframework.boot.cli.compiler.grape.ProgressReporter"));
if ("detail".equals(progressReporter) || Boolean.getBoolean("groovy.grape.report.downloads")) {
return new DetailedProgressReporter(session, System.out);
}
else if ("none".equals(progressReporter)) {
@@ -144,8 +139,7 @@ public class AetherGrapeEngine implements GrapeEngine {
private List<Exclusion> createExclusions(Map<?, ?> args) {
List<Exclusion> exclusions = new ArrayList<Exclusion>();
if (args != null) {
List<Map<String, Object>> exclusionMaps = (List<Map<String, Object>>) args
.get("excludes");
List<Map<String, Object>> exclusionMaps = (List<Map<String, Object>>) args.get("excludes");
if (exclusionMaps != null) {
for (Map<String, Object> exclusionMap : exclusionMaps) {
exclusions.add(createExclusion(exclusionMap));
@@ -161,8 +155,7 @@ public class AetherGrapeEngine implements GrapeEngine {
return new Exclusion(group, module, "*", "*");
}
private List<Dependency> createDependencies(Map<?, ?>[] dependencyMaps,
List<Exclusion> exclusions) {
private List<Dependency> createDependencies(Map<?, ?>[] dependencyMaps, List<Exclusion> exclusions) {
List<Dependency> dependencies = new ArrayList<Dependency>(dependencyMaps.length);
for (Map<?, ?> dependencyMap : dependencyMaps) {
dependencies.add(createDependency(dependencyMap, exclusions));
@@ -170,8 +163,7 @@ public class AetherGrapeEngine implements GrapeEngine {
return dependencies;
}
private Dependency createDependency(Map<?, ?> dependencyMap,
List<Exclusion> exclusions) {
private Dependency createDependency(Map<?, ?> dependencyMap, List<Exclusion> exclusions) {
Artifact artifact = createArtifact(dependencyMap);
if (isTransitive(dependencyMap)) {
return new Dependency(artifact, JavaScopes.COMPILE, false, exclusions);
@@ -201,8 +193,7 @@ public class AetherGrapeEngine implements GrapeEngine {
}
}
else if (ext != null && !type.equals(ext)) {
throw new IllegalArgumentException(
"If both type and ext are specified they must have the same value");
throw new IllegalArgumentException("If both type and ext are specified they must have the same value");
}
return type;
}
@@ -215,8 +206,7 @@ public class AetherGrapeEngine implements GrapeEngine {
private List<Dependency> getDependencies(DependencyResult dependencyResult) {
List<Dependency> dependencies = new ArrayList<Dependency>();
for (ArtifactResult artifactResult : dependencyResult.getArtifactResults()) {
dependencies.add(
new Dependency(artifactResult.getArtifact(), JavaScopes.COMPILE));
dependencies.add(new Dependency(artifactResult.getArtifact(), JavaScopes.COMPILE));
}
return dependencies;
}
@@ -238,8 +228,7 @@ public class AetherGrapeEngine implements GrapeEngine {
public void addResolver(Map<String, Object> args) {
String name = (String) args.get("name");
String root = (String) args.get("root");
RemoteRepository.Builder builder = new RemoteRepository.Builder(name, "default",
root);
RemoteRepository.Builder builder = new RemoteRepository.Builder(name, "default", root);
RemoteRepository repository = builder.build();
addRepository(repository);
}
@@ -255,8 +244,7 @@ public class AetherGrapeEngine implements GrapeEngine {
}
private RemoteRepository getPossibleMirror(RemoteRepository remoteRepository) {
RemoteRepository mirror = this.session.getMirrorSelector()
.getMirror(remoteRepository);
RemoteRepository mirror = this.session.getMirrorSelector().getMirror(remoteRepository);
if (mirror != null) {
return mirror;
}
@@ -275,8 +263,7 @@ public class AetherGrapeEngine implements GrapeEngine {
private RemoteRepository applyAuthentication(RemoteRepository repository) {
if (repository.getAuthentication() == null) {
RemoteRepository.Builder builder = new RemoteRepository.Builder(repository);
builder.setAuthentication(this.session.getAuthenticationSelector()
.getAuthentication(repository));
builder.setAuthentication(this.session.getAuthenticationSelector().getAuthentication(repository));
repository = builder.build();
}
return repository;
@@ -309,13 +296,11 @@ public class AetherGrapeEngine implements GrapeEngine {
}
}
private List<File> resolve(List<Dependency> dependencies)
throws ArtifactResolutionException {
private List<File> resolve(List<Dependency> dependencies) throws ArtifactResolutionException {
try {
CollectRequest collectRequest = getCollectRequest(dependencies);
DependencyRequest dependencyRequest = getDependencyRequest(collectRequest);
DependencyResult result = this.repositorySystem
.resolveDependencies(this.session, dependencyRequest);
DependencyResult result = this.repositorySystem.resolveDependencies(this.session, dependencyRequest);
addManagedDependencies(result);
return getFiles(result);
}
@@ -328,17 +313,15 @@ public class AetherGrapeEngine implements GrapeEngine {
}
private CollectRequest getCollectRequest(List<Dependency> dependencies) {
CollectRequest collectRequest = new CollectRequest((Dependency) null,
dependencies, new ArrayList<RemoteRepository>(this.repositories));
collectRequest
.setManagedDependencies(this.resolutionContext.getManagedDependencies());
CollectRequest collectRequest = new CollectRequest((Dependency) null, dependencies,
new ArrayList<RemoteRepository>(this.repositories));
collectRequest.setManagedDependencies(this.resolutionContext.getManagedDependencies());
return collectRequest;
}
private DependencyRequest getDependencyRequest(CollectRequest collectRequest) {
DependencyRequest dependencyRequest = new DependencyRequest(collectRequest,
DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE,
JavaScopes.RUNTIME));
DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE, JavaScopes.RUNTIME));
return dependencyRequest;
}
@@ -353,8 +336,7 @@ public class AetherGrapeEngine implements GrapeEngine {
@Override
public Object grab(String endorsedModule) {
throw new UnsupportedOperationException(
"Grabbing an endorsed module is not supported");
throw new UnsupportedOperationException("Grabbing an endorsed module is not supported");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,45 +45,36 @@ public abstract class AetherGrapeEngineFactory {
public static AetherGrapeEngine create(GroovyClassLoader classLoader,
List<RepositoryConfiguration> repositoryConfigurations,
DependencyResolutionContext dependencyResolutionContext, boolean quiet) {
RepositorySystem repositorySystem = createServiceLocator()
.getService(RepositorySystem.class);
DefaultRepositorySystemSession repositorySystemSession = MavenRepositorySystemUtils
.newSession();
RepositorySystem repositorySystem = createServiceLocator().getService(RepositorySystem.class);
DefaultRepositorySystemSession repositorySystemSession = MavenRepositorySystemUtils.newSession();
ServiceLoader<RepositorySystemSessionAutoConfiguration> autoConfigurations = ServiceLoader
.load(RepositorySystemSessionAutoConfiguration.class);
for (RepositorySystemSessionAutoConfiguration autoConfiguration : autoConfigurations) {
autoConfiguration.apply(repositorySystemSession, repositorySystem);
}
new DefaultRepositorySystemSessionAutoConfiguration()
.apply(repositorySystemSession, repositorySystem);
return new AetherGrapeEngine(classLoader, repositorySystem,
repositorySystemSession, createRepositories(repositoryConfigurations),
dependencyResolutionContext, quiet);
new DefaultRepositorySystemSessionAutoConfiguration().apply(repositorySystemSession, repositorySystem);
return new AetherGrapeEngine(classLoader, repositorySystem, repositorySystemSession,
createRepositories(repositoryConfigurations), dependencyResolutionContext, quiet);
}
private static ServiceLocator createServiceLocator() {
DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator();
locator.addService(RepositorySystem.class, DefaultRepositorySystem.class);
locator.addService(RepositoryConnectorFactory.class,
BasicRepositoryConnectorFactory.class);
locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class);
locator.addService(TransporterFactory.class, HttpTransporterFactory.class);
locator.addService(TransporterFactory.class, FileTransporterFactory.class);
return locator;
}
private static List<RemoteRepository> createRepositories(
List<RepositoryConfiguration> repositoryConfigurations) {
List<RemoteRepository> repositories = new ArrayList<RemoteRepository>(
repositoryConfigurations.size());
private static List<RemoteRepository> createRepositories(List<RepositoryConfiguration> repositoryConfigurations) {
List<RemoteRepository> repositories = new ArrayList<RemoteRepository>(repositoryConfigurations.size());
for (RepositoryConfiguration repositoryConfiguration : repositoryConfigurations) {
RemoteRepository.Builder builder = new RemoteRepository.Builder(
repositoryConfiguration.getName(), "default",
repositoryConfiguration.getUri().toASCIIString());
RemoteRepository.Builder builder = new RemoteRepository.Builder(repositoryConfiguration.getName(),
"default", repositoryConfiguration.getUri().toASCIIString());
if (!repositoryConfiguration.getSnapshotsEnabled()) {
builder.setSnapshotPolicy(
new RepositoryPolicy(false, RepositoryPolicy.UPDATE_POLICY_NEVER,
RepositoryPolicy.CHECKSUM_POLICY_IGNORE));
builder.setSnapshotPolicy(new RepositoryPolicy(false, RepositoryPolicy.UPDATE_POLICY_NEVER,
RepositoryPolicy.CHECKSUM_POLICY_IGNORE));
}
repositories.add(builder.build());
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,25 +34,22 @@ import org.springframework.util.StringUtils;
*
* @author Andy Wilkinson
*/
public class DefaultRepositorySystemSessionAutoConfiguration
implements RepositorySystemSessionAutoConfiguration {
public class DefaultRepositorySystemSessionAutoConfiguration implements RepositorySystemSessionAutoConfiguration {
@Override
public void apply(DefaultRepositorySystemSession session,
RepositorySystem repositorySystem) {
public void apply(DefaultRepositorySystemSession session, RepositorySystem repositorySystem) {
if (session.getLocalRepositoryManager() == null) {
LocalRepository localRepository = new LocalRepository(getM2RepoDirectory());
LocalRepositoryManager localRepositoryManager = repositorySystem
.newLocalRepositoryManager(session, localRepository);
LocalRepositoryManager localRepositoryManager = repositorySystem.newLocalRepositoryManager(session,
localRepository);
session.setLocalRepositoryManager(localRepositoryManager);
}
ProxySelector existing = session.getProxySelector();
if (existing == null || !(existing instanceof CompositeProxySelector)) {
JreProxySelector fallback = new JreProxySelector();
ProxySelector selector = (existing != null)
? new CompositeProxySelector(Arrays.asList(existing, fallback))
ProxySelector selector = (existing != null) ? new CompositeProxySelector(Arrays.asList(existing, fallback))
: fallback;
session.setProxySelector(selector);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -49,8 +49,7 @@ public class DependencyResolutionContext {
private ArtifactCoordinatesResolver artifactCoordinatesResolver;
private String getIdentifier(Dependency dependency) {
return getIdentifier(dependency.getArtifact().getGroupId(),
dependency.getArtifact().getArtifactId());
return getIdentifier(dependency.getArtifact().getGroupId(), dependency.getArtifact().getArtifactId());
}
private String getIdentifier(String groupId, String artifactId) {
@@ -64,8 +63,7 @@ public class DependencyResolutionContext {
public String getManagedVersion(String groupId, String artifactId) {
Dependency dependency = getManagedDependency(groupId, artifactId);
if (dependency == null) {
dependency = this.managedDependencyByGroupAndArtifact
.get(getIdentifier(groupId, artifactId));
dependency = this.managedDependencyByGroupAndArtifact.get(getIdentifier(groupId, artifactId));
}
return (dependency != null) ? dependency.getArtifact().getVersion() : null;
}
@@ -75,15 +73,13 @@ public class DependencyResolutionContext {
}
private Dependency getManagedDependency(String group, String artifact) {
return this.managedDependencyByGroupAndArtifact
.get(getIdentifier(group, artifact));
return this.managedDependencyByGroupAndArtifact.get(getIdentifier(group, artifact));
}
public void addManagedDependencies(List<Dependency> dependencies) {
this.managedDependencies.addAll(dependencies);
for (Dependency dependency : dependencies) {
this.managedDependencyByGroupAndArtifact.put(getIdentifier(dependency),
dependency);
this.managedDependencyByGroupAndArtifact.put(getIdentifier(dependency), dependency);
}
}
@@ -93,20 +89,16 @@ public class DependencyResolutionContext {
List<Exclusion> aetherExclusions = new ArrayList<Exclusion>();
for (org.springframework.boot.cli.compiler.dependencies.Dependency.Exclusion exclusion : dependency
.getExclusions()) {
aetherExclusions.add(new Exclusion(exclusion.getGroupId(),
exclusion.getArtifactId(), "*", "*"));
aetherExclusions.add(new Exclusion(exclusion.getGroupId(), exclusion.getArtifactId(), "*", "*"));
}
Dependency aetherDependency = new Dependency(
new DefaultArtifact(dependency.getGroupId(),
dependency.getArtifactId(), "jar", dependency.getVersion()),
JavaScopes.COMPILE, false, aetherExclusions);
Dependency aetherDependency = new Dependency(new DefaultArtifact(dependency.getGroupId(),
dependency.getArtifactId(), "jar", dependency.getVersion()), JavaScopes.COMPILE, false,
aetherExclusions);
this.managedDependencies.add(0, aetherDependency);
this.managedDependencyByGroupAndArtifact.put(getIdentifier(aetherDependency),
aetherDependency);
this.managedDependencyByGroupAndArtifact.put(getIdentifier(aetherDependency), aetherDependency);
}
this.dependencyManagement = (this.dependencyManagement != null)
? new CompositeDependencyManagement(dependencyManagement,
this.dependencyManagement)
? new CompositeDependencyManagement(dependencyManagement, this.dependencyManagement)
: dependencyManagement;
this.artifactCoordinatesResolver = new DependencyManagementArtifactCoordinatesResolver(
this.dependencyManagement);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,21 +31,18 @@ import org.eclipse.aether.transfer.TransferResource;
*/
final class DetailedProgressReporter implements ProgressReporter {
DetailedProgressReporter(DefaultRepositorySystemSession session,
final PrintStream out) {
DetailedProgressReporter(DefaultRepositorySystemSession session, final PrintStream out) {
session.setTransferListener(new AbstractTransferListener() {
@Override
public void transferStarted(TransferEvent event)
throws TransferCancelledException {
public void transferStarted(TransferEvent event) throws TransferCancelledException {
out.println("Downloading: " + getResourceIdentifier(event.getResource()));
}
@Override
public void transferSucceeded(TransferEvent event) {
out.printf("Downloaded: %s (%s)%n",
getResourceIdentifier(event.getResource()),
out.printf("Downloaded: %s (%s)%n", getResourceIdentifier(event.getResource()),
getTransferSpeed(event));
}
});
@@ -57,8 +54,7 @@ final class DetailedProgressReporter implements ProgressReporter {
private String getTransferSpeed(TransferEvent event) {
long kb = event.getTransferredBytes() / 1024;
float seconds = (System.currentTimeMillis()
- event.getResource().getTransferStartTime()) / 1000.0f;
float seconds = (System.currentTimeMillis() - event.getResource().getTransferStartTime()) / 1000.0f;
return String.format("%dKB at %.1fKB/sec", kb, (kb / seconds));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,24 +32,22 @@ import org.springframework.util.StringUtils;
* @author Andy Wilkinson
* @since 1.2.5
*/
public class GrapeRootRepositorySystemSessionAutoConfiguration
implements RepositorySystemSessionAutoConfiguration {
public class GrapeRootRepositorySystemSessionAutoConfiguration implements RepositorySystemSessionAutoConfiguration {
@Override
public void apply(DefaultRepositorySystemSession session,
RepositorySystem repositorySystem) {
public void apply(DefaultRepositorySystemSession session, RepositorySystem repositorySystem) {
String grapeRoot = System.getProperty("grape.root");
if (StringUtils.hasLength(grapeRoot)) {
configureLocalRepository(session, repositorySystem, grapeRoot);
}
}
private void configureLocalRepository(DefaultRepositorySystemSession session,
RepositorySystem repositorySystem, String grapeRoot) {
private void configureLocalRepository(DefaultRepositorySystemSession session, RepositorySystem repositorySystem,
String grapeRoot) {
File repositoryDir = new File(grapeRoot, "repository");
LocalRepository localRepository = new LocalRepository(repositoryDir);
LocalRepositoryManager localRepositoryManager = repositorySystem
.newLocalRepositoryManager(session, localRepository);
LocalRepositoryManager localRepositoryManager = repositorySystem.newLocalRepositoryManager(session,
localRepository);
session.setLocalRepositoryManager(localRepositoryManager);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -92,8 +92,8 @@ public final class RepositoryConfiguration {
@Override
public String toString() {
return "RepositoryConfiguration [name=" + this.name + ", uri=" + this.uri
+ ", snapshotsEnabled=" + this.snapshotsEnabled + "]";
return "RepositoryConfiguration [name=" + this.name + ", uri=" + this.uri + ", snapshotsEnabled="
+ this.snapshotsEnabled + "]";
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,17 +29,15 @@ import org.springframework.boot.cli.compiler.maven.MavenSettingsReader;
*
* @author Andy Wilkinson
*/
public class SettingsXmlRepositorySystemSessionAutoConfiguration
implements RepositorySystemSessionAutoConfiguration {
public class SettingsXmlRepositorySystemSessionAutoConfiguration implements RepositorySystemSessionAutoConfiguration {
@Override
public void apply(DefaultRepositorySystemSession session,
RepositorySystem repositorySystem) {
public void apply(DefaultRepositorySystemSession session, RepositorySystem repositorySystem) {
MavenSettings settings = getSettings(session);
String localRepository = settings.getLocalRepository();
if (localRepository != null) {
session.setLocalRepositoryManager(repositorySystem.newLocalRepositoryManager(
session, new LocalRepository(localRepository)));
session.setLocalRepositoryManager(
repositorySystem.newLocalRepositoryManager(session, new LocalRepository(localRepository)));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -73,15 +73,13 @@ final class SummaryProgressReporter implements ProgressReporter {
}
private void reportProgress() {
if (!this.finished
&& System.currentTimeMillis() - this.startTime > INITIAL_DELAY) {
if (!this.finished && System.currentTimeMillis() - this.startTime > INITIAL_DELAY) {
if (!this.started) {
this.started = true;
this.out.print("Resolving dependencies..");
this.lastProgressTime = System.currentTimeMillis();
}
else if (System.currentTimeMillis()
- this.lastProgressTime > PROGRESS_DELAY) {
else if (System.currentTimeMillis() - this.lastProgressTime > PROGRESS_DELAY) {
this.out.print(".");
this.lastProgressTime = System.currentTimeMillis();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -94,14 +94,13 @@ public class MavenSettings {
private MirrorSelector createMirrorSelector(Settings settings) {
DefaultMirrorSelector selector = new DefaultMirrorSelector();
for (Mirror mirror : settings.getMirrors()) {
selector.add(mirror.getId(), mirror.getUrl(), mirror.getLayout(), false,
mirror.getMirrorOf(), mirror.getMirrorOfLayouts());
selector.add(mirror.getId(), mirror.getUrl(), mirror.getLayout(), false, mirror.getMirrorOf(),
mirror.getMirrorOfLayouts());
}
return selector;
}
private AuthenticationSelector createAuthenticationSelector(
SettingsDecryptionResult decryptedSettings) {
private AuthenticationSelector createAuthenticationSelector(SettingsDecryptionResult decryptedSettings) {
DefaultAuthenticationSelector selector = new DefaultAuthenticationSelector();
for (Server server : decryptedSettings.getServers()) {
AuthenticationBuilder auth = new AuthenticationBuilder();
@@ -112,28 +111,22 @@ public class MavenSettings {
return new ConservativeAuthenticationSelector(selector);
}
private ProxySelector createProxySelector(
SettingsDecryptionResult decryptedSettings) {
private ProxySelector createProxySelector(SettingsDecryptionResult decryptedSettings) {
DefaultProxySelector selector = new DefaultProxySelector();
for (Proxy proxy : decryptedSettings.getProxies()) {
Authentication authentication = new AuthenticationBuilder()
.addUsername(proxy.getUsername()).addPassword(proxy.getPassword())
.build();
selector.add(
new org.eclipse.aether.repository.Proxy(proxy.getProtocol(),
proxy.getHost(), proxy.getPort(), authentication),
proxy.getNonProxyHosts());
Authentication authentication = new AuthenticationBuilder().addUsername(proxy.getUsername())
.addPassword(proxy.getPassword()).build();
selector.add(new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(),
authentication), proxy.getNonProxyHosts());
}
return selector;
}
private List<Profile> determineActiveProfiles(Settings settings) {
SpringBootCliModelProblemCollector problemCollector = new SpringBootCliModelProblemCollector();
List<org.apache.maven.model.Profile> activeModelProfiles = createProfileSelector()
.getActiveProfiles(createModelProfiles(settings.getProfiles()),
new SpringBootCliProfileActivationContext(
settings.getActiveProfiles()),
problemCollector);
List<org.apache.maven.model.Profile> activeModelProfiles = createProfileSelector().getActiveProfiles(
createModelProfiles(settings.getProfiles()),
new SpringBootCliProfileActivationContext(settings.getActiveProfiles()), problemCollector);
if (!problemCollector.getProblems().isEmpty()) {
throw new IllegalStateException(createFailureMessage(problemCollector));
}
@@ -145,14 +138,12 @@ public class MavenSettings {
return activeProfiles;
}
private String createFailureMessage(
SpringBootCliModelProblemCollector problemCollector) {
private String createFailureMessage(SpringBootCliModelProblemCollector problemCollector) {
StringWriter message = new StringWriter();
PrintWriter printer = new PrintWriter(message);
printer.println("Failed to determine active profiles:");
for (ModelProblemCollectorRequest problem : problemCollector.getProblems()) {
String location = (problem.getLocation() != null)
? " at " + problem.getLocation() : "";
String location = (problem.getLocation() != null) ? " at " + problem.getLocation() : "";
printer.println(" " + problem.getMessage() + location);
if (problem.getException() != null) {
printer.println(indentStackTrace(problem.getException(), " "));
@@ -191,31 +182,27 @@ public class MavenSettings {
private DefaultProfileSelector createProfileSelector() {
DefaultProfileSelector selector = new DefaultProfileSelector();
selector.addProfileActivator(new FileProfileActivator()
.setPathTranslator(new DefaultPathTranslator()));
selector.addProfileActivator(new FileProfileActivator().setPathTranslator(new DefaultPathTranslator()));
selector.addProfileActivator(new JdkVersionProfileActivator());
selector.addProfileActivator(new PropertyProfileActivator());
selector.addProfileActivator(new OperatingSystemProfileActivator());
return selector;
}
private List<org.apache.maven.model.Profile> createModelProfiles(
List<Profile> profiles) {
private List<org.apache.maven.model.Profile> createModelProfiles(List<Profile> profiles) {
List<org.apache.maven.model.Profile> modelProfiles = new ArrayList<org.apache.maven.model.Profile>();
for (Profile profile : profiles) {
org.apache.maven.model.Profile modelProfile = new org.apache.maven.model.Profile();
modelProfile.setId(profile.getId());
if (profile.getActivation() != null) {
modelProfile
.setActivation(createModelActivation(profile.getActivation()));
modelProfile.setActivation(createModelActivation(profile.getActivation()));
}
modelProfiles.add(modelProfile);
}
return modelProfiles;
}
private org.apache.maven.model.Activation createModelActivation(
Activation activation) {
private org.apache.maven.model.Activation createModelActivation(Activation activation) {
org.apache.maven.model.Activation modelActivation = new org.apache.maven.model.Activation();
modelActivation.setActiveByDefault(activation.isActiveByDefault());
if (activation.getFile() != null) {
@@ -266,8 +253,7 @@ public class MavenSettings {
return this.activeProfiles;
}
private static final class SpringBootCliProfileActivationContext
implements ProfileActivationContext {
private static final class SpringBootCliProfileActivationContext implements ProfileActivationContext {
private final List<String> activeProfiles;
@@ -308,8 +294,7 @@ public class MavenSettings {
}
private static final class SpringBootCliModelProblemCollector
implements ModelProblemCollector {
private static final class SpringBootCliModelProblemCollector implements ModelProblemCollector {
private final List<ModelProblemCollectorRequest> problems = new ArrayList<ModelProblemCollectorRequest>();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -57,8 +57,7 @@ public class MavenSettingsReader {
Settings settings = loadSettings();
SettingsDecryptionResult decrypted = decryptSettings(settings);
if (!decrypted.getProblems().isEmpty()) {
Log.error(
"Maven settings decryption failed. Some Maven repositories may be inaccessible");
Log.error("Maven settings decryption failed. Some Maven repositories may be inaccessible");
// Continue - the encrypted credentials may not be used
}
return new MavenSettings(settings, decrypted);
@@ -70,18 +69,15 @@ public class MavenSettingsReader {
request.setUserSettingsFile(settingsFile);
request.setSystemProperties(System.getProperties());
try {
return new DefaultSettingsBuilderFactory().newInstance().build(request)
.getEffectiveSettings();
return new DefaultSettingsBuilderFactory().newInstance().build(request).getEffectiveSettings();
}
catch (SettingsBuildingException ex) {
throw new IllegalStateException(
"Failed to build settings from " + settingsFile, ex);
throw new IllegalStateException("Failed to build settings from " + settingsFile, ex);
}
}
private SettingsDecryptionResult decryptSettings(Settings settings) {
DefaultSettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest(
settings);
DefaultSettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest(settings);
return createSettingsDecrypter().decrypt(request);
}
@@ -93,16 +89,14 @@ public class MavenSettingsReader {
return settingsDecrypter;
}
private void setField(Class<?> sourceClass, String fieldName, Object target,
Object value) {
private void setField(Class<?> sourceClass, String fieldName, Object target, Object value) {
try {
Field field = sourceClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(target, value);
}
catch (Exception ex) {
throw new IllegalStateException(
"Failed to set field '" + fieldName + "' on '" + target + "'", ex);
throw new IllegalStateException("Failed to set field '" + fieldName + "' on '" + target + "'", ex);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -74,13 +74,11 @@ public abstract class ResourceUtils {
return getUrlsFromWildcardPath(path, classLoader);
}
catch (Exception ex) {
throw new IllegalArgumentException(
"Cannot create URL from path [" + path + "]", ex);
throw new IllegalArgumentException("Cannot create URL from path [" + path + "]", ex);
}
}
private static List<String> getUrlsFromWildcardPath(String path,
ClassLoader classLoader) throws IOException {
private static List<String> getUrlsFromWildcardPath(String path, ClassLoader classLoader) throws IOException {
if (path.contains(":")) {
return getUrlsFromPrefixedWildcardPath(path, classLoader);
}
@@ -96,10 +94,10 @@ public abstract class ResourceUtils {
return new ArrayList<String>(result);
}
private static List<String> getUrlsFromPrefixedWildcardPath(String path,
ClassLoader classLoader) throws IOException {
Resource[] resources = new PathMatchingResourcePatternResolver(
new FileSearchResourceLoader(classLoader)).getResources(path);
private static List<String> getUrlsFromPrefixedWildcardPath(String path, ClassLoader classLoader)
throws IOException {
Resource[] resources = new PathMatchingResourcePatternResolver(new FileSearchResourceLoader(classLoader))
.getResources(path);
List<String> result = new ArrayList<String>();
for (Resource resource : resources) {
if (resource.exists()) {
@@ -116,8 +114,7 @@ public abstract class ResourceUtils {
}
private static List<String> getChildFiles(Resource resource) throws IOException {
Resource[] children = new PathMatchingResourcePatternResolver()
.getResources(resource.getURL() + "/**");
Resource[] children = new PathMatchingResourcePatternResolver().getResources(resource.getURL() + "/**");
List<String> childFiles = new ArrayList<String>();
for (Resource child : children) {
if (!child.getFile().isDirectory()) {
@@ -154,9 +151,7 @@ public abstract class ResourceUtils {
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(
location.substring(CLASSPATH_URL_PREFIX.length()),
getClassLoader());
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
}
else {
if (location.startsWith(FILE_URL_PREFIX)) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,8 +28,8 @@ import java.lang.annotation.Target;
* @author Andy Wilkinson
* @since 1.3.0
*/
@Target({ ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE,
ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE })
@Target({ ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD,
ElementType.PARAMETER, ElementType.TYPE })
@Retention(RetentionPolicy.SOURCE)
public @interface DependencyManagementBom {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,8 +36,7 @@ import org.codehaus.groovy.control.CompilationFailedException;
*/
public abstract class GroovyTemplate {
public static String template(String name)
throws IOException, CompilationFailedException, ClassNotFoundException {
public static String template(String name) throws IOException, CompilationFailedException, ClassNotFoundException {
return template(name, Collections.<String, Object>emptyMap());
}
@@ -46,8 +45,7 @@ public abstract class GroovyTemplate {
return template(new GStringTemplateEngine(), name, model);
}
public static String template(TemplateEngine engine, String name,
Map<String, ?> model)
public static String template(TemplateEngine engine, String name, Map<String, ?> model)
throws IOException, CompilationFailedException, ClassNotFoundException {
Writable writable = getTemplate(engine, name).make(model);
StringWriter result = new StringWriter();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,8 +34,7 @@ public class ClassLoaderIntegrationTests {
@Test
public void runWithIsolatedClassLoader() throws Exception {
// CLI classes or dependencies should not be exposed to the app
String output = this.cli.run("classloader-test-app.groovy",
SpringCli.class.getName());
String output = this.cli.run("classloader-test-app.groovy", SpringCli.class.getName());
assertThat(output).contains("HasClasses-false-true-false");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -100,8 +100,7 @@ public class CliTester implements TestRule {
return getOutput();
}
private <T extends OptionParsingCommand> Future<T> submitCommand(final T command,
String... args) {
private <T extends OptionParsingCommand> Future<T> submitCommand(final T command, String... args) {
clearUrlHandler();
final String[] sources = getSources(args);
return Executors.newSingleThreadExecutor().submit(new Callable<T>() {
@@ -161,16 +160,13 @@ public class CliTester implements TestRule {
@Override
public Statement apply(final Statement base, final Description description) {
final Statement statement = CliTester.this.outputCapture
.apply(new RunLauncherStatement(base), description);
final Statement statement = CliTester.this.outputCapture.apply(new RunLauncherStatement(base), description);
return new Statement() {
@Override
public void evaluate() throws Throwable {
Assume.assumeTrue(
"Not running sample integration tests because integration profile not active",
System.getProperty("spring.profiles.active", "integration")
.contains("integration"));
Assume.assumeTrue("Not running sample integration tests because integration profile not active",
System.getProperty("spring.profiles.active", "integration").contains("integration"));
statement.evaluate();
}
};
@@ -182,8 +178,7 @@ public class CliTester implements TestRule {
public String getHttpOutput(String uri) {
try {
InputStream stream = URI.create("http://localhost:" + this.port + uri).toURL()
.openStream();
InputStream stream = URI.create("http://localhost:" + this.port + uri).toURL().openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
StringBuilder result = new StringBuilder();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -56,34 +56,29 @@ public class GrabCommandIntegrationTests {
// Use --autoconfigure=false to limit the amount of downloaded dependencies
String output = this.cli.grab("grab.groovy", "--autoconfigure=false");
assertThat(new File("target/repository/joda-time/joda-time").isDirectory())
.isTrue();
assertThat(new File("target/repository/joda-time/joda-time").isDirectory()).isTrue();
// Should be resolved from local repository cache
assertThat(output.contains("Downloading: file:")).isTrue();
}
@Test
public void duplicateDependencyManagementBomAnnotationsProducesAnError()
throws Exception {
public void duplicateDependencyManagementBomAnnotationsProducesAnError() throws Exception {
try {
this.cli.grab("duplicateDependencyManagementBom.groovy");
fail();
}
catch (Exception ex) {
assertThat(ex.getMessage())
.contains("Duplicate @DependencyManagementBom annotation");
assertThat(ex.getMessage()).contains("Duplicate @DependencyManagementBom annotation");
}
}
@Test
public void customMetadata() throws Exception {
System.setProperty("grape.root", "target");
FileSystemUtils.copyRecursively(
new File("src/test/resources/grab-samples/repository"),
FileSystemUtils.copyRecursively(new File("src/test/resources/grab-samples/repository"),
new File("target/repository"));
this.cli.grab("customDependencyManagement.groovy", "--autoconfigure=false");
assertThat(new File("target/repository/javax/ejb/ejb-api/3.0").isDirectory())
.isTrue();
assertThat(new File("target/repository/javax/ejb/ejb-api/3.0").isDirectory()).isTrue();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -147,8 +147,7 @@ public class SampleIntegrationTests {
System.setProperty("spring.artemis.embedded.queues", "spring-boot");
try {
String output = this.cli.run("jms.groovy");
assertThat(output)
.contains("Received Greetings from Spring Boot via Artemis");
assertThat(output).contains("Received Greetings from Spring Boot via Artemis");
}
finally {
System.clearProperty("spring.artemis.embedded.queues");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,32 +47,27 @@ public class SpringApplicationLauncherTests {
@Test
public void launchWithClassConfiguredBySystemProperty() {
System.setProperty("spring.application.class.name",
"system.property.SpringApplication");
System.setProperty("spring.application.class.name", "system.property.SpringApplication");
assertThat(launch()).contains("system.property.SpringApplication");
}
@Test
public void launchWithClassConfiguredByEnvironmentVariable() {
this.env.put("SPRING_APPLICATION_CLASS_NAME",
"environment.variable.SpringApplication");
this.env.put("SPRING_APPLICATION_CLASS_NAME", "environment.variable.SpringApplication");
assertThat(launch()).contains("environment.variable.SpringApplication");
}
@Test
public void systemPropertyOverridesEnvironmentVariable() {
System.setProperty("spring.application.class.name",
"system.property.SpringApplication");
this.env.put("SPRING_APPLICATION_CLASS_NAME",
"environment.variable.SpringApplication");
System.setProperty("spring.application.class.name", "system.property.SpringApplication");
this.env.put("SPRING_APPLICATION_CLASS_NAME", "environment.variable.SpringApplication");
assertThat(launch()).contains("system.property.SpringApplication");
}
@Test
public void sourcesDefaultPropertiesAndArgsAreUsedToLaunch() throws Exception {
System.setProperty("spring.application.class.name",
TestSpringApplication.class.getName());
System.setProperty("spring.application.class.name", TestSpringApplication.class.getName());
Object[] sources = new Object[0];
String[] args = new String[0];
new SpringApplicationLauncher(getClass().getClassLoader()).launch(sources, args);
@@ -81,15 +76,14 @@ public class SpringApplicationLauncherTests {
assertThat(args == TestSpringApplication.args).isTrue();
Map<String, String> defaultProperties = TestSpringApplication.defaultProperties;
assertThat(defaultProperties).hasSize(1)
.containsEntry("spring.groovy.template.check-template-location", "false");
assertThat(defaultProperties).hasSize(1).containsEntry("spring.groovy.template.check-template-location",
"false");
}
private Set<String> launch() {
TestClassLoader classLoader = new TestClassLoader(getClass().getClassLoader());
try {
new TestSpringApplicationLauncher(classLoader).launch(new Object[0],
new String[0]);
new TestSpringApplicationLauncher(classLoader).launch(new Object[0], new String[0]);
}
catch (Exception ex) {
// Launch will fail, but we can still check that the launcher tried to use
@@ -107,8 +101,7 @@ public class SpringApplicationLauncherTests {
}
@Override
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
this.classes.add(name);
return super.loadClass(name, resolve);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,8 +33,7 @@ public class OptionParsingCommandTests {
public void optionHelp() {
OptionHandler handler = new OptionHandler();
handler.option("bar", "Bar");
OptionParsingCommand command = new TestOptionParsingCommand("foo", "Foo",
handler);
OptionParsingCommand command = new TestOptionParsingCommand("foo", "Foo", handler);
assertThat(command.getHelp()).contains("--bar");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,33 +40,26 @@ public class ResourceMatcherTests {
@Test
public void nonExistentRoot() throws IOException {
ResourceMatcher resourceMatcher = new ResourceMatcher(
Arrays.asList("alpha/**", "bravo/*", "*"),
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("alpha/**", "bravo/*", "*"),
Arrays.asList(".*", "alpha/**/excluded"));
List<MatchedResource> matchedResources = resourceMatcher
.find(Arrays.asList(new File("does-not-exist")));
List<MatchedResource> matchedResources = resourceMatcher.find(Arrays.asList(new File("does-not-exist")));
assertThat(matchedResources).isEmpty();
}
@SuppressWarnings("unchecked")
@Test
public void defaults() throws Exception {
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""),
Arrays.asList(""));
Collection<String> includes = (Collection<String>) ReflectionTestUtils
.getField(resourceMatcher, "includes");
Collection<String> excludes = (Collection<String>) ReflectionTestUtils
.getField(resourceMatcher, "excludes");
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), Arrays.asList(""));
Collection<String> includes = (Collection<String>) ReflectionTestUtils.getField(resourceMatcher, "includes");
Collection<String> excludes = (Collection<String>) ReflectionTestUtils.getField(resourceMatcher, "excludes");
assertThat(includes).contains("static/**");
assertThat(excludes).contains("**/*.jar");
}
@Test
public void excludedWins() throws Exception {
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"),
Arrays.asList("**/*.jar"));
List<MatchedResource> found = resourceMatcher
.find(Arrays.asList(new File("src/test/resources")));
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"), Arrays.asList("**/*.jar"));
List<MatchedResource> found = resourceMatcher.find(Arrays.asList(new File("src/test/resources")));
assertThat(found).areNot(new Condition<MatchedResource>() {
@Override
@@ -80,10 +73,8 @@ public class ResourceMatcherTests {
@SuppressWarnings("unchecked")
@Test
public void includedDeltas() throws Exception {
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("-static/**"),
Arrays.asList(""));
Collection<String> includes = (Collection<String>) ReflectionTestUtils
.getField(resourceMatcher, "includes");
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("-static/**"), Arrays.asList(""));
Collection<String> includes = (Collection<String>) ReflectionTestUtils.getField(resourceMatcher, "includes");
assertThat(includes).contains("templates/**");
assertThat(includes).doesNotContain("static/**");
}
@@ -91,12 +82,10 @@ public class ResourceMatcherTests {
@SuppressWarnings("unchecked")
@Test
public void includedDeltasAndNewEntries() throws Exception {
ResourceMatcher resourceMatcher = new ResourceMatcher(
Arrays.asList("-static/**", "foo.jar"), Arrays.asList("-**/*.jar"));
Collection<String> includes = (Collection<String>) ReflectionTestUtils
.getField(resourceMatcher, "includes");
Collection<String> excludes = (Collection<String>) ReflectionTestUtils
.getField(resourceMatcher, "excludes");
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("-static/**", "foo.jar"),
Arrays.asList("-**/*.jar"));
Collection<String> includes = (Collection<String>) ReflectionTestUtils.getField(resourceMatcher, "includes");
Collection<String> excludes = (Collection<String>) ReflectionTestUtils.getField(resourceMatcher, "excludes");
assertThat(includes).contains("foo.jar");
assertThat(includes).contains("templates/**");
assertThat(includes).doesNotContain("static/**");
@@ -106,20 +95,16 @@ public class ResourceMatcherTests {
@SuppressWarnings("unchecked")
@Test
public void excludedDeltas() throws Exception {
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""),
Arrays.asList("-**/*.jar"));
Collection<String> excludes = (Collection<String>) ReflectionTestUtils
.getField(resourceMatcher, "excludes");
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), Arrays.asList("-**/*.jar"));
Collection<String> excludes = (Collection<String>) ReflectionTestUtils.getField(resourceMatcher, "excludes");
assertThat(excludes).doesNotContain("**/*.jar");
}
@Test
public void jarFileAlwaysMatches() throws Exception {
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"),
Arrays.asList("**/*.jar"));
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"), Arrays.asList("**/*.jar"));
List<MatchedResource> found = resourceMatcher
.find(Arrays.asList(new File("src/test/resources/templates"),
new File("src/test/resources/foo.jar")));
.find(Arrays.asList(new File("src/test/resources/templates"), new File("src/test/resources/foo.jar")));
assertThat(found).areAtLeastOne(new Condition<MatchedResource>() {
@Override
@@ -132,8 +117,7 @@ public class ResourceMatcherTests {
@Test
public void resourceMatching() throws IOException {
ResourceMatcher resourceMatcher = new ResourceMatcher(
Arrays.asList("alpha/**", "bravo/*", "*"),
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("alpha/**", "bravo/*", "*"),
Arrays.asList(".*", "alpha/**/excluded"));
List<MatchedResource> matchedResources = resourceMatcher
.find(Arrays.asList(new File("src/test/resources/resource-matcher/one"),
@@ -143,8 +127,7 @@ public class ResourceMatcherTests {
for (MatchedResource resource : matchedResources) {
paths.add(resource.getName());
}
assertThat(paths).containsOnly("alpha/nested/fileA", "bravo/fileC", "fileD",
"bravo/fileE", "fileF", "three");
assertThat(paths).containsOnly("alpha/nested/fileA", "bravo/fileC", "fileD", "bravo/fileE", "fileF", "three");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -51,30 +51,26 @@ public abstract class AbstractHttpClientMockTests {
protected final CloseableHttpClient http = mock(CloseableHttpClient.class);
protected void mockSuccessfulMetadataTextGet() throws IOException {
mockSuccessfulMetadataGet("metadata/service-metadata-2.1.0.txt", "text/plain",
true);
mockSuccessfulMetadataGet("metadata/service-metadata-2.1.0.txt", "text/plain", true);
}
protected void mockSuccessfulMetadataGet(boolean serviceCapabilities)
protected void mockSuccessfulMetadataGet(boolean serviceCapabilities) throws IOException {
mockSuccessfulMetadataGet("metadata/service-metadata-2.1.0.json", "application/vnd.initializr.v2.1+json",
serviceCapabilities);
}
protected void mockSuccessfulMetadataGetV2(boolean serviceCapabilities) throws IOException {
mockSuccessfulMetadataGet("metadata/service-metadata-2.0.0.json", "application/vnd.initializr.v2+json",
serviceCapabilities);
}
protected void mockSuccessfulMetadataGet(String contentPath, String contentType, boolean serviceCapabilities)
throws IOException {
mockSuccessfulMetadataGet("metadata/service-metadata-2.1.0.json",
"application/vnd.initializr.v2.1+json", serviceCapabilities);
}
protected void mockSuccessfulMetadataGetV2(boolean serviceCapabilities)
throws IOException {
mockSuccessfulMetadataGet("metadata/service-metadata-2.0.0.json",
"application/vnd.initializr.v2+json", serviceCapabilities);
}
protected void mockSuccessfulMetadataGet(String contentPath, String contentType,
boolean serviceCapabilities) throws IOException {
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
byte[] content = readClasspathResource(contentPath);
mockHttpEntity(response, content, contentType);
mockStatus(response, 200);
given(this.http.execute(argThat(getForMetadata(serviceCapabilities))))
.willReturn(response);
given(this.http.execute(argThat(getForMetadata(serviceCapabilities)))).willReturn(response);
}
protected byte[] readClasspathResource(String contentPath) throws IOException {
@@ -82,46 +78,38 @@ public abstract class AbstractHttpClientMockTests {
return StreamUtils.copyToByteArray(resource.getInputStream());
}
protected void mockSuccessfulProjectGeneration(
MockHttpProjectGenerationRequest request) throws IOException {
protected void mockSuccessfulProjectGeneration(MockHttpProjectGenerationRequest request) throws IOException {
// Required for project generation as the metadata is read first
mockSuccessfulMetadataGet(false);
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
mockHttpEntity(response, request.content, request.contentType);
mockStatus(response, 200);
String header = (request.fileName != null)
? contentDispositionValue(request.fileName) : null;
String header = (request.fileName != null) ? contentDispositionValue(request.fileName) : null;
mockHttpHeader(response, "Content-Disposition", header);
given(this.http.execute(argThat(getForNonMetadata()))).willReturn(response);
}
protected void mockProjectGenerationError(int status, String message)
throws IOException, JSONException {
protected void mockProjectGenerationError(int status, String message) throws IOException, JSONException {
// Required for project generation as the metadata is read first
mockSuccessfulMetadataGet(false);
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
mockHttpEntity(response, createJsonError(status, message).getBytes(),
"application/json");
mockHttpEntity(response, createJsonError(status, message).getBytes(), "application/json");
mockStatus(response, status);
given(this.http.execute(isA(HttpGet.class))).willReturn(response);
}
protected void mockMetadataGetError(int status, String message)
throws IOException, JSONException {
protected void mockMetadataGetError(int status, String message) throws IOException, JSONException {
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
mockHttpEntity(response, createJsonError(status, message).getBytes(),
"application/json");
mockHttpEntity(response, createJsonError(status, message).getBytes(), "application/json");
mockStatus(response, status);
given(this.http.execute(isA(HttpGet.class))).willReturn(response);
}
protected HttpEntity mockHttpEntity(CloseableHttpResponse response, byte[] content,
String contentType) {
protected HttpEntity mockHttpEntity(CloseableHttpResponse response, byte[] content, String contentType) {
try {
HttpEntity entity = mock(HttpEntity.class);
given(entity.getContent()).willReturn(new ByteArrayInputStream(content));
Header contentTypeHeader = (contentType != null)
? new BasicHeader("Content-Type", contentType) : null;
Header contentTypeHeader = (contentType != null) ? new BasicHeader("Content-Type", contentType) : null;
given(entity.getContentType()).willReturn(contentTypeHeader);
given(response.getEntity()).willReturn(entity);
return entity;
@@ -137,8 +125,7 @@ public abstract class AbstractHttpClientMockTests {
given(response.getStatusLine()).willReturn(statusLine);
}
protected void mockHttpHeader(CloseableHttpResponse response, String headerName,
String value) {
protected void mockHttpHeader(CloseableHttpResponse response, String headerName, String value) {
Header header = (value != null) ? new BasicHeader(headerName, value) : null;
given(response.getFirstHeader(headerName)).willReturn(header);
}
@@ -179,8 +166,7 @@ public abstract class AbstractHttpClientMockTests {
this(contentType, fileName, new byte[] { 0, 0, 0, 0 });
}
public MockHttpProjectGenerationRequest(String contentType, String fileName,
byte[] content) {
public MockHttpProjectGenerationRequest(String contentType, String fileName, byte[] content) {
this.contentType = contentType;
this.fileName = fileName;
this.content = content;

View File

@@ -92,8 +92,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
String fileName = UUID.randomUUID().toString() + ".zip";
File file = new File(fileName);
assertThat(file.exists()).as("file should not exist").isFalse();
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", fileName);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", fileName);
mockSuccessfulProjectGeneration(request);
try {
assertThat(this.command.run()).isEqualTo(ExitStatus.OK);
@@ -106,8 +105,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
@Test
public void generateProjectNoFileNameAvailable() throws Exception {
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", null);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", null);
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run()).isEqualTo(ExitStatus.ERROR);
}
@@ -116,25 +114,22 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
public void generateProjectAndExtract() throws Exception {
File folder = this.temporaryFolder.newFolder();
byte[] archive = createFakeZipArchive("test.txt", "Fake content");
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", "demo.zip", archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip",
archive);
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run("--extract", folder.getAbsolutePath()))
.isEqualTo(ExitStatus.OK);
assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK);
File archiveFile = new File(folder, "test.txt");
assertThat(archiveFile).exists();
}
@Test
public void generateProjectAndExtractWillNotWriteEntriesOutsideOutputLocation()
throws Exception {
public void generateProjectAndExtractWillNotWriteEntriesOutsideOutputLocation() throws Exception {
File folder = this.temporaryFolder.newFolder();
byte[] archive = createFakeZipArchive("../outside.txt", "Fake content");
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", "demo.zip", archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip",
archive);
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run("--extract", folder.getAbsolutePath()))
.isEqualTo(ExitStatus.ERROR);
assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.ERROR);
File archiveFile = new File(folder.getParentFile(), "outside.txt");
assertThat(archiveFile).doesNotExist();
}
@@ -143,11 +138,10 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
public void generateProjectAndExtractWithConvention() throws Exception {
File folder = this.temporaryFolder.newFolder();
byte[] archive = createFakeZipArchive("test.txt", "Fake content");
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", "demo.zip", archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip",
archive);
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run(folder.getAbsolutePath() + "/"))
.isEqualTo(ExitStatus.OK);
assertThat(this.command.run(folder.getAbsolutePath() + "/")).isEqualTo(ExitStatus.OK);
File archiveFile = new File(folder, "test.txt");
assertThat(archiveFile).exists();
}
@@ -157,8 +151,8 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
String fileName = UUID.randomUUID().toString();
assertThat(fileName.contains(".")).as("No dot in filename").isFalse();
byte[] archive = createFakeZipArchive("test.txt", "Fake content");
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", "demo.zip", archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip",
archive);
mockSuccessfulProjectGeneration(request);
File file = new File(fileName);
File archiveFile = new File(file, "test.txt");
@@ -177,8 +171,8 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
String fileName = UUID.randomUUID().toString();
String content = "Fake Content";
byte[] archive = content.getBytes();
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/octet-stream", "pom.xml", archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/octet-stream",
"pom.xml", archive);
mockSuccessfulProjectGeneration(request);
File file = new File(fileName);
try {
@@ -199,11 +193,10 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
assertThat(file.exists()).as("file should not exist").isFalse();
try {
byte[] archive = createFakeZipArchive("test.txt", "Fake content");
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/foobar", fileName, archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/foobar",
fileName, archive);
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run("--extract", folder.getAbsolutePath()))
.isEqualTo(ExitStatus.OK);
assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK);
assertThat(file.exists()).as("file should have been saved instead").isTrue();
}
finally {
@@ -219,11 +212,9 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
assertThat(file.exists()).as("file should not exist").isFalse();
try {
byte[] archive = createFakeZipArchive("test.txt", "Fake content");
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
null, fileName, archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(null, fileName, archive);
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run("--extract", folder.getAbsolutePath()))
.isEqualTo(ExitStatus.OK);
assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK);
assertThat(file.exists()).as("file should have been saved instead").isTrue();
}
finally {
@@ -235,21 +226,19 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
public void fileNotOverwrittenByDefault() throws Exception {
File file = this.temporaryFolder.newFile();
long fileLength = file.length();
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", file.getAbsolutePath());
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip",
file.getAbsolutePath());
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run()).as("Should have failed")
.isEqualTo(ExitStatus.ERROR);
assertThat(file.length()).as("File should not have changed")
.isEqualTo(fileLength);
assertThat(this.command.run()).as("Should have failed").isEqualTo(ExitStatus.ERROR);
assertThat(file.length()).as("File should not have changed").isEqualTo(fileLength);
}
@Test
public void overwriteFile() throws Exception {
File file = this.temporaryFolder.newFile();
long fileLength = file.length();
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", file.getAbsolutePath());
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip",
file.getAbsolutePath());
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run("--force")).isEqualTo(ExitStatus.OK);
assertThat(fileLength != file.length()).as("File should have changed").isTrue();
@@ -259,33 +248,28 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
public void fileInArchiveNotOverwrittenByDefault() throws Exception {
File folder = this.temporaryFolder.newFolder();
File conflict = new File(folder, "test.txt");
assertThat(conflict.createNewFile()).as("Should have been able to create file")
.isTrue();
assertThat(conflict.createNewFile()).as("Should have been able to create file").isTrue();
long fileLength = conflict.length();
// also contains test.txt
byte[] archive = createFakeZipArchive("test.txt", "Fake content");
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", "demo.zip", archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip",
archive);
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run("--extract", folder.getAbsolutePath()))
.isEqualTo(ExitStatus.ERROR);
assertThat(conflict.length()).as("File should not have changed")
.isEqualTo(fileLength);
assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.ERROR);
assertThat(conflict.length()).as("File should not have changed").isEqualTo(fileLength);
}
@Test
public void parseProjectOptions() throws Exception {
this.handler.disableProjectGeneration();
this.command.run("-g=org.demo", "-a=acme", "-v=1.2.3-SNAPSHOT", "-n=acme-sample",
"--description=Acme sample project", "--package-name=demo.foo",
"-t=ant-project", "--build=grunt", "--format=web", "-p=war", "-j=1.9",
"-l=groovy", "-b=1.2.0.RELEASE", "-d=web,data-jpa");
"--description=Acme sample project", "--package-name=demo.foo", "-t=ant-project", "--build=grunt",
"--format=web", "-p=war", "-j=1.9", "-l=groovy", "-b=1.2.0.RELEASE", "-d=web,data-jpa");
assertThat(this.handler.lastRequest.getGroupId()).isEqualTo("org.demo");
assertThat(this.handler.lastRequest.getArtifactId()).isEqualTo("acme");
assertThat(this.handler.lastRequest.getVersion()).isEqualTo("1.2.3-SNAPSHOT");
assertThat(this.handler.lastRequest.getName()).isEqualTo("acme-sample");
assertThat(this.handler.lastRequest.getDescription())
.isEqualTo("Acme sample project");
assertThat(this.handler.lastRequest.getDescription()).isEqualTo("Acme sample project");
assertThat(this.handler.lastRequest.getPackageName()).isEqualTo("demo.foo");
assertThat(this.handler.lastRequest.getType()).isEqualTo("ant-project");
assertThat(this.handler.lastRequest.getBuild()).isEqualTo("grunt");
@@ -304,18 +288,15 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
public void overwriteFileInArchive() throws Exception {
File folder = this.temporaryFolder.newFolder();
File conflict = new File(folder, "test.txt");
assertThat(conflict.createNewFile()).as("Should have been able to create file")
.isTrue();
assertThat(conflict.createNewFile()).as("Should have been able to create file").isTrue();
long fileLength = conflict.length();
// also contains test.txt
byte[] archive = createFakeZipArchive("test.txt", "Fake content");
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", "demo.zip", archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip",
archive);
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run("--force", "--extract", folder.getAbsolutePath()))
.isEqualTo(ExitStatus.OK);
assertThat(fileLength != conflict.length()).as("File should have changed")
.isTrue();
assertThat(this.command.run("--force", "--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK);
assertThat(fileLength != conflict.length()).as("File should have changed").isTrue();
}
@Test
@@ -377,8 +358,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
assertThat(agent.getValue()).startsWith("SpringBootCli/");
}
private byte[] createFakeZipArchive(String fileName, String content)
throws IOException {
private byte[] createFakeZipArchive(String fileName, String content) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos);
try {
@@ -393,8 +373,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
return bos.toByteArray();
}
private static class TestableInitCommandOptionHandler
extends InitCommand.InitOptionHandler {
private static class TestableInitCommandOptionHandler extends InitCommand.InitOptionHandler {
private boolean disableProjectGeneration;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,8 +44,7 @@ public class InitializrServiceMetadataTests {
assertThat(metadata.getDefaults().get("javaVersion")).isEqualTo("1.7");
assertThat(metadata.getDefaults().get("groupId")).isEqualTo("org.test");
assertThat(metadata.getDefaults().get("name")).isEqualTo("demo");
assertThat(metadata.getDefaults().get("description"))
.isEqualTo("Demo project for Spring Boot");
assertThat(metadata.getDefaults().get("description")).isEqualTo("Demo project for Spring Boot");
assertThat(metadata.getDefaults().get("packaging")).isEqualTo("jar");
assertThat(metadata.getDefaults().get("language")).isEqualTo("java");
assertThat(metadata.getDefaults().get("artifactId")).isEqualTo("demo");
@@ -63,8 +62,7 @@ public class InitializrServiceMetadataTests {
// Security description
assertThat(metadata.getDependency("aop").getName()).isEqualTo("AOP");
assertThat(metadata.getDependency("security").getName()).isEqualTo("Security");
assertThat(metadata.getDependency("security").getDescription())
.isEqualTo("Security description");
assertThat(metadata.getDependency("security").getDescription()).isEqualTo("Security description");
assertThat(metadata.getDependency("jdbc").getName()).isEqualTo("JDBC");
assertThat(metadata.getDependency("data-jpa").getName()).isEqualTo("JPA");
assertThat(metadata.getDependency("data-mongodb").getName()).isEqualTo("MongoDB");
@@ -79,8 +77,7 @@ public class InitializrServiceMetadataTests {
assertThat(projectType.getTags().get("format")).isEqualTo("project");
}
private static InitializrServiceMetadata createInstance(String version)
throws JSONException {
private static InitializrServiceMetadata createInstance(String version) throws JSONException {
try {
return new InitializrServiceMetadata(readJson(version));
}
@@ -90,12 +87,10 @@ public class InitializrServiceMetadataTests {
}
private static JSONObject readJson(String version) throws IOException, JSONException {
Resource resource = new ClassPathResource(
"metadata/service-metadata-" + version + ".json");
Resource resource = new ClassPathResource("metadata/service-metadata-" + version + ".json");
InputStream stream = resource.getInputStream();
try {
return new JSONObject(
StreamUtils.copyToString(stream, Charset.forName("UTF-8")));
return new JSONObject(StreamUtils.copyToString(stream, Charset.forName("UTF-8")));
}
finally {
stream.close();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -49,19 +49,18 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests {
@Test
public void generateSimpleProject() throws Exception {
ProjectGenerationRequest request = new ProjectGenerationRequest();
MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest(
"application/xml", "foo.zip");
MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest("application/xml",
"foo.zip");
ProjectGenerationResponse entity = generateProject(request, mockHttpRequest);
assertProjectEntity(entity, mockHttpRequest.contentType,
mockHttpRequest.fileName);
assertProjectEntity(entity, mockHttpRequest.contentType, mockHttpRequest.fileName);
}
@Test
public void generateProjectCustomTargetFilename() throws Exception {
ProjectGenerationRequest request = new ProjectGenerationRequest();
request.setOutput("bar.zip");
MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest(
"application/xml", null);
MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest("application/xml",
null);
ProjectGenerationResponse entity = generateProject(request, mockHttpRequest);
assertProjectEntity(entity, mockHttpRequest.contentType, null);
}
@@ -69,8 +68,8 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests {
@Test
public void generateProjectNoDefaultFileName() throws Exception {
ProjectGenerationRequest request = new ProjectGenerationRequest();
MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest(
"application/xml", null);
MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest("application/xml",
null);
ProjectGenerationResponse entity = generateProject(request, mockHttpRequest);
assertProjectEntity(entity, mockHttpRequest.contentType, null);
}
@@ -144,13 +143,11 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests {
MockHttpProjectGenerationRequest mockRequest) throws Exception {
mockSuccessfulProjectGeneration(mockRequest);
ProjectGenerationResponse entity = this.invoker.generate(request);
assertThat(entity.getContent()).as("wrong body content")
.isEqualTo(mockRequest.content);
assertThat(entity.getContent()).as("wrong body content").isEqualTo(mockRequest.content);
return entity;
}
private static void assertProjectEntity(ProjectGenerationResponse entity,
String mimeType, String fileName) {
private static void assertProjectEntity(ProjectGenerationResponse entity, String mimeType, String fileName) {
if (mimeType == null) {
assertThat(entity.getContentType()).isNull();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -43,8 +43,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class ProjectGenerationRequestTests {
public static final Map<String, String> EMPTY_TAGS = Collections
.<String, String>emptyMap();
public static final Map<String, String> EMPTY_TAGS = Collections.<String, String>emptyMap();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@@ -53,8 +52,7 @@ public class ProjectGenerationRequestTests {
@Test
public void defaultSettings() {
assertThat(this.request.generateUrl(createDefaultMetadata()))
.isEqualTo(createDefaultUrl("?type=test-type"));
assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo(createDefaultUrl("?type=test-type"));
}
@Test
@@ -62,8 +60,8 @@ public class ProjectGenerationRequestTests {
String customServerUrl = "http://foo:8080/initializr";
this.request.setServiceUrl(customServerUrl);
this.request.getDependencies().add("security");
assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo(new URI(
customServerUrl + "/starter.zip?dependencies=security&type=test-type"));
assertThat(this.request.generateUrl(createDefaultMetadata()))
.isEqualTo(new URI(customServerUrl + "/starter.zip?dependencies=security&type=test-type"));
}
@Test
@@ -84,8 +82,8 @@ public class ProjectGenerationRequestTests {
public void multipleDependencies() {
this.request.getDependencies().add("web");
this.request.getDependencies().add("data-jpa");
assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo(
createDefaultUrl("?dependencies=web%2Cdata-jpa&type=test-type"));
assertThat(this.request.generateUrl(createDefaultMetadata()))
.isEqualTo(createDefaultUrl("?dependencies=web%2Cdata-jpa&type=test-type"));
}
@Test
@@ -104,14 +102,12 @@ public class ProjectGenerationRequestTests {
@Test
public void customType() throws URISyntaxException {
ProjectType projectType = new ProjectType("custom", "Custom Type", "/foo", true,
EMPTY_TAGS);
ProjectType projectType = new ProjectType("custom", "Custom Type", "/foo", true, EMPTY_TAGS);
InitializrServiceMetadata metadata = new InitializrServiceMetadata(projectType);
this.request.setType("custom");
this.request.getDependencies().add("data-rest");
assertThat(this.request.generateUrl(metadata))
.isEqualTo(new URI(ProjectGenerationRequest.DEFAULT_SERVICE_URL
+ "/foo?dependencies=data-rest&type=custom"));
assertThat(this.request.generateUrl(metadata)).isEqualTo(
new URI(ProjectGenerationRequest.DEFAULT_SERVICE_URL + "/foo?dependencies=data-rest&type=custom"));
}
@Test
@@ -135,9 +131,8 @@ public class ProjectGenerationRequestTests {
this.request.setVersion("1.0.1-SNAPSHOT");
this.request.setDescription("Spring Boot Test");
assertThat(this.request.generateUrl(createDefaultMetadata()))
.isEqualTo(createDefaultUrl(
"?groupId=org.acme&artifactId=sample&version=1.0.1-SNAPSHOT"
+ "&description=Spring+Boot+Test&type=test-type"));
.isEqualTo(createDefaultUrl("?groupId=org.acme&artifactId=sample&version=1.0.1-SNAPSHOT"
+ "&description=Spring+Boot+Test&type=test-type"));
}
@Test
@@ -157,8 +152,8 @@ public class ProjectGenerationRequestTests {
@Test
public void outputArchiveWithDotsCustomizeArtifactId() {
this.request.setOutput("my.nice.project.zip");
assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo(
createDefaultUrl("?artifactId=my.nice.project&type=test-type"));
assertThat(this.request.generateUrl(createDefaultMetadata()))
.isEqualTo(createDefaultUrl("?artifactId=my.nice.project&type=test-type"));
}
@Test
@@ -192,8 +187,7 @@ public class ProjectGenerationRequestTests {
public void buildOneMatch() throws Exception {
InitializrServiceMetadata metadata = readMetadata();
setBuildAndFormat("gradle", null);
assertThat(this.request.generateUrl(metadata))
.isEqualTo(createDefaultUrl("?type=gradle-project"));
assertThat(this.request.generateUrl(metadata)).isEqualTo(createDefaultUrl("?type=gradle-project"));
}
@Test
@@ -201,8 +195,7 @@ public class ProjectGenerationRequestTests {
InitializrServiceMetadata metadata = readMetadata();
setBuildAndFormat("gradle", "project");
this.request.setType("maven-build");
assertThat(this.request.generateUrl(metadata))
.isEqualTo(createUrl("/pom.xml?type=maven-build"));
assertThat(this.request.generateUrl(metadata)).isEqualTo(createUrl("/pom.xml?type=maven-build"));
}
@Test
@@ -239,8 +232,7 @@ public class ProjectGenerationRequestTests {
}
private static InitializrServiceMetadata createDefaultMetadata() {
ProjectType projectType = new ProjectType("test-type", "The test type",
"/starter.zip", true, EMPTY_TAGS);
ProjectType projectType = new ProjectType("test-type", "The test type", "/starter.zip", true, EMPTY_TAGS);
return new InitializrServiceMetadata(projectType);
}
@@ -248,13 +240,10 @@ public class ProjectGenerationRequestTests {
return readMetadata("2.0.0");
}
private static InitializrServiceMetadata readMetadata(String version)
throws JSONException {
private static InitializrServiceMetadata readMetadata(String version) throws JSONException {
try {
Resource resource = new ClassPathResource(
"metadata/service-metadata-" + version + ".json");
String content = StreamUtils.copyToString(resource.getInputStream(),
Charset.forName("UTF-8"));
Resource resource = new ClassPathResource("metadata/service-metadata-" + version + ".json");
String content = StreamUtils.copyToString(resource.getInputStream(), Charset.forName("UTF-8"));
JSONObject json = new JSONObject(content);
return new InitializrServiceMetadata(json);
}

Some files were not shown because too many files have changed in this diff Show More