Skip to content

Commit

Permalink
Fix tests and adjust to changes in OR 8.1.2
Browse files Browse the repository at this point in the history
  • Loading branch information
fabapp2 committed Aug 10, 2023
1 parent 210a059 commit d4dc28c
Show file tree
Hide file tree
Showing 8 changed files with 62 additions and 38 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@

import lombok.Getter;
import lombok.Setter;
import org.springframework.sbm.scopes.annotations.ScanScope;
import org.springframework.stereotype.Component;

@Component
@Getter
@Setter
@ScanScope
public class ProjectContextHolder {
private ProjectContext projectContext;
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
import org.springframework.sbm.engine.context.ProjectContextHolder;
import lombok.RequiredArgsConstructor;
import org.openrewrite.Parser;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.tree.J;
import org.springframework.context.event.EventListener;
import org.springframework.sbm.parsers.JavaParserBuilder;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
Expand All @@ -39,7 +39,7 @@
@RequiredArgsConstructor
public class DependenciesChangedEventHandler {
private final ProjectContextHolder projectContextHolder;
private final JavaParser javaParser;
private final JavaParserBuilder javaParserBuilder;
private final ExecutionContext executionContext;

@EventListener
Expand All @@ -53,7 +53,7 @@ public void onDependenciesChanged(DependenciesChangedEvent event) {

Path projectRootDirectory = projectContextHolder.getProjectContext().getProjectRootDirectory();

Stream<SourceFile> parsedCompilationUnits = javaParser.parseInputs(compilationUnits, null, executionContext);
Stream<SourceFile> parsedCompilationUnits = javaParserBuilder.build().parseInputs(compilationUnits, null, executionContext);
// ((J.VariableDeclarations)parsedCompilationUnits.get(0).getClasses().get(0).getBody().getStatements().get(0)).getLeadingAnnotations().get(0).getType()
parsedCompilationUnits
.filter(J.CompilationUnit.class::isInstance)
Expand All @@ -63,6 +63,8 @@ public void onDependenciesChanged(DependenciesChangedEvent event) {
.filter(js -> js.getResource().getAbsolutePath().equals(projectRootDirectory.resolve(cu.getSourcePath()).normalize()))
.forEach(js -> js.getResource().replaceWith(cu));
});
} else {
throw new IllegalStateException("Could not get ProjectContext from ProjectContextHolder.");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,13 @@
package org.springframework.sbm.java.impl;

import org.openrewrite.*;
import org.openrewrite.internal.InMemoryLargeSourceSet;
import org.openrewrite.java.*;
import org.openrewrite.java.format.WrappingAndBraces;
import org.openrewrite.java.tree.*;
import org.springframework.sbm.java.api.*;
import org.springframework.sbm.java.migration.visitor.RemoveImplementsVisitor;
import org.springframework.sbm.java.refactoring.JavaRefactoring;
import org.springframework.sbm.parsers.JavaParserBuilder;
import org.springframework.sbm.project.resource.SbmApplicationProperties;
import org.springframework.sbm.project.resource.RewriteSourceFileHolder;
import lombok.extern.slf4j.Slf4j;
import org.openrewrite.java.search.DeclaresMethod;
Expand Down Expand Up @@ -156,6 +154,9 @@ public void addMethod(String methodTemplate, Set<String> requiredImports) {
@Override
public ClassDeclaration visitClassDeclaration(ClassDeclaration classDecl, ExecutionContext executionContext) {
ClassDeclaration cd = super.visitClassDeclaration(classDecl, executionContext);
J.CompilationUnit cu = getCursor().dropParentUntil(J.CompilationUnit.class::isInstance).getValue();
checkTypeAvailability(cu, requiredImports);

JavaTemplate template = JavaTemplate
.builder(methodTemplate)
.javaParser(javaParserBuilder)
Expand All @@ -169,6 +170,16 @@ public ClassDeclaration visitClassDeclaration(ClassDeclaration classDecl, Execut
this.apply(new WrappingAndBraces());
}

private void checkTypeAvailability(J.CompilationUnit cd, Set<String> requiredImports) {
List<String> missingTypes = cd.getTypesInUse().getTypesInUse().stream()
.map(JavaType::toString)
.filter(t -> !requiredImports.contains(t))
.toList();
if(!missingTypes.isEmpty()) {
throw new IllegalArgumentException("These types %s are not available to in compilation unit %s".formatted(missingTypes, cd.getSourcePath()));
}
}


private List<J.Annotation> findORAnnotations(String annotation) {
return getClassDeclaration().getLeadingAnnotations()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@

@Component
@ScanScope
@Deprecated
public class RewriteJavaParser implements JavaParser {

private final SbmApplicationProperties sbmApplicationProperties;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import org.springframework.core.io.Resource;
import org.springframework.sbm.engine.context.ProjectContext;
import org.springframework.sbm.engine.context.ProjectContextFactory;
import org.springframework.sbm.engine.context.ProjectContextHolder;
import org.springframework.sbm.engine.git.Commit;
import org.springframework.sbm.engine.git.GitSupport;
import org.springframework.sbm.project.RewriteSourceFileWrapper;
Expand All @@ -41,6 +42,7 @@ public class ProjectContextInitializer {
private final GitSupport gitSupport;
private final RewriteSourceFileWrapper rewriteSourceFileWrapper;
private final ExecutionContext executionContext;
private final ProjectContextHolder projectContextHolder;

public ProjectContext initProjectContext(Path projectDir, List<Resource> resources) {
final Path absoluteProjectDir = projectDir.toAbsolutePath().normalize();
Expand All @@ -54,7 +56,7 @@ public ProjectContext initProjectContext(Path projectDir, List<Resource> resourc
ProjectContext projectContext = projectContextFactory.createProjectContext(projectDir, projectResourceSet);

storeGitCommitHash(projectDir, projectContext);

projectContextHolder.setProjectContext(projectContext);
return projectContext;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -309,12 +309,14 @@ void testAddMethod() {
@Test
void testAddMethod2() {
String template =
"@Bean\n" +
"IntegrationFlow http_routeFlow() {\n" +
"return IntegrationFlows.from(Http.inboundChannelAdapter(\"/test\")).handle((p, h) -> p)\n" +
".log(LoggingHandler.Level.INFO)\n" +
".get();\n" +
"}\n";
"""
@Bean
IntegrationFlow http_routeFlow() {
return IntegrationFlows.from(Http.inboundChannelAdapter("/test")).handle((p, h) -> p)
.log(LoggingHandler.Level.INFO)
.get();
}
""";

Set<String> requiredImports = Set.of("org.springframework.integration.transformer.ObjectToStringTransformer",
"org.springframework.context.annotation.Configuration",
Expand All @@ -326,40 +328,40 @@ void testAddMethod2() {
"org.springframework.integration.http.dsl.Http");

ProjectContext context = TestProjectContext.buildProjectContext()
.withBuildFileHavingDependencies("org.springframework.boot:spring-boot-starter-integration:2.5.5",
"org.springframework.boot:spring-boot-starter-web:2.5.5")
.withJavaSource("src/main/java/Config.java", "public class Config {}")
.withBuildFileHavingDependencies(
"org.springframework.boot:spring-boot-starter-integration:2.5.5",
"org.springframework.boot:spring-boot-starter-web:2.5.5"
)
.withJavaSource("src/main/java", "public class Config {}")
.build();

long before = System.currentTimeMillis();

context.getBuildFile().addDependency(Dependency.builder()
context.getApplicationModules().getRootModule().getBuildFile().addDependency(Dependency.builder()
.groupId("org.springframework.integration")
.artifactId("spring-integration-http")
.version("5.4.4")
.build());

long timeSpent = System.currentTimeMillis() - before;
System.out.println("Adding a dependency took: " + (timeSpent/1000) + " sec.");

Type type = context.getProjectJavaSources().list().get(0).getTypes().get(0);
JavaSource javaSource = context.getProjectJavaSources().findJavaSourceDeclaringType("Config").get();
Type type = javaSource.getTypes().get(0);
type.addMethod(template, requiredImports);

assertThat(context.getProjectJavaSources().list().get(0).print()).isEqualTo(
"import org.springframework.context.annotation.Bean;\n" +
"import org.springframework.integration.dsl.IntegrationFlow;\n" +
"import org.springframework.integration.dsl.IntegrationFlows;\n" +
"import org.springframework.integration.handler.LoggingHandler;\n" +
"import org.springframework.integration.http.dsl.Http;\n" +
"\n" +
"public class Config {\n" +
" @Bean\n" +
" IntegrationFlow http_routeFlow() {\n" +
" return IntegrationFlows.from(Http.inboundChannelAdapter(\"/test\")).handle((p, h) -> p)\n" +
" .log(LoggingHandler.Level.INFO)\n" +
" .get();\n" +
" }\n" +
"}"
assertThat(javaSource.print()).isEqualTo(
"""
import org.springframework.context.annotation.Bean;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.handler.LoggingHandler;
import org.springframework.integration.http.dsl.Http;
public class Config {
@Bean
IntegrationFlow http_routeFlow() {
return IntegrationFlows.from(Http.inboundChannelAdapter("/test")).handle((p, h) -> p)
.log(LoggingHandler.Level.INFO)
.get();
}
}
"""
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import org.springframework.sbm.java.impl.DependenciesChangedEventHandler;
import org.springframework.sbm.java.impl.RewriteJavaParser;
import org.springframework.sbm.openrewrite.RewriteExecutionContext;
import org.springframework.sbm.parsers.JavaParserBuilder;
import org.springframework.sbm.project.resource.SbmApplicationProperties;
import org.springframework.sbm.project.resource.TestProjectContext;

Expand Down Expand Up @@ -563,7 +564,7 @@ public class Cat {
assertThat(fireEvent.getResolvedDependencies().get(0).toString()).endsWith("javax/validation/validation-api/2.0.1.Final/validation-api-2.0.1.Final.jar");

// call DependenciesChangedEventHandler to trigger recompile
RewriteJavaParser rewriteJavaParser = new RewriteJavaParser(new SbmApplicationProperties(), executionContext);
JavaParserBuilder rewriteJavaParser = new JavaParserBuilder();
ProjectContextHolder projectContextHolder = new ProjectContextHolder();
projectContextHolder.setProjectContext(context);
DependenciesChangedEventHandler handler = new DependenciesChangedEventHandler(projectContextHolder, rewriteJavaParser, executionContext);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,9 @@ public Builder withJavaSource(Path sourcePathDir, String sourceCode) {
if (sourcePathDir.isAbsolute()) {
throw new IllegalArgumentException("Source path must be relative to project root dir.");
}
if(sourcePathDir.toString().endsWith(".java")) {
throw new IllegalArgumentException("The provided path '%s' should only be the source path, e.g. 'src/main/'java'. Package and filename will be calculated from provided source code.".formatted(sourcePathDir));
}
String fqName = JavaSourceUtil.retrieveFullyQualifiedClassFileName(sourceCode);
Path sourcePath = sourcePathDir.resolve(fqName);
this.resourcesWithRelativePaths.put(sourcePath, sourceCode);
Expand Down

0 comments on commit d4dc28c

Please sign in to comment.