diff --git a/pom.xml b/pom.xml index 22695c9..dad532a 100644 --- a/pom.xml +++ b/pom.xml @@ -33,6 +33,10 @@ 2.43.0 2.41.0 2.47.0 + + 0.1.0-SNAPSHOT https://sonarcloud.io vitruv-tools @@ -76,6 +80,13 @@ ${emf.codegen.ecore.version} + + + tools.vitruv + tools.vitruv.neojoin.frontend.language + ${neojoin.version} + + org.springdoc springdoc-openapi-starter-webmvc-ui @@ -99,6 +110,20 @@ + + + + central-snapshots + https://central.sonatype.com/repository/maven-snapshots/ + + false + + + true + + + + diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildRequest.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildRequest.java index 9221e72..869b3fa 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildRequest.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildRequest.java @@ -29,6 +29,9 @@ public record VsumBuildRequest( /** File extension of VitruvOCL constraint files. */ public static final String CONSTRAINTS_EXTENSION = ".ocl"; + /** File extension of view files. */ + public static final String VIEWS_EXTENSION = ".nj"; + /** Makes the lists immutable and rejects {@code null} lists. */ public VsumBuildRequest { metamodels = List.copyOf(metamodels); @@ -60,7 +63,7 @@ public static VsumBuildRequest fromMultipart( read(metamodelFiles, "metamodel", METAMODEL_EXTENSION), read(reactionFiles, "reactions", REACTIONS_EXTENSION), read(constraintFiles, "constraint", CONSTRAINTS_EXTENSION), - read(viewFiles, "view definition", null)); + read(viewFiles, "view definition", VIEWS_EXTENSION)); } private static List read( diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildService.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildService.java index 6c8f7c1..667ebc5 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildService.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildService.java @@ -28,6 +28,7 @@ import tools.vitruv.methodologist.setup.vsum.service.project.ProjectGenerator; import tools.vitruv.methodologist.setup.vsum.service.project.ProjectLayout; import tools.vitruv.methodologist.setup.vsum.service.reactions.ReactionsProcessor; +import tools.vitruv.methodologist.setup.vsum.service.views.NeoJoinChecker; import tools.vitruv.methodologist.setup.vsum.service.views.ViewDefinitionProcessor; /** @@ -48,6 +49,7 @@ public class VsumProjectBuildService { private final MetamodelProcessor metamodelProcessor; private final ReactionsProcessor reactionsProcessor; private final ConstraintsProcessor constraintsProcessor; + private final NeoJoinChecker neoJoinChecker; private final ViewDefinitionProcessor viewDefinitionProcessor; private final ProjectGenerator projectGenerator; private final MavenBuildRunner mavenBuildRunner; @@ -131,6 +133,7 @@ ProjectSources generateProject(VsumBuildRequest request, Path projectRoot) throw reactionsProcessor.process(request.reactions(), metamodels, projectRoot); List constraintResources = constraintsProcessor.process(request.constraints(), projectRoot); + neoJoinChecker.check(request.viewDefinitions(), metamodels); viewDefinitionProcessor.process(request.viewDefinitions(), metamodels, projectRoot); projectGenerator.generate(projectRoot, metamodels, specifications, constraintResources); return sources(request, metamodels, constraintResources, projectRoot); diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationService.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationService.java index 4d0acc6..0807516 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationService.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationService.java @@ -1,13 +1,17 @@ package tools.vitruv.methodologist.setup.vsum.service; +import java.io.IOException; import java.util.List; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; +import tools.vitruv.methodologist.setup.exception.MethodologistSetupException; import tools.vitruv.methodologist.setup.vsum.service.metamodel.GeneratedMetamodel; import tools.vitruv.methodologist.setup.vsum.service.metamodel.MetamodelProcessor; import tools.vitruv.methodologist.setup.vsum.service.problem.VsumBuildException; import tools.vitruv.methodologist.setup.vsum.service.reactions.ReactionsProcessor; +import tools.vitruv.methodologist.setup.vsum.service.views.NeoJoinChecker; /** * Checks a VSUM project without building it, so that problems can be shown while it is edited. @@ -23,10 +27,12 @@ public class VsumValidationService { private final MetamodelProcessor metamodelProcessor; private final ReactionsProcessor reactionsProcessor; + private final NeoJoinChecker neoJoinChecker; /** * Checks the project. Like the build, the checks stop at the first stage with problems: reactions - * are only checked once the metamodels are valid. + * and view definitions are only checked once the metamodels are valid, and view definitions once + * the reactions are. * * @param request the project, as for a build * @return the problems the build would report before running Maven @@ -35,10 +41,19 @@ public VsumValidationResult validate(VsumBuildRequest request) { try { List metamodels = metamodelProcessor.check(request.metamodels()); reactionsProcessor.check(request.reactions(), metamodels); + neoJoinChecker.check(request.viewDefinitions(), metamodels); return VsumValidationResult.of(List.of()); } catch (VsumBuildException e) { log.debug("VSUM validation found problems: {}", e.getMessage()); return VsumValidationResult.of(e.getProblems()); + } catch (IOException e) { + // the views are checked from temporary files; failing to write them is not a problem of the + // uploads + throw new MethodologistSetupException( + VsumErrorCodes.BUILD_ERROR, + "Failed to validate the VSUM project: " + e.getMessage(), + HttpStatus.INTERNAL_SERVER_ERROR, + e); } } } diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/views/NeoJoinChecker.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/views/NeoJoinChecker.java new file mode 100644 index 0000000..27b3b31 --- /dev/null +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/views/NeoJoinChecker.java @@ -0,0 +1,200 @@ +package tools.vitruv.methodologist.setup.vsum.service.views; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.EPackage; +import org.eclipse.emf.ecore.EValidator; +import org.eclipse.emf.ecore.EcorePackage; +import org.eclipse.emf.ecore.impl.EPackageRegistryImpl; +import org.eclipse.xtext.common.types.TypesPackage; +import org.eclipse.xtext.diagnostics.Severity; +import org.eclipse.xtext.xbase.XbasePackage; +import org.eclipse.xtext.xtype.XtypePackage; +import org.springframework.stereotype.Service; +import tools.vitruv.methodologist.setup.vsum.service.UploadedFile; +import tools.vitruv.methodologist.setup.vsum.service.VsumErrorCodes; +import tools.vitruv.methodologist.setup.vsum.service.metamodel.GeneratedMetamodel; +import tools.vitruv.methodologist.setup.vsum.service.problem.BuildProblem; +import tools.vitruv.methodologist.setup.vsum.service.problem.BuildProblem.Source; +import tools.vitruv.methodologist.setup.vsum.service.problem.Excerpts; +import tools.vitruv.methodologist.setup.vsum.service.problem.VsumBuildException; +import tools.vitruv.neojoin.NeoJoinStandaloneSetup; +import tools.vitruv.neojoin.Parser; +import tools.vitruv.neojoin.ast.AstPackage; + +/** + * Checks NeoJoin view definitions before the build: parses and validates each file with NeoJoin + * against the uploaded metamodels, and rejects export names and view-type nsURIs declared in more + * than one file. + */ +@Service +public class NeoJoinChecker { + + private static final Pattern EXPORT_PATTERN = Pattern.compile("(?m)^[ \\t]*(export)[ \\t]+"); + + /** + * Xtext registers NeoJoin's validator globally and keeps the first one, which is bound to the + * metamodels of the first check. Each check replaces it, and checks run one at a time. + */ + private static final Object XTEXT_VALIDATOR_LOCK = new Object(); + + /** The packages NeoJoin's validator is registered for. */ + private static final List VALIDATED_PACKAGES = + List.of( + AstPackage.eINSTANCE, + XbasePackage.eINSTANCE, + XtypePackage.eINSTANCE, + TypesPackage.eINSTANCE); + + /** + * Checks the view definitions against the metamodels. Syntax errors, unresolved imports, Xbase + * type errors, and duplicate export names or view-type nsURIs are reported together. + * + * @param viewDefinitions uploaded NeoJoin view definitions + * @param metamodels the processed metamodels the views may import + * @throws VsumBuildException when a view definition is invalid + * @throws IOException when a view definition cannot be written to a temporary file for parsing + */ + public void check(List viewDefinitions, List metamodels) + throws IOException { + synchronized (XTEXT_VALIDATOR_LOCK) { + checkExclusively(viewDefinitions, metamodels); + } + } + + private void checkExclusively( + List viewDefinitions, List metamodels) throws IOException { + + // 1. Register available metamodels + EPackage.Registry registry = new EPackageRegistryImpl(); + register(EcorePackage.eINSTANCE, registry); + + for (GeneratedMetamodel model : metamodels) { + if (model.ePackage() != null) { + register(model.ePackage(), registry); + } + } + + // 2. Initialize NeoJoin parser + VALIDATED_PACKAGES.forEach(EValidator.Registry.INSTANCE::remove); + NeoJoinStandaloneSetup setup = new NeoJoinStandaloneSetup(registry); + + List problems = new ArrayList<>(); + + Map exportOwners = new HashMap<>(); + Map nsUriOwners = new HashMap<>(); + + // 3. Parse and validate each uploaded view + for (UploadedFile file : viewDefinitions) { + Parser parser = setup.getParser(); + Path path = Files.createTempFile("neojoin-", ".nj"); + + try { + Files.write(path, file.content()); + + Parser.Result result = parser.parse(URI.createFileURI(path.toString())); + + // 4. Collect NeoJoin validation errors + for (var issue : result.issues()) { + if (issue.getSeverity() == Severity.ERROR) { + problems.add( + BuildProblem.at( + Source.VIEWS, + file.fileName(), + file.text(), + issue.getLineNumber(), + issue.getColumn(), + issue.getMessage())); + } + } + + // Handle a failed parse without diagnostics + if (result instanceof Parser.Result.Failure && result.issues().isEmpty()) { + problems.add( + BuildProblem.of( + Source.VIEWS, file.fileName(), "Unable to parse NeoJoin view definition")); + } + + // 5. Check duplicates across files + if (result instanceof Parser.Result.Success success) { + + String exportName = success.aqr().export().name(); + + String nsUri = success.aqr().export().uri().toString(); + + String previousExport = exportOwners.putIfAbsent(exportName, file.fileName()); + + if (previousExport != null) { + problems.add( + duplicateProblem( + file, + "Duplicate export name '" + + exportName + + "' already declared in " + + previousExport)); + } + + String previousNsUri = nsUriOwners.putIfAbsent(nsUri, file.fileName()); + + if (previousNsUri != null) { + problems.add( + duplicateProblem( + file, + "Duplicate view-type nsURI '" + + nsUri + + "' already declared in " + + previousNsUri)); + } + } + + } finally { + Files.deleteIfExists(path); + } + } + + // 6. Reject invalid view definitions + if (!problems.isEmpty()) { + throw new VsumBuildException( + VsumErrorCodes.INPUT_ERROR, "Invalid NeoJoin view definitions:", problems); + } + } + + private static void register(EPackage ePackage, EPackage.Registry registry) { + + if (ePackage.getNsURI() != null) { + registry.put(ePackage.getNsURI(), ePackage); + } + + for (EPackage subpackage : ePackage.getESubpackages()) { + register(subpackage, registry); + } + } + + private static BuildProblem duplicateProblem(UploadedFile file, String message) { + + String text = file.text(); + Matcher matcher = EXPORT_PATTERN.matcher(text); + + if (!matcher.find()) { + return BuildProblem.of(Source.VIEWS, file.fileName(), message); + } + + int offset = matcher.start(1); + + return BuildProblem.at( + Source.VIEWS, + file.fileName(), + text, + Excerpts.lineOf(text, offset), + Excerpts.columnOf(text, offset), + message); + } +} diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/controller/VsumControllerErrorHandlingTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/controller/VsumControllerErrorHandlingTest.java index 5e0aa99..47eccb8 100644 --- a/src/test/java/tools/vitruv/methodologist/setup/vsum/controller/VsumControllerErrorHandlingTest.java +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/controller/VsumControllerErrorHandlingTest.java @@ -22,13 +22,17 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import tools.vitruv.methodologist.setup.config.GlobalExceptionHandler; import tools.vitruv.methodologist.setup.exception.MethodologistSetupException; +import tools.vitruv.methodologist.setup.vsum.service.TestFiles; import tools.vitruv.methodologist.setup.vsum.service.VsumErrorCodes; import tools.vitruv.methodologist.setup.vsum.service.VsumProjectBuildService; import tools.vitruv.methodologist.setup.vsum.service.VsumValidationResult; import tools.vitruv.methodologist.setup.vsum.service.VsumValidationService; +import tools.vitruv.methodologist.setup.vsum.service.metamodel.MetamodelProcessor; import tools.vitruv.methodologist.setup.vsum.service.problem.BuildProblem; import tools.vitruv.methodologist.setup.vsum.service.problem.BuildProblem.Source; import tools.vitruv.methodologist.setup.vsum.service.problem.VsumBuildException; +import tools.vitruv.methodologist.setup.vsum.service.reactions.ReactionsProcessor; +import tools.vitruv.methodologist.setup.vsum.service.views.NeoJoinChecker; class VsumControllerErrorHandlingTest { @@ -210,6 +214,59 @@ void invalidProjectsAreValidatedWithOk() throws Exception { verifyNoInteractions(buildService); } + /** /validate runs NeoJoin on the uploaded views, and reports their problems with 200. */ + @Test + void viewDefinitionsAreValidatedByNeoJoin() throws Exception { + MockMvc validating = + MockMvcBuilders.standaloneSetup( + new VsumController( + buildService, + new VsumValidationService( + new MetamodelProcessor(), new ReactionsProcessor(), new NeoJoinChecker()))) + .setControllerAdvice(new GlobalExceptionHandler()) + .build(); + MockMultipartFile metamodel = + new MockMultipartFile( + "metamodelFiles", + "model.ecore", + "application/xml", + TestFiles.fixture("model.ecore").content()); + MockMultipartFile view = + new MockMultipartFile( + "viewFiles", + "components.nj", + "text/plain", + TestFiles.fixture("components.nj") + .text() + .replace("from Component", "from Komponent") + .getBytes()); + + validating + .perform(multipart("/api/vsum/validate").file(metamodel).file(view)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.valid").value(false)) + .andExpect(jsonPath("$.problems[0].source").value("VIEWS")) + .andExpect(jsonPath("$.problems[0].file").value("components.nj")) + .andExpect(jsonPath("$.problems[0].line").value(5)) + .andExpect(jsonPath("$.problems[0].column").value(6)) + .andExpect( + jsonPath("$.problems[0].message") + .value(org.hamcrest.Matchers.containsString("Komponent"))); + validating + .perform( + multipart("/api/vsum/validate") + .file(metamodel) + .file( + new MockMultipartFile( + "viewFiles", + "components.nj", + "text/plain", + TestFiles.fixture("components.nj").content()))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.valid").value(true)); + verifyNoInteractions(buildService); + } + @Test void validProjectsHaveNoProblems() throws Exception { when(validationService.validate(any())).thenReturn(VsumValidationResult.of(List.of())); diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildEndToEndTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildEndToEndTest.java index d544637..26ae117 100644 --- a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildEndToEndTest.java +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildEndToEndTest.java @@ -23,6 +23,7 @@ import tools.vitruv.methodologist.setup.vsum.service.metamodel.MetamodelProcessor; import tools.vitruv.methodologist.setup.vsum.service.project.ProjectGenerator; import tools.vitruv.methodologist.setup.vsum.service.reactions.ReactionsProcessor; +import tools.vitruv.methodologist.setup.vsum.service.views.NeoJoinChecker; import tools.vitruv.methodologist.setup.vsum.service.views.NeoJoinViewDefinitionProcessor; /** @@ -40,6 +41,7 @@ class VsumBuildEndToEndTest { new MetamodelProcessor(), new ReactionsProcessor(), new ConstraintsProcessor(), + new NeoJoinChecker(), new NeoJoinViewDefinitionProcessor(), new ProjectGenerator(properties), new MavenBuildRunner(properties), diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildRequestTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildRequestTest.java index 4ceb7c9..d2002c3 100644 --- a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildRequestTest.java +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildRequestTest.java @@ -45,6 +45,28 @@ void rejectsWrongExtensions() { assertTrue(exception.getMessage().contains("'.reactions'"), exception.getMessage()); } + @Test + void rejectsViewDefinitionsWithoutTheNeoJoinExtension() { + MethodologistSetupException exception = + assertThrows( + MethodologistSetupException.class, + () -> + VsumBuildRequest.fromMultipart( + List.of(file("m.ecore")), null, null, List.of(file("view.txt")))); + + assertEquals(VsumErrorCodes.INPUT_ERROR, exception.getErrorCode()); + assertTrue(exception.getMessage().contains("'.nj'"), exception.getMessage()); + } + + @Test + void acceptsViewDefinitionsWithTheNeoJoinExtension() { + VsumBuildRequest request = + VsumBuildRequest.fromMultipart( + List.of(file("m.ecore")), null, null, List.of(file("Components.NJ"))); + + assertEquals("Components.NJ", request.viewDefinitions().get(0).fileName()); + } + @Test void rejectsEmptyFiles() { MockMultipartFile empty = new MockMultipartFile("metamodelFiles", "m.ecore", null, new byte[0]); diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildServiceTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildServiceTest.java index b39b462..8bc46ed 100644 --- a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildServiceTest.java +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildServiceTest.java @@ -38,6 +38,7 @@ import tools.vitruv.methodologist.setup.vsum.service.project.ProjectGenerator; import tools.vitruv.methodologist.setup.vsum.service.project.ProjectLayout; import tools.vitruv.methodologist.setup.vsum.service.reactions.ReactionsProcessor; +import tools.vitruv.methodologist.setup.vsum.service.views.NeoJoinChecker; import tools.vitruv.methodologist.setup.vsum.service.views.NeoJoinViewDefinitionProcessor; class VsumProjectBuildServiceTest { @@ -47,7 +48,7 @@ class VsumProjectBuildServiceTest { List.of(fixture("model.ecore"), fixture("model2.ecore")), List.of(fixture("templateReactions.reactions")), List.of(fixture("constraints.ocl")), - List.of(text("components.nj", "view stub"))); + List.of(fixture("components.nj"))); private final VsumBuildProperties properties = new VsumBuildProperties(); private final VsumProjectBuildService service = @@ -55,6 +56,7 @@ class VsumProjectBuildServiceTest { new MetamodelProcessor(), new ReactionsProcessor(), new ConstraintsProcessor(), + new NeoJoinChecker(), new NeoJoinViewDefinitionProcessor(), new ProjectGenerator(properties), new MavenBuildRunner(properties), @@ -142,6 +144,7 @@ void keepsTheWorkspacesOfFailuresNotCausedByTheUploads(String errorCode, boolean new MetamodelProcessor(), new ReactionsProcessor(), new ConstraintsProcessor(), + new NeoJoinChecker(), new NeoJoinViewDefinitionProcessor(), new ProjectGenerator(properties), mavenBuildRunner, @@ -192,6 +195,7 @@ void rejectsMisspelledClassesBeforeTheMavenBuild() { new MetamodelProcessor(), new ReactionsProcessor(), new ConstraintsProcessor(), + new NeoJoinChecker(), new NeoJoinViewDefinitionProcessor(), new ProjectGenerator(properties), mavenBuildRunner, @@ -218,6 +222,47 @@ void rejectsMisspelledClassesBeforeTheMavenBuild() { assertEquals("Did you mean 'Entity'?", problem.hint()); } + /** An invalid view definition is rejected by NeoJoin before the Maven build of /build or /jar. */ + @Test + void rejectsInvalidViewDefinitionsBeforeTheMavenBuild() throws IOException { + MavenBuildRunner mavenBuildRunner = mock(MavenBuildRunner.class); + VsumProjectBuildService checked = + new VsumProjectBuildService( + new MetamodelProcessor(), + new ReactionsProcessor(), + new ConstraintsProcessor(), + new NeoJoinChecker(), + new NeoJoinViewDefinitionProcessor(), + new ProjectGenerator(properties), + mavenBuildRunner, + properties); + String view = + fixture("components.nj") + .text() + .replace("http://vitruv.tools/methodologisttemplate/model\"", "http://example.org/x\""); + VsumBuildRequest request = + new VsumBuildRequest( + List.of(fixture("model.ecore"), fixture("model2.ecore")), + List.of(fixture("templateReactions.reactions")), + List.of(), + List.of(text("components.nj", view))); + + for (Runnable build : + List.of( + () -> checked.buildProjectJar(request), () -> checked.buildProjectArchive(request))) { + VsumBuildException exception = assertThrows(VsumBuildException.class, build::run); + + assertEquals(VsumErrorCodes.INPUT_ERROR, exception.getErrorCode()); + assertEquals(HttpStatus.BAD_REQUEST, exception.getStatus()); + BuildProblem problem = exception.getProblems().get(0); + assertEquals(Source.VIEWS, problem.source()); + assertEquals("components.nj", problem.file()); + assertEquals(lineContaining(view, "http://example.org/x"), problem.line()); + assertTrue(problem.message().contains("http://example.org/x"), problem.message()); + } + verify(mavenBuildRunner, never()).build(any(), any()); + } + /** * An error only the Reactions compiler finds, a misspelled feature in Xbase code, is reported at * its line in the upload, as one problem with a hint. Runs the real Maven build. diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationServiceTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationServiceTest.java index 89b8b11..99326ce 100644 --- a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationServiceTest.java +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationServiceTest.java @@ -37,6 +37,7 @@ import tools.vitruv.methodologist.setup.vsum.service.problem.VsumBuildException; import tools.vitruv.methodologist.setup.vsum.service.project.ProjectGenerator; import tools.vitruv.methodologist.setup.vsum.service.reactions.ReactionsProcessor; +import tools.vitruv.methodologist.setup.vsum.service.views.NeoJoinChecker; import tools.vitruv.methodologist.setup.vsum.service.views.NeoJoinViewDefinitionProcessor; class VsumValidationServiceTest { @@ -46,11 +47,12 @@ class VsumValidationServiceTest { List.of(fixture("model.ecore"), fixture("model2.ecore")), List.of(fixture("templateReactions.reactions")), List.of(fixture("constraints.ocl")), - List.of(text("components.nj", "view stub"))); + List.of(fixture("components.nj"))); private final VsumBuildProperties properties = new VsumBuildProperties(); private final VsumValidationService service = - new VsumValidationService(new MetamodelProcessor(), new ReactionsProcessor()); + new VsumValidationService( + new MetamodelProcessor(), new ReactionsProcessor(), new NeoJoinChecker()); @TempDir Path temporaryDirectory; @@ -102,6 +104,26 @@ void reportsTheReactionsProblemsTheBuildReportsBeforeMaven() { assertEquals(problemsOfTheBuild(request), result); } + @Test + void reportsTheViewProblemsTheBuildReportsBeforeMaven() { + String view = + fixture("components.nj").text().replace("supportedProtocols.size", "supportedProtocolz"); + VsumBuildRequest request = + new VsumBuildRequest( + List.of(fixture("model.ecore"), fixture("model2.ecore")), + List.of(fixture("templateReactions.reactions")), + List.of(), + List.of(text("components.nj", view))); + + VsumValidationResult result = service.validate(request); + + assertFalse(result.valid()); + assertEquals(Source.VIEWS, result.problems().get(0).source()); + assertEquals("components.nj", result.problems().get(0).file()); + assertTrue(result.problems().get(0).message().contains("supportedProtocolz")); + assertEquals(problemsOfTheBuild(request), result); + } + @Test void leavesNoFilesBehind() throws IOException { Set before = buildWorkspaces(); @@ -132,6 +154,7 @@ void isAnsweredWhileABuildIsRunning() throws Exception { new MetamodelProcessor(), new ReactionsProcessor(), new ConstraintsProcessor(), + new NeoJoinChecker(), new NeoJoinViewDefinitionProcessor(), new ProjectGenerator(buildProperties), new MavenBuildRunner(buildProperties), @@ -169,6 +192,7 @@ private VsumValidationResult problemsOfTheBuild(VsumBuildRequest request) { new MetamodelProcessor(), new ReactionsProcessor(), new ConstraintsProcessor(), + new NeoJoinChecker(), new NeoJoinViewDefinitionProcessor(), new ProjectGenerator(properties), mavenBuildRunner, diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/views/NeoJoinCheckerTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/views/NeoJoinCheckerTest.java new file mode 100644 index 0000000..f29113a --- /dev/null +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/views/NeoJoinCheckerTest.java @@ -0,0 +1,308 @@ +package tools.vitruv.methodologist.setup.vsum.service.views; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static tools.vitruv.methodologist.setup.vsum.service.TestFiles.fixture; +import static tools.vitruv.methodologist.setup.vsum.service.TestFiles.text; + +import java.io.IOException; +import java.util.List; +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.EAttribute; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EPackage; +import org.eclipse.emf.ecore.EValidator; +import org.eclipse.emf.ecore.EcoreFactory; +import org.eclipse.emf.ecore.EcorePackage; +import org.eclipse.emf.ecore.resource.impl.ResourceImpl; +import org.eclipse.xtext.common.types.TypesPackage; +import org.eclipse.xtext.xbase.XbasePackage; +import org.eclipse.xtext.xtype.XtypePackage; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import tools.vitruv.methodologist.setup.vsum.service.UploadedFile; +import tools.vitruv.methodologist.setup.vsum.service.VsumErrorCodes; +import tools.vitruv.methodologist.setup.vsum.service.metamodel.GeneratedMetamodel; +import tools.vitruv.methodologist.setup.vsum.service.metamodel.MetamodelProcessor; +import tools.vitruv.methodologist.setup.vsum.service.problem.BuildProblem; +import tools.vitruv.methodologist.setup.vsum.service.problem.BuildProblem.Source; +import tools.vitruv.methodologist.setup.vsum.service.problem.VsumBuildException; +import tools.vitruv.neojoin.ast.AstPackage; + +class NeoJoinCheckerTest { + + private static final String MODEL_NS_URI = "http://vitruv.tools/methodologisttemplate/model"; + + private static final List METAMODELS = + new MetamodelProcessor().check(List.of(fixture("model.ecore"), fixture("model2.ecore"))); + + private final NeoJoinChecker checker = new NeoJoinChecker(); + + @Test + void acceptsAValidQuery() { + assertDoesNotThrow(() -> checker.check(List.of(fixture("components.nj")), METAMODELS)); + } + + @Test + void acceptsNoViewDefinitions() { + assertDoesNotThrow(() -> checker.check(List.of(), METAMODELS)); + } + + @Test + void reportsSyntaxErrorsAtTheirLocation() { + String view = + """ + export components to "http://example.org/components" + + import "%s" + + from Component c + create ComponentView { + c.name + """ + .formatted(MODEL_NS_URI); + + BuildProblem problem = onlyProblem(text("broken.nj", view)); + + assertEquals("broken.nj", problem.file()); + assertNotNull(problem.line(), problem.toString()); + assertNotNull(problem.column(), problem.toString()); + assertNotNull(problem.excerpt(), problem.toString()); + assertTrue(problem.message().contains("'}'"), problem.message()); + } + + @Test + void reportsImportsOfMetamodelsThatWereNotUploaded() { + String view = + """ + export components to "http://example.org/components" + + import "http://example.org/unknown" + + from Component c + create ComponentView + """; + + VsumBuildException exception = rejected(text("unknown.nj", view)); + + BuildProblem problem = exception.getProblems().get(0); + assertEquals(Source.VIEWS, problem.source()); + assertEquals("unknown.nj", problem.file()); + assertEquals(3, problem.line(), exception.getMessage()); + assertEquals(8, problem.column(), exception.getMessage()); + assertTrue(problem.message().contains("http://example.org/unknown"), problem.message()); + assertTrue(problem.excerpt().contains("import \"http://example.org/unknown\"")); + } + + @Test + void reportsInvalidXbaseExpressions() { + String view = + fixture("components.nj").text().replace("supportedProtocols.size", "supportedProtocolz"); + + BuildProblem problem = onlyProblem(text("components.nj", view)); + + assertEquals(lineContaining(view, "supportedProtocolz"), problem.line()); + assertTrue(problem.message().contains("supportedProtocolz"), problem.message()); + } + + @Test + void rejectsDuplicateExportNames() { + UploadedFile first = view("a.nj", "components", "http://example.org/a"); + UploadedFile second = view("b.nj", "components", "http://example.org/b"); + + BuildProblem problem = onlyProblem(first, second); + + assertEquals("b.nj", problem.file()); + assertEquals(1, problem.line()); + assertEquals(1, problem.column()); + assertEquals("Duplicate export name 'components' already declared in a.nj", problem.message()); + assertTrue(problem.excerpt().contains("export components to"), problem.excerpt()); + } + + @Test + void rejectsDuplicateViewTypeNsUris() { + UploadedFile first = view("a.nj", "first", "http://example.org/views"); + UploadedFile second = view("b.nj", "second", "http://example.org/views"); + + BuildProblem problem = onlyProblem(first, second); + + assertEquals("b.nj", problem.file()); + assertEquals(1, problem.line()); + assertEquals(1, problem.column()); + assertEquals( + "Duplicate view-type nsURI 'http://example.org/views' already declared in a.nj", + problem.message()); + assertTrue(problem.excerpt().contains("export second to"), problem.excerpt()); + } + + @Test + void resolvesImportsOfSubpackages() { + EPackage root = ePackage("root", "http://example.org/root", "RootThing"); + EPackage sub = ePackage("sub", "http://example.org/root/sub", "SubThing"); + root.getESubpackages().add(sub); + String view = + """ + export things to "http://example.org/things" + + import "http://example.org/root/sub" + + from SubThing t + create Thing { + t.label + } + """; + + assertDoesNotThrow(() -> checker.check(List.of(text("things.nj", view)), metamodels(root))); + } + + /** + * Starts each test as in a fresh JVM, where the first NeoJoin validator registered would be kept + * for all later checks. + */ + @BeforeEach + void forgetNeoJoinValidators() { + List.of( + AstPackage.eINSTANCE, + XbasePackage.eINSTANCE, + XtypePackage.eINSTANCE, + TypesPackage.eINSTANCE) + .forEach(EValidator.Registry.INSTANCE::remove); + } + + /** + * NeoJoin's validator resolves 'conforms to' with the metamodels of the check; a later request + * must find its own metamodels, not only those of the first request. + */ + @Test + void validatesEachRequestAgainstItsOwnMetamodels() throws IOException { + checker.check(List.of(fixture("components.nj")), METAMODELS); + EPackage reference = ePackage("reference", "http://example.org/reference", "Thing"); + String view = + """ + export things to "http://example.org/things" + conforms to "http://example.org/reference" + + import "http://example.org/reference" + + from Thing t + create Thing { + t.label + } + """; + + assertDoesNotThrow( + () -> checker.check(List.of(text("things.nj", view)), metamodels(reference))); + } + + /** A later request must not see the metamodels of an earlier request. */ + @Test + void doesNotSeeTheMetamodelsOfEarlierRequests() throws IOException { + EPackage earlier = ePackage("earlier", "http://example.org/earlier", "Thing"); + String earlierView = + """ + export things to "http://example.org/things" + conforms to "http://example.org/earlier" + + import "http://example.org/earlier" + + from Thing t + create Thing { + t.label + } + """; + checker.check(List.of(text("things.nj", earlierView)), metamodels(earlier)); + String laterView = + """ + export components to "http://example.org/components" + conforms to "http://example.org/earlier" + + import "%s" + + from Component c + create ComponentView { + c.name + } + """ + .formatted(MODEL_NS_URI); + + BuildProblem problem = onlyProblem(text("components.nj", laterView)); + + assertEquals(2, problem.line()); + assertEquals( + "Reference metamodel not found: http://example.org/earlier", + problem.message(), + problem.toString()); + } + + private BuildProblem onlyProblem(UploadedFile... views) { + VsumBuildException exception = rejected(views); + assertEquals(1, exception.getProblems().size(), exception.getMessage()); + BuildProblem problem = exception.getProblems().get(0); + assertEquals(Source.VIEWS, problem.source()); + return problem; + } + + private VsumBuildException rejected(UploadedFile... views) { + VsumBuildException exception = + assertThrows(VsumBuildException.class, () -> checker.check(List.of(views), METAMODELS)); + assertEquals(VsumErrorCodes.INPUT_ERROR, exception.getErrorCode(), exception.getMessage()); + return exception; + } + + private static UploadedFile view(String fileName, String exportName, String nsUri) { + return text( + fileName, + """ + export %s to "%s" + + import "%s" + + from Component c + create ComponentView { + c.name + } + """ + .formatted(exportName, nsUri, MODEL_NS_URI)); + } + + private static EPackage ePackage(String name, String nsUri, String className) { + EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage(); + ePackage.setName(name); + ePackage.setNsPrefix(name); + ePackage.setNsURI(nsUri); + EClass eClass = EcoreFactory.eINSTANCE.createEClass(); + eClass.setName(className); + EAttribute label = EcoreFactory.eINSTANCE.createEAttribute(); + label.setName("label"); + label.setEType(EcorePackage.Literals.ESTRING); + eClass.getEStructuralFeatures().add(label); + ePackage.getEClassifiers().add(eClass); + return ePackage; + } + + /** Places the package in a resource, as the metamodel processor does with the uploads. */ + private static List metamodels(EPackage ePackage) { + new ResourceImpl(URI.createURI(ePackage.getName() + ".ecore")).getContents().add(ePackage); + return List.of( + new GeneratedMetamodel( + ePackage.getName(), + ePackage.getNsURI(), + ePackage.getName() + ".ecore", + ePackage.getName() + ".genmodel", + List.of(), + ePackage)); + } + + private static int lineContaining(String text, String fragment) { + List lines = text.lines().toList(); + for (int i = 0; i < lines.size(); i++) { + if (lines.get(i).contains(fragment)) { + return i + 1; + } + } + throw new IllegalArgumentException(fragment); + } +} diff --git a/src/test/resources/vsum/components.nj b/src/test/resources/vsum/components.nj new file mode 100644 index 0000000..88fa6aa --- /dev/null +++ b/src/test/resources/vsum/components.nj @@ -0,0 +1,9 @@ +export components to "http://vitruv.tools/methodologisttemplate/views/components" + +import "http://vitruv.tools/methodologisttemplate/model" + +from Component c +create ComponentView { + c.name + protocolCount := c.supportedProtocols.size +}