@@ -182,7 +181,12 @@
*/
public class TestProjectContext {
- private static final Path DEFAULT_PROJECT_ROOT = Path.of(".").resolve("target").resolve("dummy-test-path").normalize().toAbsolutePath();
+ private static final Path DEFAULT_PROJECT_ROOT = Path
+ .of(".")
+ .resolve("target")
+ .resolve("dummy-test-path")
+ .normalize()
+ .toAbsolutePath();
private static final String DEFAULT_PACKAGE_NAME = "not.found";
@@ -195,9 +199,17 @@ public static Builder buildProjectContext() {
return new Builder(DEFAULT_PROJECT_ROOT);
}
+ /**
+ *
+ */
+ public static Builder buildProjectContext(ConfigurableListableBeanFactory beanFactory) {
+ return new Builder(DEFAULT_PROJECT_ROOT, beanFactory);
+ }
+
/**
* Build {@code ProjectContext} with default project root of absolute path of './dummy-test-path'
*
+ *
* @param eventPublisher the eventPublisher to use
*/
public static Builder buildProjectContext(ApplicationEventPublisher eventPublisher) {
@@ -207,6 +219,7 @@ public static Builder buildProjectContext(ApplicationEventPublisher eventPublish
/**
* Build {@code ProjectContext} with default project root of absolute path of './dummy-test-path'
*
+ *
* @param eventPublisher the eventPublisher to use
*/
public static Builder buildProjectContext(ApplicationEventPublisher eventPublisher, RewriteJavaParser rewriteJavaParser) {
@@ -220,7 +233,9 @@ public static Path getDefaultProjectRoot() {
return DEFAULT_PROJECT_ROOT;
}
- public static String getDefaultPackageName() { return DEFAULT_PACKAGE_NAME; }
+ public static String getDefaultPackageName() {
+ return DEFAULT_PACKAGE_NAME;
+ }
public static ProjectContext buildFromDir(Path of) {
final Path absoluteProjectRoot = of.toAbsolutePath().normalize();
@@ -246,30 +261,27 @@ public static ProjectContext buildFromDir(Path of) {
}
public static class Builder {
+ @Deprecated
+ private RewriteJavaParser javaParser;
+ private ConfigurableListableBeanFactory beanFactory;
private Path projectRoot;
private List resourceWrapperList = new ArrayList<>();
private List dependencies = new ArrayList<>();
private Map resourcesWithRelativePaths = new LinkedHashMap<>();
- private ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
+ private ApplicationEventPublisher eventPublisher;
private ProjectResourceWrapperRegistry resourceWrapperRegistry;
private OpenRewriteMavenBuildFile mockedBuildFile;
private DependencyHelper dependencyHelper = new DependencyHelper();
private SbmApplicationProperties sbmApplicationProperties = new SbmApplicationProperties();
-
+ private ExecutionContext executionContext;
private Optional springVersion = Optional.empty();
- private JavaParser javaParser;
- private RewriteMavenParser mavenParser = new RewriteMavenParser(new MavenSettingsInitializer());;
-
public Builder(Path projectRoot) {
- this.projectRoot = projectRoot;
- sbmApplicationProperties.setDefaultBasePackage(DEFAULT_PACKAGE_NAME);
- sbmApplicationProperties.setJavaParserLoggingCompilationWarningsAndErrors(true);
- this.javaParser = new RewriteJavaParser(sbmApplicationProperties);
+ this(projectRoot, (ConfigurableListableBeanFactory) null);
}
public Builder(Path projectRoot, ApplicationEventPublisher eventPublisher) {
- this(projectRoot);
+ this(projectRoot, (ConfigurableListableBeanFactory) null);
this.eventPublisher = eventPublisher;
}
@@ -278,6 +290,18 @@ public Builder(Path defaultProjectRoot, ApplicationEventPublisher eventPublisher
this.javaParser = rewriteJavaParser;
}
+ public Builder(Path defaultProjectRoot, ConfigurableListableBeanFactory beanFactory) {
+ this.projectRoot = defaultProjectRoot;
+ sbmApplicationProperties.setDefaultBasePackage(DEFAULT_PACKAGE_NAME);
+ sbmApplicationProperties.setJavaParserLoggingCompilationWarningsAndErrors(true);
+ this.beanFactory = beanFactory;
+ }
+
+ public Builder withExecutionContext(ExecutionContext executionContext) {
+ this.executionContext = executionContext;
+ return this;
+ }
+
public Builder withProjectRoot(Path projectRoot) {
this.projectRoot = projectRoot.toAbsolutePath().normalize();
return this;
@@ -295,8 +319,8 @@ public Builder withApplicationProperties(SbmApplicationProperties sbmApplication
* @param content of the resource
*/
public Builder addProjectResource(Path sourcePath, String content) {
- if (sourcePath.isAbsolute())
- throw new IllegalArgumentException("Invalid sourcePath given, sourcePath must be given relative from project root.");
+ if (sourcePath.isAbsolute()) throw new IllegalArgumentException(
+ "Invalid sourcePath given, sourcePath must be given relative from project root.");
this.resourcesWithRelativePaths.put(sourcePath.normalize(), content);
return this;
}
@@ -421,7 +445,7 @@ public Builder withMavenBuildFileSource(Path path, String pomSource) {
public Builder withMavenBuildFileSource(String sourceDir, String pomSource) {
Path sourcePath = Path.of(sourceDir);
- if(!sourceDir.endsWith("pom.xml")) {
+ if (!sourceDir.endsWith("pom.xml")) {
sourcePath = sourcePath.resolve("pom.xml");
}
this.addProjectResource(sourcePath, pomSource);
@@ -441,14 +465,7 @@ public Builder withMockedBuildFile(OpenRewriteMavenBuildFile mockedBuildFile) {
public Builder withDummyRootBuildFile() {
if (containsAnyPomXml() || !dependencies.isEmpty())
throw new IllegalArgumentException("ProjectContext already contains pom.xml files.");
- String xml = "\n" +
- "\n" +
- " 4.0.0\n" +
- " com.example\n" +
- " dummy-root\n" +
- " 0.1.0-SNAPSHOT\n" +
- " jar\n" +
- "\n";
+ String xml = "\n" + "\n" + " 4.0.0\n" + " com.example\n" + " dummy-root\n" + " 0.1.0-SNAPSHOT\n" + " jar\n" + "\n";
resourcesWithRelativePaths.put(Path.of("pom.xml"), xml);
return this;
}
@@ -461,9 +478,9 @@ public ProjectContext serializeProjectContext(Path targetDir) {
ProjectContext projectContext = build();
- ProjectContextSerializer serializer = new ProjectContextSerializer(new ProjectResourceSetSerializer(new ProjectResourceSerializer()));
- projectContext.getProjectResources().stream()
- .forEach(r -> r.markChanged());
+ ProjectContextSerializer serializer = new ProjectContextSerializer(
+ new ProjectResourceSetSerializer(new ProjectResourceSerializer()));
+ projectContext.getProjectResources().stream().forEach(r -> r.markChanged());
serializer.writeChanges(projectContext);
return projectContext;
}
@@ -474,7 +491,7 @@ public ProjectContext serializeProjectContext(Path targetDir) {
public ProjectContext build() {
verifyValidBuildFileSetup();
- if(!containsAnyPomXml()) {
+ if (!containsAnyPomXml()) {
String xml = """
@@ -498,32 +515,41 @@ public ProjectContext build() {
// create resource map with fully qualified paths
Map resourcesWithAbsolutePaths = new LinkedHashMap<>();
- resourcesWithRelativePaths.entrySet().stream()
- .forEach(e -> {
- Path absolutePath = projectRoot.resolve(e.getKey()).normalize().toAbsolutePath();
- resourcesWithAbsolutePaths.put(absolutePath, e.getValue());
- });
+ resourcesWithRelativePaths.entrySet().stream().forEach(e -> {
+ Path absolutePath = projectRoot.resolve(e.getKey()).normalize().toAbsolutePath();
+ resourcesWithAbsolutePaths.put(absolutePath, e.getValue());
+ });
// create list of dummy resources
List scannedResources = mapToResources(resourcesWithAbsolutePaths);
// create beans
- ProjectResourceSetHolder projectResourceSetHolder = new ProjectResourceSetHolder();
- JavaRefactoringFactory javaRefactoringFactory = new JavaRefactoringFactoryImpl(projectResourceSetHolder);
-
- // create ProjectResourceWrapperRegistry and register Java and Maven resource wrapper
- MavenBuildFileRefactoringFactory mavenBuildFileRefactoringFactory = new MavenBuildFileRefactoringFactory(projectResourceSetHolder, mavenParser);
- BuildFileResourceWrapper buildFileResourceWrapper = new BuildFileResourceWrapper(eventPublisher,
- mavenBuildFileRefactoringFactory);
- resourceWrapperList.add(buildFileResourceWrapper);
- JavaSourceProjectResourceWrapper javaSourceProjectResourceWrapper = new JavaSourceProjectResourceWrapper(javaRefactoringFactory, javaParser);
- resourceWrapperList.add(javaSourceProjectResourceWrapper);
- orderByOrderAnnotationValue(resourceWrapperList);
- resourceWrapperRegistry = new ProjectResourceWrapperRegistry(resourceWrapperList);
+// ProjectResourceSetHolder projectResourceSetHolder = new ProjectResourceSetHolder();
+// JavaRefactoringFactory javaRefactoringFactory = new JavaRefactoringFactoryImpl(projectResourceSetHolder, executionContext);
+//
+// // create ProjectResourceWrapperRegistry and register Java and Maven resource wrapper
+// MavenBuildFileRefactoringFactory mavenBuildFileRefactoringFactory = new MavenBuildFileRefactoringFactory(projectResourceSetHolder, mavenParser);
+// BuildFileResourceWrapper buildFileResourceWrapper = new BuildFileResourceWrapper(eventPublisher,
+// mavenBuildFileRefactoringFactory,
+// executionContext);
+// resourceWrapperList.add(buildFileResourceWrapper);
+// JavaSourceProjectResourceWrapper javaSourceProjectResourceWrapper = new JavaSourceProjectResourceWrapper(
+// javaRefactoringFactory, javaParser, executionContext);
+// resourceWrapperList.add(javaSourceProjectResourceWrapper);
+// orderByOrderAnnotationValue(resourceWrapperList);
+// resourceWrapperRegistry = new ProjectResourceWrapperRegistry(resourceWrapperList);
// create ProjectContextInitializer
- ProjectContextFactory projectContextFactory = new ProjectContextFactory(resourceWrapperRegistry, projectResourceSetHolder, javaRefactoringFactory, new BasePackageCalculator(sbmApplicationProperties), javaParser);
- ProjectContextInitializer projectContextInitializer = createProjectContextInitializer(projectContextFactory);
+ /*
+ ProjectContextFactory projectContextFactory = new ProjectContextFactory(resourceWrapperRegistry,
+ projectResourceSetHolder,
+ javaRefactoringFactory,
+ new BasePackageCalculator(
+ sbmApplicationProperties),
+ javaParser,
+ executionContext);
+ */
+ ProjectContextInitializer projectContextInitializer = createProjectContextInitializer();
// create ProjectContext
ProjectContext projectContext = projectContextInitializer.initProjectContext(projectRoot, scannedResources);
@@ -552,39 +578,34 @@ private Integer getOrder(ProjectResourceWrapper l1) {
}
@NotNull
- private ProjectContextInitializer createProjectContextInitializer(ProjectContextFactory projectContextFactory) {
- // FIXME: #7 remove
-// RewriteMavenParserFactory rewriteMavenParserFactory = new RewriteMavenParserFactory(new MavenPomCacheProvider(), eventPublisher, new ResourceParser(eventPublisher));
-
-
- ResourceParser resourceParser = new ResourceParser(
- new RewriteJsonParser(),
- new RewriteXmlParser(),
- new RewriteYamlParser(),
- new RewritePropertiesParser(),
- new RewritePlainTextParser(),
- new ResourceParser.ResourceFilter(),
- eventPublisher);
-
- MavenArtifactDownloader artifactDownloader = new RewriteMavenArtifactDownloader();
-
- JavaProvenanceMarkerFactory javaProvenanceMarkerFactory = new JavaProvenanceMarkerFactory();
- MavenProjectParser mavenProjectParser = new MavenProjectParser(
- resourceParser,
- mavenParser,
- artifactDownloader,
- eventPublisher,
- javaProvenanceMarkerFactory,
- javaParser,
- new MavenConfigHandler());
-
- GitSupport gitSupport = mock(GitSupport.class);
- when(gitSupport.repoExists(projectRoot.toFile())).thenReturn(true);
- when(gitSupport.getLatestCommit(projectRoot.toFile())).thenReturn(Optional.empty());
-
- RewriteSourceFileWrapper wrapper = new RewriteSourceFileWrapper();
- ProjectContextInitializer projectContextInitializer = new ProjectContextInitializer(projectContextFactory, mavenProjectParser, gitSupport, wrapper);
- return projectContextInitializer;
+ private ProjectContextInitializer createProjectContextInitializer() {
+ AtomicReference projectContextInitializerRef = new AtomicReference<>();
+ if(beanFactory != null) {
+ ProjectContextInitializer bean = beanFactory.getBean(ProjectContextInitializer.class);
+ projectContextInitializerRef.set(bean);
+ executionContext = beanFactory.getBean(ExecutionContext.class);
+ } else {
+ Map, Object> replacedBean = new HashMap<>();
+ if(sbmApplicationProperties != null) {
+ replacedBean.put(SbmApplicationProperties.class, sbmApplicationProperties);
+ }
+
+ if(eventPublisher != null) {
+ replacedBean.put(ApplicationEventPublisher.class, eventPublisher);
+ }
+
+ SpringBeanProvider.run(
+ ctx -> {
+ beanFactory = ctx.getBeanFactory();
+ projectContextInitializerRef.set(ctx.getBean(ProjectContextInitializer.class));
+ executionContext = ctx.getBean(ExecutionContext.class);
+ },
+ replacedBean,
+ SpringBeanProvider.ComponentScanConfiguration.class,
+ Configuration.class,
+ CustomValidatorBean.class);
+ }
+ return projectContextInitializerRef.get();
}
private void verifyValidBuildFileSetup() {
@@ -594,16 +615,21 @@ private void verifyValidBuildFileSetup() {
boolean containsAnyPomXml = containsAnyPomXml();
if (containsAnyPomXml && isClasspathGiven) {
- throw new IllegalArgumentException("Found classpath entries and pom.xml in resources. When classpath is provided the root pom gets generated");
+ throw new IllegalArgumentException(
+ "Found classpath entries and pom.xml in resources. When classpath is provided the root pom gets generated");
} else if (containsAnyPomXml && hasSpringBootParent) {
- throw new IllegalArgumentException("Found spring boot version for parent pom and root pom.xml in resources. When spring boot version is provided the root pom gets generated");
+ throw new IllegalArgumentException(
+ "Found spring boot version for parent pom and root pom.xml in resources. When spring boot version is provided the root pom gets generated");
} else if (containsAnyPomXml && isMockedBuildFileGiven) {
- throw new IllegalArgumentException("Found mocked BuildFile and root pom.xml in resources. When mocked BuildFile is provided no other pom.xml must exist");
+ throw new IllegalArgumentException(
+ "Found mocked BuildFile and root pom.xml in resources. When mocked BuildFile is provided no other pom.xml must exist");
}
if (mockedBuildFile != null && isClasspathGiven) {
- throw new IllegalArgumentException("Found mocked BuildFile and classpath entries. When mocked BuildFile is provided no other pom.xml must exist");
- } else if(mockedBuildFile != null && hasSpringBootParent) {
- throw new IllegalArgumentException("Found mocked BuildFile and Spring Boot version. When mocked BuildFile is provided no other pom.xml, parent or dependencies must exist");
+ throw new IllegalArgumentException(
+ "Found mocked BuildFile and classpath entries. When mocked BuildFile is provided no other pom.xml must exist");
+ } else if (mockedBuildFile != null && hasSpringBootParent) {
+ throw new IllegalArgumentException(
+ "Found mocked BuildFile and Spring Boot version. When mocked BuildFile is provided no other pom.xml, parent or dependencies must exist");
}
}
@@ -612,26 +638,43 @@ private boolean containsAnyPomXml() {
}
private List mapToResources(Map resources) {
- return resources.entrySet().stream()
+ return resources
+ .entrySet()
+ .stream()
.map(e -> new TestDummyResource(e.getKey(), e.getValue()))
.collect(Collectors.toList());
}
private Parser.Input createParserInput(Path path, String value) {
- return new Parser.Input(path, null, () -> new ByteArrayInputStream(value.getBytes(StandardCharsets.UTF_8)), true);
+ return new Parser.Input(path, null, () -> new ByteArrayInputStream(value.getBytes(StandardCharsets.UTF_8)),
+ true);
}
@NotNull
private String getDependenciesSection() {
StringBuilder dependenciesSection = new StringBuilder();
- if(!dependencies.isEmpty()) {
+ if (!dependencies.isEmpty()) {
dependenciesSection.append(" ").append("").append("\n");
dependencyHelper.mapCoordinatesToDependencies(dependencies).stream().forEach(dependency -> {
dependenciesSection.append(" ").append(" ").append("").append("\n");
- dependenciesSection.append(" ").append(" ").append(" ").append("").append(dependency.getGroupId()).append("").append("\n");
- dependenciesSection.append(" ").append(" ").append(" ").append("").append(dependency.getArtifactId()).append("").append("\n");
- if(dependency.getVersion() != null) {
+ dependenciesSection
+ .append(" ")
+ .append(" ")
+ .append(" ")
+ .append("")
+ .append(dependency.getGroupId())
+ .append("")
+ .append("\n");
+ dependenciesSection
+ .append(" ")
+ .append(" ")
+ .append(" ")
+ .append("")
+ .append(dependency.getArtifactId())
+ .append("")
+ .append("\n");
+ if (dependency.getVersion() != null) {
dependenciesSection
.append(" ")
.append(" ")
@@ -671,6 +714,14 @@ public Builder withSpringBootParentOf(String springVersion) {
this.springVersion = Optional.of(springVersion);
return this;
}
+
+ public TestProjectContextInfo buildProjectContextInfo() {
+ ProjectContext build = this.build();
+ if(!AutowireCapableBeanFactory.class.isInstance(beanFactory)){
+ throw new IllegalStateException("Provided beanFactory must be of type %s".formatted(AutowireCapableBeanFactory.class.getName()));
+ }
+ return new TestProjectContextInfo(build, executionContext, (AutowireCapableBeanFactory)beanFactory);
+ }
}
}
diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/test/ActionTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/test/ActionTest.java
new file mode 100644
index 000000000..c2432cd52
--- /dev/null
+++ b/components/sbm-core/src/test/java/org/springframework/sbm/test/ActionTest.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2021 - 2022 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.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.springframework.sbm.test;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.sbm.build.migration.actions.RemoveManagedDependencies;
+import org.springframework.sbm.engine.context.ProjectContext;
+import org.springframework.sbm.engine.recipe.Action;
+import org.springframework.sbm.project.resource.TestProjectContext;
+
+import java.util.function.Consumer;
+
+/**
+ * Test helper to test {@link Action} implementations that require injected Spring beans like e.g. {@link org.openrewrite.ExecutionContext}.
+ *
+ * Spring managed beans created during {@link ProjectContext} initialization will be injected into fields in {@link Action}s
+ * when annotated with
+ *
+ * [source,java]
+ * --
+ * public class MyAction {
+ * {@literal @}Autowired
+ * {@literal @}JsonIgnore
+ * private ExecutionContext executionContext;
+ * }
+ * --
+ *
+ * @author Fabian Krüger
+ */
+public class ActionTest {
+ private TestProjectContext.Builder projectContextBuilder;
+ private Action actionUnderTest;
+
+ public static ActionTest withProjectContext(TestProjectContext.Builder projectContextBuilder) {
+ ActionTest actionTest = new ActionTest(projectContextBuilder);
+ return actionTest;
+ }
+
+ /**
+ * @param projectContextBuilder Builder for the {@link ProjectContext} that will be provided to the Action under test
+ */
+ private ActionTest(TestProjectContext.Builder projectContextBuilder) {
+ this.projectContextBuilder = projectContextBuilder;
+ }
+
+ /**
+ * Spring beans will be injected into Members annotated with @{@link Autowired} and @{@link JsonIgnore}.
+ *
+ * @param actionUnderTest the tested {@link Action} instance.
+ */
+ public ActionTest actionUnderTest(Action actionUnderTest) {
+ this.actionUnderTest = actionUnderTest;
+ return this;
+ }
+
+ /**
+ * @param projectContextConsumer a {@link Consumer} taking the resulting {@link ProjectContext} to verify migrations.
+ */
+ public void verify(Consumer projectContextConsumer) {
+ TestProjectContextInfo projectContext = projectContextBuilder.buildProjectContextInfo();
+ projectContext.beanFactory().autowireBean(actionUnderTest);
+ actionUnderTest.apply(projectContext.projectContext());
+ projectContextConsumer.accept(projectContext.projectContext());
+ }
+}
diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/test/SpringBeanProvider.java b/components/sbm-core/src/test/java/org/springframework/sbm/test/SpringBeanProvider.java
new file mode 100644
index 000000000..b8dc7359e
--- /dev/null
+++ b/components/sbm-core/src/test/java/org/springframework/sbm/test/SpringBeanProvider.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright 2021 - 2022 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.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.springframework.sbm.test;
+
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.config.BeanPostProcessor;
+import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
+import org.springframework.boot.context.annotation.Configurations;
+import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
+import org.springframework.boot.test.context.runner.ApplicationContextRunner;
+import org.springframework.boot.test.context.runner.ContextConsumer;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.sbm.archfitfun.ExecutionScopeArchFitTestContext;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Optional;
+
+public class SpringBeanProvider {
+
+ @Configuration
+ @ComponentScan(value = "org.springframework.sbm", excludeFilters = @ComponentScan.Filter(classes = TestConfiguration.class))
+ public static class ComponentScanConfiguration { }
+
+ public static void run(ContextConsumer testcode, Class>... springBeans) {
+ ApplicationContextRunner contextRunner = new ApplicationContextRunner();
+ for (Class> springBean : springBeans) {
+ if(springBean.isAssignableFrom(Configurations.class)) {
+ Configurations c = Configurations.class.cast(springBean);
+ contextRunner.withConfiguration(c);
+ } else {
+ contextRunner = contextRunner.withBean(springBean);
+ }
+ }
+ contextRunner.run(testcode);
+ }
+
+ public static void run(ContextConsumer testcode, Map, Object> replacedBeans, Class>... springBeans) {
+ AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
+ ConfigurableListableBeanFactory beanFactory = annotationConfigApplicationContext.getBeanFactory();
+ beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
+ @Override
+ public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
+ Class> beanClass = bean.getClass();
+ Optional
\ No newline at end of file
diff --git a/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/properties/SpringBootApplicationPropertiesRegistrar.java b/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/properties/SpringBootApplicationPropertiesRegistrar.java
index 45fdf3879..39700cd65 100644
--- a/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/properties/SpringBootApplicationPropertiesRegistrar.java
+++ b/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/properties/SpringBootApplicationPropertiesRegistrar.java
@@ -16,6 +16,7 @@
package org.springframework.sbm.boot.properties;
import lombok.RequiredArgsConstructor;
+import org.openrewrite.ExecutionContext;
import org.openrewrite.SourceFile;
import org.openrewrite.properties.tree.Properties;
import org.springframework.sbm.boot.properties.api.SpringBootApplicationProperties;
@@ -37,6 +38,7 @@ public class SpringBootApplicationPropertiesRegistrar implements ProjectResource
public static final String PATTERN1 = "/**/src/main/resources/config/application*.properties";
private PathMatcher pathMatcher = new OsAgnosticPathMatcher();
private final SpringApplicationPropertiesPathMatcher springApplicationPropertiesPathMatcher;
+ private final ExecutionContext executionContext;
@Override
public boolean shouldHandle(RewriteSourceFileHolder extends SourceFile> rewriteSourceFileHolder) {
@@ -49,7 +51,7 @@ public boolean shouldHandle(RewriteSourceFileHolder extends SourceFile> rewrit
public SpringBootApplicationProperties wrapRewriteSourceFileHolder(RewriteSourceFileHolder extends SourceFile> rewriteSourceFileHolder) {
// TODO: How to pass current executionContext ?
Properties.File properties = Properties.File.class.cast(rewriteSourceFileHolder.getSourceFile());
- SpringBootApplicationProperties springBootApplicationProperties = new SpringBootApplicationProperties(rewriteSourceFileHolder.getAbsoluteProjectDir(), properties);
+ SpringBootApplicationProperties springBootApplicationProperties = new SpringBootApplicationProperties(rewriteSourceFileHolder.getAbsoluteProjectDir(), properties, executionContext);
SpringProfile springProfile = extractProfileFromFilename(springBootApplicationProperties.getAbsolutePath());
springBootApplicationProperties.setSpringProfile(springProfile);
return springBootApplicationProperties;
diff --git a/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/properties/actions/AddSpringBootApplicationPropertiesAction.java b/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/properties/actions/AddSpringBootApplicationPropertiesAction.java
index e4013caa3..940ef9b94 100644
--- a/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/properties/actions/AddSpringBootApplicationPropertiesAction.java
+++ b/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/properties/actions/AddSpringBootApplicationPropertiesAction.java
@@ -15,12 +15,15 @@
*/
package org.springframework.sbm.boot.properties.actions;
+import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
+import org.openrewrite.ExecutionContext;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.sbm.boot.properties.api.SpringBootApplicationProperties;
import org.springframework.sbm.boot.properties.search.SpringBootApplicationPropertiesResourceListFilter;
import org.springframework.sbm.build.api.Module;
@@ -36,6 +39,13 @@
public class AddSpringBootApplicationPropertiesAction extends AbstractAction {
public static final Path APPLICATION_PROPERTIES_PATH = Path.of("src/main/resources/application.properties");
+ @Autowired
+ @JsonIgnore
+ private ExecutionContext executionContext;
+
+ public AddSpringBootApplicationPropertiesAction(ExecutionContext executionContext) {
+ this.executionContext = executionContext;
+ }
@Override
public void apply(ProjectContext context) {
@@ -53,7 +63,8 @@ public void apply(Module module) {
SpringBootApplicationProperties springBootApplicationProperties = SpringBootApplicationProperties
.newApplicationProperties(
module.getProjectRootDirectory(),
- module.getModulePath().resolve(APPLICATION_PROPERTIES_PATH)
+ module.getModulePath().resolve(APPLICATION_PROPERTIES_PATH),
+ executionContext
);
module.getMainResourceSet().addResource(springBootApplicationProperties);
}
diff --git a/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/properties/api/SpringBootApplicationProperties.java b/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/properties/api/SpringBootApplicationProperties.java
index 6cc127473..614e1487d 100644
--- a/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/properties/api/SpringBootApplicationProperties.java
+++ b/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/properties/api/SpringBootApplicationProperties.java
@@ -15,13 +15,17 @@
*/
package org.springframework.sbm.boot.properties.api;
+import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
+import org.openrewrite.ExecutionContext;
import org.openrewrite.Tree;
import org.openrewrite.marker.Markers;
import org.openrewrite.properties.tree.Properties.File;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.sbm.openrewrite.RewriteExecutionContext;
import org.springframework.sbm.properties.api.PropertiesSource;
+import org.springframework.util.Assert;
import java.nio.file.Path;
import java.util.List;
@@ -32,24 +36,19 @@ public class SpringBootApplicationProperties extends PropertiesSource {
private SpringProfile springProfile = new SpringProfile("default");
- public SpringBootApplicationProperties(Path absoluteProjectDir, File sourceFile, RewriteExecutionContext executionContext) {
+ public SpringBootApplicationProperties(Path absoluteProjectDir, File sourceFile, ExecutionContext executionContext) {
super(absoluteProjectDir, executionContext, sourceFile);
+ Assert.notNull(executionContext, "ExecutionContext must not be null.");
}
-
- public SpringBootApplicationProperties(Path absoluteProjectDir, File sourceFile) {
- // FIXME: why is context required here and how should it be retrieved ?
- this(absoluteProjectDir, sourceFile, new RewriteExecutionContext());
- }
-
- public static SpringBootApplicationProperties newApplicationProperties(Path absoluteProjectDir, Path sourcePath) {
-
+ public static SpringBootApplicationProperties newApplicationProperties(Path absoluteProjectDir, Path sourcePath, ExecutionContext executionContext) {
+ Assert.notNull(executionContext, "ExecutionContext must not be null.");
if(absoluteProjectDir.resolve(sourcePath).toFile().isDirectory()) {
throw new IllegalArgumentException(String.format("Given sourcePath '%s' is a directory. An existing file with Spring Boot application properties must be passed.", sourcePath));
}
File file = new File(Tree.randomId(), "", Markers.EMPTY, sourcePath, List.of(), "", null, false, null, null);
- SpringBootApplicationProperties springBootApplicationProperties = new SpringBootApplicationProperties(absoluteProjectDir, file);
+ SpringBootApplicationProperties springBootApplicationProperties = new SpringBootApplicationProperties(absoluteProjectDir, file, executionContext);
springBootApplicationProperties.markChanged();
return springBootApplicationProperties;
}
diff --git a/components/sbm-support-boot/src/test/java/org/springframework/sbm/architecture/FindIllegalExecutionContextCreationsTest.java b/components/sbm-support-boot/src/test/java/org/springframework/sbm/architecture/FindIllegalExecutionContextCreationsTest.java
new file mode 100644
index 000000000..877c4eda6
--- /dev/null
+++ b/components/sbm-support-boot/src/test/java/org/springframework/sbm/architecture/FindIllegalExecutionContextCreationsTest.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2021 - 2022 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.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.springframework.sbm.architecture;
+
+import com.tngtech.archunit.core.domain.AccessTarget;
+import com.tngtech.archunit.core.domain.JavaCall;
+import com.tngtech.archunit.core.domain.JavaClass;
+import com.tngtech.archunit.core.importer.ImportOption;
+import com.tngtech.archunit.junit.AnalyzeClasses;
+import com.tngtech.archunit.junit.ArchTest;
+import com.tngtech.archunit.junit.ArchTests;
+import com.tngtech.archunit.lang.ArchRule;
+import org.openrewrite.ExecutionContext;
+import org.springframework.sbm.openrewrite.RewriteExecutionContext;
+import org.springframework.sbm.scopeplayground.ScopeConfiguration;
+
+import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
+
+/**
+ * @author Fabian Krüger
+ */
+@AnalyzeClasses(packages = {"org.springframework.sbm", "org.openrewrite"}, importOptions = {ImportOption.DoNotIncludeTests.class, ImportOption.DoNotIncludeJars.class})
+public class FindIllegalExecutionContextCreationsTest {
+ @ArchTest
+ static final ArchTests executionContextMustNotBeCreatedWithNew = ArchTests.in(
+ ControlledInstantiationOfExecutionContextTest.class);
+}
\ No newline at end of file
diff --git a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/SpringBootApplicationPropertiesRegistrarTest.java b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/SpringBootApplicationPropertiesRegistrarTest.java
index eb6fb14a1..a4ee8a28b 100644
--- a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/SpringBootApplicationPropertiesRegistrarTest.java
+++ b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/SpringBootApplicationPropertiesRegistrarTest.java
@@ -16,6 +16,7 @@
package org.springframework.sbm.boot.properties;
import org.springframework.sbm.boot.properties.api.SpringBootApplicationProperties;
+import org.springframework.sbm.openrewrite.RewriteExecutionContext;
import org.springframework.sbm.project.resource.RewriteSourceFileHolder;
import org.springframework.sbm.properties.parser.RewritePropertiesParser;
import org.junit.jupiter.api.Test;
@@ -27,12 +28,11 @@
import static org.assertj.core.api.Assertions.assertThat;
-@ExtendWith(MockitoExtension.class)
class SpringBootApplicationPropertiesRegistrarTest {
private Path projectRoot = Path.of("./testdir").toAbsolutePath().normalize();
private String content = "foo=bar\na=b";
- private SpringBootApplicationPropertiesRegistrar sut = new SpringBootApplicationPropertiesRegistrar(new SpringApplicationPropertiesPathMatcher());
+ private SpringBootApplicationPropertiesRegistrar sut = new SpringBootApplicationPropertiesRegistrar(new SpringApplicationPropertiesPathMatcher(), new RewriteExecutionContext());
@Test
void shouldHandleReturnsTrueForDefault() {
diff --git a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/actions/AddSpringBootApplicationPropertiesActionTest.java b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/actions/AddSpringBootApplicationPropertiesActionTest.java
index af1c41073..4e161cc09 100644
--- a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/actions/AddSpringBootApplicationPropertiesActionTest.java
+++ b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/actions/AddSpringBootApplicationPropertiesActionTest.java
@@ -18,12 +18,14 @@
import org.springframework.sbm.boot.properties.api.SpringBootApplicationProperties;
import org.springframework.sbm.boot.properties.search.SpringBootApplicationPropertiesResourceListFilter;
import org.springframework.sbm.engine.context.ProjectContext;
+import org.springframework.sbm.openrewrite.RewriteExecutionContext;
import org.springframework.sbm.project.resource.TestProjectContext;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.sbm.test.ActionTest;
import java.nio.file.Path;
@@ -34,32 +36,35 @@ class AddSpringBootApplicationPropertiesActionTest {
@InjectMocks
private final AddSpringBootApplicationPropertiesAction sut = new AddSpringBootApplicationPropertiesAction();
- private ProjectContext projectContext;
+ private TestProjectContext.Builder projectContextBuilder;
@BeforeEach
void beforeEach() {
- projectContext = TestProjectContext.buildProjectContext()
- .withProjectRoot(Path.of("."))
- .build();
+ projectContextBuilder = TestProjectContext.buildProjectContext()
+ .withProjectRoot(Path.of("."));
}
@Test
void apply() {
- sut.apply(projectContext);
- SpringBootApplicationProperties springBootApplicationProperties = projectContext.search(new SpringBootApplicationPropertiesResourceListFilter()).get(0);
- assertThat(springBootApplicationProperties).isNotNull();
- assertThat(springBootApplicationProperties.hasChanges()).isTrue();
+ ActionTest.withProjectContext(projectContextBuilder)
+ .actionUnderTest(sut)
+ .verify(projectContext -> {
+ SpringBootApplicationProperties springBootApplicationProperties = projectContext.search(new SpringBootApplicationPropertiesResourceListFilter()).get(0);
+ assertThat(springBootApplicationProperties).isNotNull();
+ assertThat(springBootApplicationProperties.hasChanges()).isTrue();
+ });
}
@Test
void isApplicableShouldReturnTrueWhenNoApplicationPropertiesFileExist() {
- boolean isApplicable = sut.isApplicable(projectContext);
+ boolean isApplicable = sut.isApplicable(projectContextBuilder.build());
assertThat(isApplicable).isTrue();
}
@Test
void isApplicableShouldReturnFalseWhenApplicationPropertiesFileExist() {
- projectContext.getProjectResources().add(SpringBootApplicationProperties.newApplicationProperties(projectContext.getProjectRootDirectory(), Path.of("./src/main/resources/application.properties")));
+ ProjectContext projectContext = this.projectContextBuilder.build();
+ projectContext.getProjectResources().add(SpringBootApplicationProperties.newApplicationProperties(projectContext.getProjectRootDirectory(), Path.of("./src/main/resources/application.properties"), new RewriteExecutionContext()));
boolean isApplicable = sut.isApplicable(projectContext);
assertThat(isApplicable).isFalse();
}
diff --git a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/api/SpringBootApplicationPropertiesTest.java b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/api/SpringBootApplicationPropertiesTest.java
index 0763168d9..fab4a9cce 100644
--- a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/api/SpringBootApplicationPropertiesTest.java
+++ b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/api/SpringBootApplicationPropertiesTest.java
@@ -19,6 +19,7 @@
import org.junit.jupiter.api.Test;
import org.openrewrite.properties.PropertiesParser;
import org.openrewrite.properties.tree.Properties;
+import org.springframework.sbm.openrewrite.RewriteExecutionContext;
import java.nio.file.Path;
import java.util.List;
@@ -29,7 +30,7 @@ class SpringBootApplicationPropertiesTest {
@Test
void createNewProperties_Add_Print() {
- SpringBootApplicationProperties sut = SpringBootApplicationProperties.newApplicationProperties(Path.of("./projectDir").toAbsolutePath(), Path.of("./fake2.properties"));
+ SpringBootApplicationProperties sut = SpringBootApplicationProperties.newApplicationProperties(Path.of("./projectDir").toAbsolutePath(), Path.of("./fake2.properties"), new RewriteExecutionContext());
sut.setProperty("some", "property");
sut.setProperty("another", "foo");
assertThat(sut.print()).isEqualTo("some=property\n" +
@@ -41,7 +42,7 @@ void parseExistingPropertiesTest() {
List parse = new PropertiesParser().parse(
"foo=bar\n" +
"bob=bill");
- SpringBootApplicationProperties sut = new SpringBootApplicationProperties(Path.of("./projectDir").toAbsolutePath(), parse.get(0));
+ SpringBootApplicationProperties sut = new SpringBootApplicationProperties(Path.of("./projectDir").toAbsolutePath(), parse.get(0), new RewriteExecutionContext());
assertThat(sut.getProperty("foo").get()).isEqualTo("bar");
assertThat(sut.getProperty("bob").get()).isEqualTo("bill");
assertThat(sut.getProperty("jane")).isEmpty();
diff --git a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/finder/SpringBootDefaultPropertiesFinderTest.java b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/finder/SpringBootDefaultPropertiesFinderTest.java
index 4d7dde42c..33ed181ab 100644
--- a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/finder/SpringBootDefaultPropertiesFinderTest.java
+++ b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/finder/SpringBootDefaultPropertiesFinderTest.java
@@ -19,6 +19,7 @@
import org.springframework.sbm.boot.properties.SpringApplicationPropertiesPathMatcher;
import org.springframework.sbm.boot.properties.SpringBootApplicationPropertiesRegistrar;
import org.springframework.sbm.engine.context.ProjectContext;
+import org.springframework.sbm.openrewrite.RewriteExecutionContext;
import org.springframework.sbm.project.resource.TestProjectContext;
import java.nio.file.Path;
@@ -30,7 +31,7 @@ public class SpringBootDefaultPropertiesFinderTest {
@Test
public void givenAProjectWithDefaultSpringBootProperties_applyFinder_expectPropertyFile(){
ProjectContext projectContext = TestProjectContext.buildProjectContext()
- .addRegistrar(new SpringBootApplicationPropertiesRegistrar(new SpringApplicationPropertiesPathMatcher()))
+ .addRegistrar(new SpringBootApplicationPropertiesRegistrar(new SpringApplicationPropertiesPathMatcher(), new RewriteExecutionContext()))
.addProjectResource(Path.of("src","main", "resources", "application.properties"), "foo=bar")
.build();
diff --git a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/search/SpringBootApplicationPropertiesResourceFilterTest.java b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/search/SpringBootApplicationPropertiesResourceFilterTest.java
index 1548b7ae2..c0cd758b3 100644
--- a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/search/SpringBootApplicationPropertiesResourceFilterTest.java
+++ b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/search/SpringBootApplicationPropertiesResourceFilterTest.java
@@ -19,6 +19,7 @@
import org.springframework.sbm.boot.properties.SpringBootApplicationPropertiesRegistrar;
import org.springframework.sbm.boot.properties.api.SpringBootApplicationProperties;
import org.springframework.sbm.engine.context.ProjectContext;
+import org.springframework.sbm.openrewrite.RewriteExecutionContext;
import org.springframework.sbm.project.resource.TestProjectContext;
import org.junit.jupiter.api.Test;
@@ -32,7 +33,7 @@ public class SpringBootApplicationPropertiesResourceFilterTest {
void test() {
ProjectContext context = TestProjectContext.buildProjectContext()
.addProjectResource("src/main/resources/application.properties", "foo=bar\na=b")
- .addRegistrar(new SpringBootApplicationPropertiesRegistrar(new SpringApplicationPropertiesPathMatcher()))
+ .addRegistrar(new SpringBootApplicationPropertiesRegistrar(new SpringApplicationPropertiesPathMatcher(), new RewriteExecutionContext()))
.build();
List properties = context.search(new SpringBootApplicationPropertiesResourceListFilter());
diff --git a/components/test-helper/pom.xml b/components/test-helper/pom.xml
index 031e9ba54..21a75acb3 100644
--- a/components/test-helper/pom.xml
+++ b/components/test-helper/pom.xml
@@ -35,6 +35,7 @@
org.springframework.boot
spring-boot-starter-test
+ compile
org.assertj
diff --git a/scan-scope.puml b/scan-scope.puml
new file mode 100644
index 000000000..9591de6c9
--- /dev/null
+++ b/scan-scope.puml
@@ -0,0 +1,37 @@
+@startuml
+'https://plantuml.com/component-diagram
+
+
+
+package "Some Group" {
+ HTTP - [First Component]
+ [Another Component]
+}
+
+node "Other Groups" {
+ FTP - [Second Component]
+ [First Component] --> FTP
+}
+
+cloud {
+ [Example 1]
+}
+
+
+database "MySql" {
+ folder "This is my folder" {
+ [Folder 3]
+ }
+ frame "Foo" {
+ [Frame 4]
+ }
+}
+
+cla
+
+
+[Another Component] --> [Example 1]
+[Example 1] --> [Folder 3]
+[Folder 3] --> [Frame 4]
+
+@enduml
\ No newline at end of file