From 3e298c75577b9762a311db106c4f25d9e7ba2e23 Mon Sep 17 00:00:00 2001 From: davit Date: Mon, 16 Nov 2026 12:39:51 +0100 Subject: [PATCH 1/2] Compile NeoJoin views into the generated VSUM --- Dockerfile | 8 +- README.md | 34 ++- .../setup/vsum/controller/VsumController.java | 9 +- .../vsum/service/VsumBuildProperties.java | 8 + .../setup/vsum/service/VsumBuildRequest.java | 6 +- .../setup/vsum/service/VsumBuildWarmup.java | 5 +- .../setup/vsum/service/VsumErrorCodes.java | 7 +- .../vsum/service/VsumProjectBuildService.java | 26 ++- .../vsum/service/VsumValidationService.java | 5 +- .../service/problem/BuildOutputParser.java | 56 ++++- .../vsum/service/problem/ProjectSources.java | 35 ++++ .../service/project/ProjectGenerator.java | 41 +++- .../vsum/service/project/ProjectLayout.java | 30 ++- .../vsum/service/views/GeneratedViewType.java | 95 +++++++++ .../views/NeoJoinViewDefinitionProcessor.java | 197 +++++++++++++++++- .../views/ViewDefinitionProcessor.java | 18 +- src/main/resources/templates/vsum/rootPom.ftl | 17 ++ .../templates/vsum/viewtypePluginXml.ftl | 16 ++ .../resources/templates/vsum/viewtypePom.ftl | 157 ++++++++++++++ .../templates/vsum/viewtypeProject.ftl | 18 ++ .../templates/vsum/viewtypeWorkflow.ftl | 22 ++ .../resources/templates/vsum/vsumMain.ftl | 14 ++ src/main/resources/templates/vsum/vsumPom.ftl | 8 + .../resources/templates/vsum/vsumTest.ftl | 37 +++- src/main/resources/vsum-sample/components.nj | 9 + .../vsum/service/VsumBuildEndToEndTest.java | 79 +++++-- .../vsum/service/VsumBuildWarmupTest.java | 1 + .../service/VsumProjectBuildServiceTest.java | 4 +- .../service/VsumValidationServiceTest.java | 5 +- .../service/project/ProjectGeneratorTest.java | 6 +- 30 files changed, 891 insertions(+), 82 deletions(-) create mode 100644 src/main/java/tools/vitruv/methodologist/setup/vsum/service/views/GeneratedViewType.java create mode 100644 src/main/resources/templates/vsum/viewtypePluginXml.ftl create mode 100644 src/main/resources/templates/vsum/viewtypePom.ftl create mode 100644 src/main/resources/templates/vsum/viewtypeProject.ftl create mode 100644 src/main/resources/templates/vsum/viewtypeWorkflow.ftl create mode 100644 src/main/resources/vsum-sample/components.nj diff --git a/Dockerfile b/Dockerfile index 2afb2a6..6fce670 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,9 +12,11 @@ RUN mvn --batch-mode --no-transfer-progress -DskipTests package \ FROM ${MAVEN_IMAGE} COPY --from=build /workspace/app.jar /app/app.jar -# Fill the Maven repository of the VSUM builds by building a sample project once. The image then -# contains every dependency of the generated projects, and builds run offline: they do not depend -# on Maven Central being reachable, and the first build after a deployment is as fast as the rest. +# Fill the Maven repository of the VSUM builds by building a sample project once. The sample has +# every kind of input (metamodels, reactions, VitruvOCL constraints, a NeoJoin view), so the image +# then contains every dependency of the generated projects, including the NeoJoin compiler, and +# builds run offline: they do not depend on Maven Central being reachable, and the first build +# after a deployment is as fast as the rest. # To change versions (setup.vsum.*-version), rebuild the image. ENV SETUP_VSUM_MAVEN_REPOSITORY=/opt/vsum-m2 RUN java -jar /app/app.jar \ diff --git a/README.md b/README.md index 69179ad..b614b13 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,8 @@ constraints, and view definitions. - **GenModel Validation**: Inspect GenModel files for compliance issues without modifying them - **GenModel Processing**: Apply standardization rules and download the corrected file - **VSUM Build**: Generate genmodels and a Methodologist-Template project from metamodels, reactions, - and VitruvOCL constraints, build and smoke-test it, and return the project zip or executable jar + VitruvOCL constraints, and NeoJoin view definitions, build and smoke-test it, and return the project + zip or executable jar - **VSUM Validation**: Run the checks of the build without building, e.g. after every save - **OpenAPI / Swagger UI**: Interactive API documentation - **Error Handling**: Centralized exception handling with structured error responses @@ -48,7 +49,7 @@ Maven repository (`/opt/vsum-m2`) with every dependency of the generated project builds run offline: they do not depend on Maven Central, and the first build after a deployment is as fast as the others. Building the image needs network access. -To change the Vitruvius, VitruvOCL, EMF, or plugin versions, change them in `VsumBuildProperties` and +To change the Vitruvius, VitruvOCL, NeoJoin, EMF, or plugin versions, change them in `VsumBuildProperties` and rebuild the image. A version overridden at runtime (`SETUP_VSUM_*_VERSION`) that is missing from the image is downloaded once and logged (`setup.vsum.online-fallback`); set `SETUP_VSUM_ONLINE_FALLBACK=false` to fail instead. @@ -108,13 +109,14 @@ executable VSUM jar, which hosts the VSUM in a Vitruvius server (`java -jar to ""`, imports only uploaded nsURIs, + and its file name, export, and nsURI are unique and do not clash with the metamodels. +5. Generates a project following the [Methodologist Template](https://github.com/vitruv-tools/Methodologist-Template) + (`model`, `consistency`, `vsum`, and `viewtype` if there are view definitions), with a smoke test that + creates and reloads the VSUM, compiles the constraints, and creates a view of every NeoJoin view type. +6. Runs `mvn clean verify`. The generated VSUM registers the VitruvOCL constraints at the virtual model, so its Vitruv server lists, validates, and manages them under `/vsum/constraints`, and validates them after every change propagation. +Each view definition becomes a view type, generated by [NeoJoin for Vitruvius](https://github.com/vitruv-tools/NeoJoin-for-Vitruvius) +and named after the file (`components.nj` → `Components`; `_`, `-`, and spaces are removed and the +following letter is upper case). The Vitruv server lists it next to the view types of the metamodels under +`/vsum/view/types` and creates views of it under `/vsum/view`. Changes in these views are propagated back +to the models where NeoJoin can invert the query, e.g. for plain attribute projections. + Invalid inputs are rejected with `400` before Maven runs (`VSUM_INPUT_ERROR`, `VSUM_METAMODEL_ERROR`, -`VSUM_REACTIONS_ERROR`). Failed Maven builds are classified by their output, so that only problems of the +`VSUM_REACTIONS_ERROR`, `VSUM_VIEWS_ERROR`). Failed Maven builds are classified by their output, so that only problems of the uploads are reported as such: | Status | Error code | Cause | |--------|--------------------------|-------------------------------------------------------------------------------------------| -| `422` | `VSUM_BUILD_FAILED` | The uploaded metamodels, reactions, or constraints do not compile, or the smoke test fails | +| `422` | `VSUM_BUILD_FAILED` | The uploaded metamodels, reactions, constraints, or views do not compile, or the smoke test fails | | `503` | `VSUM_BUILD_UNAVAILABLE` | The build environment failed (dependency download, disk space, memory); retried once first | | `500` | `VSUM_INTERNAL_ERROR` | Code the service generates itself does not build, or the library versions are incompatible | | `504` | `VSUM_BUILD_TIMEOUT` | The build exceeded `setup.vsum.build-timeout`; the message names the module being built | @@ -171,8 +182,9 @@ contains the same as readable text: `line`, `column`, `excerpt`, `hint`, and `hiddenFollowUpErrors` are omitted when unknown. Errors that only follow from another one, e.g. everything after a syntax error in the same reactions file, are not listed but counted in `hiddenFollowUpErrors`. Problems are reported for metamodels and reactions rejected before -the build, for Reactions compiler and Java compiler errors, and for failures of the smoke test (constraints -that cannot be evaluated, exceptions in reactions or routines while creating the VSUM). +the build, for view definitions rejected before the build, for Reactions, NeoJoin, and Java compiler +errors, and for failures of the smoke test (constraints that cannot be evaluated, exceptions in reactions +or routines while creating the VSUM, view types that cannot be created). ### Validate VSUM @@ -247,7 +259,7 @@ later startup once older than `setup.vsum.workspace-retention`. Build settings are configured with `setup.vsum.*` properties (see `VsumBuildProperties`), e.g. `setup.vsum.build-timeout`, `setup.vsum.max-concurrent-builds`, `setup.vsum.maven-arguments`, `setup.vsum.maven-repository`, `setup.vsum.offline`, `setup.vsum.maven-opts` (the builds' JVM options; -the service's `JAVA_TOOL_OPTIONS` are not passed on), the Vitruvius/VitruvOCL versions, and +the service's `JAVA_TOOL_OPTIONS` are not passed on), the Vitruvius/VitruvOCL/NeoJoin versions, and `setup.vsum.keep-failed-workspaces` for debugging. Concurrent builds share the local repository with file locking (Maven 3.9+). diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/controller/VsumController.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/controller/VsumController.java index 348d16b..2fd6f5a 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/controller/VsumController.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/controller/VsumController.java @@ -70,7 +70,8 @@ public ResponseEntity buildProject( @Parameter(description = "VitruvOCL constraint files") @RequestPart(value = "constraintFiles", required = false) List constraintFiles, - @Parameter(description = "NeoJoin view definitions (stored, not yet compiled)") + @Parameter( + description = "NeoJoin view definitions (.nj); each becomes a view type of the VSUM") @RequestPart(value = "viewFiles", required = false) List viewFiles) { VsumBuildRequest request = @@ -113,7 +114,8 @@ public ResponseEntity buildJar( @Parameter(description = "VitruvOCL constraint files") @RequestPart(value = "constraintFiles", required = false) List constraintFiles, - @Parameter(description = "NeoJoin view definitions (stored, not yet compiled)") + @Parameter( + description = "NeoJoin view definitions (.nj); each becomes a view type of the VSUM") @RequestPart(value = "viewFiles", required = false) List viewFiles) { VsumBuildRequest request = @@ -159,7 +161,8 @@ public VsumValidationResult validateProject( @Parameter(description = "VitruvOCL constraint files") @RequestPart(value = "constraintFiles", required = false) List constraintFiles, - @Parameter(description = "NeoJoin view definitions") + @Parameter( + description = "NeoJoin view definitions (.nj); each becomes a view type of the VSUM") @RequestPart(value = "viewFiles", required = false) List viewFiles) { VsumBuildRequest request = diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildProperties.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildProperties.java index 3d7e229..9a32205 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildProperties.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildProperties.java @@ -98,6 +98,14 @@ public class VsumBuildProperties { */ private String vitruvoclVersion = "0.1.0-SNAPSHOT"; + /** + * Version of NeoJoin for Vitruvius ({@code tools.vitruv:tools.vitruv.neojoin.vitruv.*}), which + * generates the view types of the view definitions. It has no release yet; pin a timestamped + * snapshot once one is published, so that builds do not change whenever a new snapshot is + * published. + */ + private String neojoinVitruvVersion = "0.1.0-SNAPSHOT"; + /** Version of {@code org.eclipse.emf.common}. */ private String emfCommonVersion = "2.46.0"; 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..cca700c 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 @@ -5,6 +5,7 @@ import java.util.Set; import org.springframework.web.multipart.MultipartFile; import tools.vitruv.methodologist.setup.exception.MethodologistSetupException; +import tools.vitruv.methodologist.setup.vsum.service.views.GeneratedViewType; /** * Everything a methodologist supplies to build a VSUM. @@ -29,6 +30,9 @@ public record VsumBuildRequest( /** File extension of VitruvOCL constraint files. */ public static final String CONSTRAINTS_EXTENSION = ".ocl"; + /** File extension of NeoJoin view definitions. */ + public static final String VIEWS_EXTENSION = GeneratedViewType.EXTENSION; + /** Makes the lists immutable and rejects {@code null} lists. */ public VsumBuildRequest { metamodels = List.copyOf(metamodels); @@ -60,7 +64,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/VsumBuildWarmup.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildWarmup.java index eef5480..1c21817 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildWarmup.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildWarmup.java @@ -90,7 +90,8 @@ boolean warmUp() { /** * The sample project: the two metamodels, reactions, and constraints of the Methodologist - * Template, which together need every dependency a generated project can have. + * Template and a NeoJoin view definition, which together need every dependency a generated + * project can have. * * @return the build request of the sample project */ @@ -99,7 +100,7 @@ static VsumBuildRequest sampleRequest() { List.of(sample("model.ecore"), sample("model2.ecore")), List.of(sample("templateReactions.reactions")), List.of(sample("constraints.ocl")), - List.of()); + List.of(sample("components.nj"))); } private static UploadedFile sample(String name) { diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumErrorCodes.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumErrorCodes.java index 333ba0c..d38e104 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumErrorCodes.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumErrorCodes.java @@ -12,9 +12,12 @@ public final class VsumErrorCodes { /** An uploaded reactions file does not fit the uploaded metamodels. */ public static final String REACTIONS_ERROR = "VSUM_REACTIONS_ERROR"; + /** An uploaded view definition is invalid or does not fit the uploaded metamodels. */ + public static final String VIEWS_ERROR = "VSUM_VIEWS_ERROR"; + /** - * The Maven build rejected the uploaded files: the metamodels, reactions, or constraints do not - * compile, or the smoke test failed. + * The Maven build rejected the uploaded files: the metamodels, reactions, constraints, or views + * do not compile, or the smoke test failed. */ public static final String BUILD_FAILED = "VSUM_BUILD_FAILED"; 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..effef4c 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.GeneratedViewType; import tools.vitruv.methodologist.setup.vsum.service.views.ViewDefinitionProcessor; /** @@ -131,15 +132,18 @@ ProjectSources generateProject(VsumBuildRequest request, Path projectRoot) throw reactionsProcessor.process(request.reactions(), metamodels, projectRoot); List constraintResources = constraintsProcessor.process(request.constraints(), projectRoot); - viewDefinitionProcessor.process(request.viewDefinitions(), metamodels, projectRoot); - projectGenerator.generate(projectRoot, metamodels, specifications, constraintResources); - return sources(request, metamodels, constraintResources, projectRoot); + List viewTypes = + viewDefinitionProcessor.process(request.viewDefinitions(), metamodels, projectRoot); + projectGenerator.generate( + projectRoot, metamodels, specifications, constraintResources, viewTypes); + return sources(request, metamodels, constraintResources, viewTypes, projectRoot); } private static ProjectSources sources( VsumBuildRequest request, List metamodels, List constraintResources, + List viewTypes, Path projectRoot) { ProjectSources sources = new ProjectSources(projectRoot); // the metamodel processor returns one entry per upload, in upload order @@ -178,12 +182,16 @@ private static ProjectSources sources( null); sources.addConstraintResource(constraintResources.get(i), file); } - for (UploadedFile view : request.viewDefinitions()) { - sources.add( - Source.VIEWS, - ProjectLayout.viewsDirectory(projectRoot).resolve(view.fileName()), - view, - null); + // the view definition processor returns one entry per upload, in upload order + for (int i = 0; i < viewTypes.size() && i < request.viewDefinitions().size(); i++) { + UploadedFile view = request.viewDefinitions().get(i); + SourceFile file = + sources.add( + Source.VIEWS, + ProjectLayout.viewsDirectory(projectRoot).resolve(view.fileName()), + view, + null); + sources.addView(viewTypes.get(i).exportName(), viewTypes.get(i).name(), file); } return sources; } 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..695edd3 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 @@ -8,6 +8,7 @@ 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.ViewDefinitionProcessor; /** * Checks a VSUM project without building it, so that problems can be shown while it is edited. @@ -23,10 +24,11 @@ public class VsumValidationService { private final MetamodelProcessor metamodelProcessor; private final ReactionsProcessor reactionsProcessor; + private final ViewDefinitionProcessor viewDefinitionProcessor; /** * Checks the project. Like the build, the checks stop at the first stage with problems: reactions - * are only checked once the metamodels are valid. + * 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,6 +37,7 @@ public VsumValidationResult validate(VsumBuildRequest request) { try { List metamodels = metamodelProcessor.check(request.metamodels()); reactionsProcessor.check(request.reactions(), metamodels); + viewDefinitionProcessor.check(request.viewDefinitions(), metamodels); return VsumValidationResult.of(List.of()); } catch (VsumBuildException e) { log.debug("VSUM validation found problems: {}", e.getMessage()); diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/BuildOutputParser.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/BuildOutputParser.java index ab70002..96d3c30 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/BuildOutputParser.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/BuildOutputParser.java @@ -19,14 +19,15 @@ import tools.vitruv.methodologist.setup.vsum.service.problem.BuildProblem.Source; import tools.vitruv.methodologist.setup.vsum.service.problem.ProjectSources.SourceFile; import tools.vitruv.methodologist.setup.vsum.service.project.ProjectLayout; +import tools.vitruv.methodologist.setup.vsum.service.views.GeneratedViewType; /** * Turns the output of a failed Maven build into problems attributed to the uploaded files. * - *

Recognizes Reactions compiler (Xtext) errors, javac errors in code generated from the - * metamodels or reactions, and failures of the generated smoke test; anything else is reported for - * the module that failed. Errors that only follow from another one are hidden (see {@link - * FollowUpErrors}). + *

Recognizes Reactions and NeoJoin compiler (Xtext) errors, javac errors in code generated from + * the metamodels, reactions, or view definitions, and failures of the generated smoke test; + * anything else is reported for the module that failed. Errors that only follow from another one + * are hidden (see {@link FollowUpErrors}). */ @Slf4j public final class BuildOutputParser { @@ -47,6 +48,12 @@ public final class BuildOutputParser { "\\bat (" + Pattern.quote(ProjectLayout.MODEL_BASE_PACKAGE) + "\\.[\\w.$]+)\\.[\\w$]+\\("); + private static final Pattern GENERATED_VIEW_CODE = Pattern.compile("/neojoin/viewtypes/([^/]+)/"); + private static final Pattern VIEW_FRAME = + Pattern.compile("\\bat neojoin\\.viewtypes\\.(\\w+)\\."); + private static final Pattern NEOJOIN_FRAME = Pattern.compile("\\bat tools\\.vitruv\\.neojoin\\."); + private static final Pattern VIEW_TYPE_MESSAGE = + Pattern.compile("(?:registers the view type|a view of the view type) (\\w+)"); private static final Pattern CONSTRAINTS_MESSAGE = Pattern.compile("Constraints in (\\S+) cannot be evaluated:\\n", Pattern.DOTALL); private static final Pattern INVARIANT = Pattern.compile("\\binv\\s+(\\w+)"); @@ -101,7 +108,8 @@ private static BuildProblem xtextProblem(Matcher xtext, ProjectSources sources) int column = Integer.parseInt(xtext.group(4)); Optional file = sources.fileAt(Path.of(xtext.group(2))); if (file.isEmpty()) { - return BuildProblem.of(Source.REACTIONS, null, message); + boolean view = xtext.group(2).endsWith(GeneratedViewType.EXTENSION); + return BuildProblem.of(view ? Source.VIEWS : Source.REACTIONS, null, message); } SourceFile source = file.get(); int uploadedLine = source.uploadedLine(line); @@ -147,6 +155,18 @@ private static BuildProblem javacProblem( "Check the Java expressions in the reactions' update and match blocks, e.g. the" + " types of the values that are assigned or compared"); } + if (module.equals(ProjectLayout.VIEWTYPE_MODULE)) { + Matcher export = GENERATED_VIEW_CODE.matcher(unixPath); + Optional view = + export.find() ? sources.viewOf(export.group(1)) : Optional.empty(); + return BuildProblem.of( + Source.VIEWS, + view.map(SourceFile::fileName).orElse(null), + "the Java code generated from the view definition does not compile: " + message) + .withHint( + "Check the Java expressions in the view definition, e.g. the types of the values" + + " that are assigned or compared"); + } return BuildProblem.of( Source.INTERNAL, null, "generated code does not compile: " + relative + ": " + message); } @@ -243,8 +263,9 @@ private static List smokeTestProblems(Path report, ProjectSources } /** - * Attributes a failure of the smoke test: constraints that cannot be evaluated, or an exception - * while creating the VSUM, located by the generated reactions or metamodel code on its stack. + * Attributes a failure of the smoke test: constraints that cannot be evaluated, view types that + * cannot be created, or an exception while creating the VSUM, located by the generated reactions, + * view type, or metamodel code on its stack. */ static List smokeTestProblems( String type, String message, String stackTrace, ProjectSources sources) { @@ -271,6 +292,24 @@ static List smokeTestProblems( return List.of(BuildProblem.of(Source.REACTIONS, null, text)); } + Matcher viewFrame = VIEW_FRAME.matcher(stackTrace); + Matcher viewTypeMessage = VIEW_TYPE_MESSAGE.matcher(message); + boolean inGeneratedViewType = viewFrame.find(); + boolean aboutViewType = viewTypeMessage.find(); + if (inGeneratedViewType || aboutViewType || NEOJOIN_FRAME.matcher(stackTrace).find()) { + Optional file = Optional.empty(); + if (inGeneratedViewType) { + file = sources.viewOf(viewFrame.group(1)); + } else if (aboutViewType) { + file = sources.viewNamed(viewTypeMessage.group(1)); + } + return List.of( + BuildProblem.of( + Source.VIEWS, + file.map(SourceFile::fileName).orElse(null), + "creating the views failed: " + exception)); + } + Matcher modelFrame = MODEL_FRAME.matcher(stackTrace); if (modelFrame.find()) { Optional file = sources.metamodelOf(modelFrame.group(1)); @@ -400,6 +439,9 @@ private static Source failedModuleSource(List output) { if (module.equals(ProjectLayout.CONSISTENCY_ARTIFACT_ID)) { return Source.REACTIONS; } + if (module.equals(ProjectLayout.VIEWTYPE_ARTIFACT_ID)) { + return Source.VIEWS; + } return Source.INTERNAL; } } diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/ProjectSources.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/ProjectSources.java index 679db53..c4677c2 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/ProjectSources.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/ProjectSources.java @@ -20,6 +20,8 @@ public final class ProjectSources { private final Map reactionsBySegment = new HashMap<>(); private final Map metamodelsByJavaPackage = new LinkedHashMap<>(); private final Map constraintsByResource = new HashMap<>(); + private final Map viewsByExport = new HashMap<>(); + private final Map viewsByName = new HashMap<>(); /** * Creates an empty mapping. @@ -101,6 +103,19 @@ public void addConstraintResource(String resource, SourceFile file) { constraintsByResource.put(resource, file); } + /** + * Records the view definition of a view type. + * + * @param exportName the exported package, into which NeoJoin generates the view type, e.g. {@code + * components} for the generated package {@code neojoin.viewtypes.components} + * @param viewTypeName the name of the view type + * @param file the view definition + */ + public void addView(String exportName, String viewTypeName, SourceFile file) { + viewsByExport.put(exportName, file); + viewsByName.put(viewTypeName, file); + } + /** * Returns the root of the generated project. * @@ -157,6 +172,26 @@ public Optional constraintsOf(String resource) { return Optional.ofNullable(constraintsByResource.get(resource)); } + /** + * Returns the view definition that exports a package. + * + * @param exportName the exported package + * @return the view definition, if known + */ + public Optional viewOf(String exportName) { + return Optional.ofNullable(viewsByExport.get(exportName)); + } + + /** + * Returns the view definition of a view type. + * + * @param viewTypeName the name of the view type + * @return the view definition, if known + */ + public Optional viewNamed(String viewTypeName) { + return Optional.ofNullable(viewsByName.get(viewTypeName)); + } + /** * Replaces paths into the project by upload names or project-relative paths, so that messages do * not expose the temporary workspace. diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/project/ProjectGenerator.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/project/ProjectGenerator.java index 4397d43..bb10115 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/project/ProjectGenerator.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/project/ProjectGenerator.java @@ -18,10 +18,12 @@ import org.springframework.stereotype.Service; import tools.vitruv.methodologist.setup.vsum.service.VsumBuildProperties; import tools.vitruv.methodologist.setup.vsum.service.metamodel.GeneratedMetamodel; +import tools.vitruv.methodologist.setup.vsum.service.views.GeneratedViewType; /** - * Renders the Maven project around the processed metamodels, reactions, and constraints, following - * the layout of the Methodologist Template. + * Renders the Maven project around the processed metamodels, reactions, constraints, and view + * definitions, following the layout of the Methodologist Template. The view type module is only + * generated if there are view definitions, so projects without views build as before. */ @Service @RequiredArgsConstructor @@ -40,16 +42,18 @@ public class ProjectGenerator { * @param changePropagationSpecifications fully qualified names of the reactions' generated change * propagation specifications * @param constraintResources classpath resources of the constraint files + * @param viewTypes the view types generated from the view definitions * @throws IOException when rendering or writing a file fails */ public void generate( Path projectRoot, List metamodels, List changePropagationSpecifications, - List constraintResources) + List constraintResources, + List viewTypes) throws IOException { Map model = - createModel(metamodels, changePropagationSpecifications, constraintResources); + createModel(metamodels, changePropagationSpecifications, constraintResources, viewTypes); Path modelModule = ProjectLayout.modelModule(projectRoot); render("rootPom.ftl", model, projectRoot.resolve("pom.xml")); @@ -78,6 +82,15 @@ public void generate( vsumModule.resolve( "src/test/java/" + vsumSources + ProjectLayout.VSUM_MAIN_CLASS + "Test.java")); + if (!viewTypes.isEmpty()) { + Path viewtypeModule = ProjectLayout.viewtypeModule(projectRoot); + render("viewtypePom.ftl", model, viewtypeModule.resolve("pom.xml")); + render("viewtypeProject.ftl", model, viewtypeModule.resolve(".project")); + render("viewtypePluginXml.ftl", model, viewtypeModule.resolve("plugin.xml")); + render("viewtypeWorkflow.ftl", model, viewtypeModule.resolve("workflow/generate.mwe2")); + Files.createDirectories(ProjectLayout.viewsDirectory(projectRoot)); + } + Files.createDirectories(ProjectLayout.reactionsDirectory(projectRoot)); Files.createDirectories(ProjectLayout.constraintsDirectory(projectRoot)); } @@ -85,7 +98,8 @@ public void generate( private Map createModel( List metamodels, List changePropagationSpecifications, - List constraintResources) { + List constraintResources, + List viewTypes) { Map model = new HashMap<>(); model.put("groupId", ProjectLayout.GROUP_ID); model.put("rootArtifactId", ProjectLayout.ROOT_ARTIFACT_ID); @@ -93,6 +107,8 @@ private Map createModel( model.put("modelArtifactId", ProjectLayout.MODEL_ARTIFACT_ID); model.put("consistencyArtifactId", ProjectLayout.CONSISTENCY_ARTIFACT_ID); model.put("vsumArtifactId", ProjectLayout.VSUM_ARTIFACT_ID); + model.put("viewtypeArtifactId", ProjectLayout.VIEWTYPE_ARTIFACT_ID); + model.put("generatedNeojoinSources", ProjectLayout.GENERATED_NEOJOIN_SOURCES); model.put("vsumPackage", ProjectLayout.VSUM_PACKAGE); model.put("vsumMainClass", ProjectLayout.VSUM_MAIN_CLASS); model.put("ecoreDirectory", ProjectLayout.ECORE_DIRECTORY); @@ -104,6 +120,7 @@ private Map createModel( model.put("vitruvDslsVersion", properties.getVitruvDslsVersion()); model.put("vitruvServerVersion", properties.getVitruvServerVersion()); model.put("vitruvoclVersion", properties.getVitruvoclVersion()); + model.put("neojoinVitruvVersion", properties.getNeojoinVitruvVersion()); model.put("emfCommonVersion", properties.getEmfCommonVersion()); model.put("emfEcoreVersion", properties.getEmfEcoreVersion()); model.put("junitVersion", properties.getJunitVersion()); @@ -146,6 +163,20 @@ private Map createModel( model.put("changePropagationSpecifications", changePropagationSpecifications); model.put("constraintResources", constraintResources); + model.put( + "viewTypes", + viewTypes.stream() + .map( + viewType -> + Map.of( + "name", viewType.name(), + "fileName", viewType.fileName(), + "exportName", viewType.exportName(), + "nsUri", viewType.nsUri(), + "viewTypeClass", viewType.viewTypeClass(), + "packageInterface", viewType.packageInterface(), + "genmodelPath", viewType.genmodelPath())) + .toList()); return model; } diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/project/ProjectLayout.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/project/ProjectLayout.java index 4df1192..740ae3e 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/project/ProjectLayout.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/project/ProjectLayout.java @@ -31,6 +31,12 @@ public final class ProjectLayout { /** Artifact id of the VSUM module. */ public static final String VSUM_ARTIFACT_ID = ROOT_ARTIFACT_ID + ".vsum"; + /** + * Artifact id of the view type module, which is only generated if NeoJoin view definitions are + * uploaded. It is also the Eclipse project name its MWE2 workflow resolves against. + */ + public static final String VIEWTYPE_ARTIFACT_ID = ROOT_ARTIFACT_ID + ".viewtype"; + /** Base package under which EMF generates the metamodel code. */ public static final String MODEL_BASE_PACKAGE = MODEL_ARTIFACT_ID; @@ -60,6 +66,15 @@ public final class ProjectLayout { /** Directory of the consistency module. */ public static final String CONSISTENCY_MODULE = "consistency"; + /** Directory of the view type module. */ + public static final String VIEWTYPE_MODULE = "viewtype"; + + /** + * Directory receiving the view types, metamodels, and genmodels NeoJoin generates from the view + * definitions, relative to the view type module. + */ + public static final String GENERATED_NEOJOIN_SOURCES = "target/generated-sources/neojoin"; + private ProjectLayout() { throw new UnsupportedOperationException("This is a utility class and cannot be instantiated"); } @@ -120,13 +135,24 @@ public static Path constraintsDirectory(Path root) { } /** - * Returns the directory holding view definitions. + * Returns the view type module directory. + * + * @param root project root + * @return the view type module directory + */ + public static Path viewtypeModule(Path root) { + return root.resolve(VIEWTYPE_MODULE); + } + + /** + * Returns the directory holding the NeoJoin view definitions. The view type module compiles each + * of them into a view type. * * @param root project root * @return the view definitions directory */ public static Path viewsDirectory(Path root) { - return root.resolve("views/src/main/neojoin"); + return viewtypeModule(root).resolve("src/main/neojoin"); } /** diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/views/GeneratedViewType.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/views/GeneratedViewType.java new file mode 100644 index 0000000..afbaae1 --- /dev/null +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/views/GeneratedViewType.java @@ -0,0 +1,95 @@ +package tools.vitruv.methodologist.setup.vsum.service.views; + +import java.util.Locale; + +/** + * A view type that NeoJoin for Vitruvius generates from an uploaded view definition. The names + * mirror its code generator ({@code NeoJoinVitruvGenerator}, {@code ViewTypeSourceGenerator}, and + * {@code NamingGenerator}), so that the generated project can refer to the generated classes. + * + * @param fileName the uploaded {@code .nj} file + * @param name the name of the view type, under which the Vitruv server offers it + * @param exportName the package the view definition exports its view metamodel to + * @param nsUri the nsURI of the view metamodel + * @param viewTypeClass the fully qualified name of the generated view type class + * @param packageInterface the fully qualified name of the generated view metamodel package + * @param genmodelPath the generated genmodel, relative to the view type module + */ +public record GeneratedViewType( + String fileName, + String name, + String exportName, + String nsUri, + String viewTypeClass, + String packageInterface, + String genmodelPath) { + + /** Base package of the generated view types ({@code NamingGenerator.PACKAGE_BASE}). */ + public static final String PACKAGE_BASE = "neojoin.viewtypes"; + + /** File extension of NeoJoin view definitions. */ + public static final String EXTENSION = ".nj"; + + /** Delimiters NeoJoin removes when turning names into class names. */ + private static final String DELIMITERS = "_ -"; + + /** + * Describes the view type generated from a view definition. + * + * @param fileName the uploaded {@code .nj} file + * @param exportName the package declared by {@code export to ""} + * @param nsUri the nsURI declared by the export + * @param generatedSources the directory NeoJoin generates into, relative to the module + * @return the view type + */ + public static GeneratedViewType of( + String fileName, String exportName, String nsUri, String generatedSources) { + String baseName = baseName(fileName); + String name = pascalCase(baseName); + String javaPackage = PACKAGE_BASE + "." + exportName; + return new GeneratedViewType( + fileName, + name, + exportName, + nsUri, + javaPackage + "." + name + "ViewType", + javaPackage + "." + pascalCase(exportName) + "Package", + generatedSources + "/ecore/" + exportName + "/" + baseName + ".genmodel"); + } + + /** + * Returns the file name without the {@code .nj} extension; NeoJoin derives the view type name + * from it. + * + * @param fileName the file name + * @return the base name + */ + static String baseName(String fileName) { + return fileName.toLowerCase(Locale.ROOT).endsWith(EXTENSION) + ? fileName.substring(0, fileName.length() - EXTENSION.length()) + : fileName; + } + + /** + * Converts a name like NeoJoin does ({@code CaseUtils.toCamelCase(name, true, '_', ' ', '-')}): + * the delimiters are removed, the letter after each of them and the first letter are upper case, + * and all other letters are lower case, e.g. {@code my_View-2} → {@code MyView2}. + * + * @param name the name + * @return the converted name + */ + static String pascalCase(String name) { + StringBuilder result = new StringBuilder(name.length()); + boolean capitalizeNext = true; + for (char character : name.toLowerCase(Locale.ROOT).toCharArray()) { + if (DELIMITERS.indexOf(character) >= 0) { + capitalizeNext = true; + } else { + boolean capitalize = capitalizeNext || result.length() == 0; + result.append(capitalize ? Character.toUpperCase(character) : character); + capitalizeNext = false; + } + } + return result.toString(); + } +} diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/views/NeoJoinViewDefinitionProcessor.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/views/NeoJoinViewDefinitionProcessor.java index ab9b47d..25c5c1e 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/views/NeoJoinViewDefinitionProcessor.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/views/NeoJoinViewDefinitionProcessor.java @@ -3,38 +3,213 @@ 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.LinkedHashSet; import java.util.List; -import lombok.extern.slf4j.Slf4j; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.emf.ecore.EcorePackage; 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.methodologist.setup.vsum.service.project.ProjectLayout; +import tools.vitruv.methodologist.setup.vsum.service.reactions.ReactionsProcessor; /** - * Stub for NeoJoin view definitions. + * Places NeoJoin view definitions into the view type module of the generated project, where NeoJoin + * for Vitruvius generates a view type from each of them during the build. The generated VSUM + * registers these view types next to the identity view types of the metamodels. * - *

NeoJoin views are not compiled into the VSUM yet. The definitions are stored in the generated - * project under {@code views/src/main/neojoin} so they are part of the returned project, but they - * do not affect the build. Replace this implementation once NeoJoin integration is available. + *

Before the build, the definitions are checked for what would only fail late or confusingly: + * the export declaration that names the generated classes, names that clash, and imports of + * metamodels that were not uploaded. Everything else is left to the NeoJoin compiler, whose errors + * the build attributes to the definitions. */ -@Slf4j @Service public class NeoJoinViewDefinitionProcessor implements ViewDefinitionProcessor { + private static final Pattern FILE_BASE_NAME = Pattern.compile("[A-Za-z][A-Za-z0-9_-]*"); + private static final Pattern EXPORT = + Pattern.compile("\\bexport\\s+\\^?([A-Za-z_][A-Za-z0-9_]*)\\s+to\\s+\"([^\"]*)\""); + private static final Pattern IMPORT = Pattern.compile("\\bimport\\s+\"([^\"]+)\""); + @Override - public void process( + public List process( List viewDefinitions, List metamodels, Path projectRoot) throws IOException { + List viewTypes = check(viewDefinitions, metamodels); if (viewDefinitions.isEmpty()) { - return; + return viewTypes; } Path directory = ProjectLayout.viewsDirectory(projectRoot); Files.createDirectories(directory); for (UploadedFile file : viewDefinitions) { Files.write(directory.resolve(file.fileName()), file.content()); } - log.warn( - "NeoJoin view definitions are not supported yet; {} file(s) were stored but not compiled", - viewDefinitions.size()); + return viewTypes; + } + + @Override + public List check( + List viewDefinitions, List metamodels) { + Set metamodelNsUris = new LinkedHashSet<>(); + metamodels.forEach( + metamodel -> { + metamodelNsUris.add(metamodel.nsUri()); + metamodel.packages().forEach(pkg -> metamodelNsUris.add(pkg.nsUri())); + }); + Set identityViewTypes = new LinkedHashSet<>(); + metamodels.forEach(metamodel -> identityViewTypes.add(metamodel.name())); + + List problems = new ArrayList<>(); + List viewTypes = new ArrayList<>(); + Map nameOwners = new HashMap<>(); + Map exportOwners = new HashMap<>(); + Map nsUriOwners = new HashMap<>(); + + for (UploadedFile file : viewDefinitions) { + String text = file.text(); + String source = ReactionsProcessor.stripComments(text); + problems.addAll(checkImports(file, source, metamodelNsUris)); + + String baseName = GeneratedViewType.baseName(file.fileName()); + if (!FILE_BASE_NAME.matcher(baseName).matches()) { + problems.add( + BuildProblem.of( + Source.VIEWS, + file.fileName(), + "the file name cannot be the name of a view type") + .withHint( + "NeoJoin names the view type after the file; start the file name with a letter" + + " and use only letters, digits, '_', and '-', e.g. 'components.nj'")); + continue; + } + + Matcher export = EXPORT.matcher(source); + if (!export.find()) { + problems.add( + BuildProblem.of(Source.VIEWS, file.fileName(), "declares no export") + .withHint( + "Start the view definition with 'export to \"\"', which names" + + " the package and nsURI of the view's metamodel")); + continue; + } + GeneratedViewType viewType = + GeneratedViewType.of( + file.fileName(), + export.group(1), + export.group(2), + ProjectLayout.GENERATED_NEOJOIN_SOURCES); + int exportOffset = export.start(); + int count = problems.size(); + + if (identityViewTypes.contains(viewType.name())) { + problems.add( + problem( + file, + exportOffset, + String.format( + "the view type '%s' has the same name as the view type of the metamodel" + + " '%s'", + viewType.name(), viewType.name())) + .withHint("Rename the file; NeoJoin names the view type after it")); + } + String nameOwner = nameOwners.putIfAbsent(viewType.name(), file.fileName()); + if (nameOwner != null) { + problems.add( + problem( + file, + exportOffset, + String.format( + "the view type '%s' is already defined by %s", viewType.name(), nameOwner)) + .withHint( + "View types are named after the file, ignoring case, '_', '-', and spaces;" + + " rename one of the files")); + } + String exportOwner = + exportOwners.putIfAbsent(viewType.exportName().toLowerCase(Locale.ROOT), file.fileName()); + if (exportOwner != null) { + problems.add( + problem( + file, + export.start(1), + String.format( + "the export '%s' is already declared in %s", + viewType.exportName(), exportOwner)) + .withHint("Each view definition needs its own export name")); + } + if (metamodelNsUris.contains(viewType.nsUri())) { + problems.add( + problem( + file, + export.start(2) - 1, + String.format( + "exports to '%s', which is the nsURI of an uploaded metamodel", + viewType.nsUri())) + .withHint("Export the view's metamodel to an nsURI of its own")); + } else { + String nsUriOwner = nsUriOwners.putIfAbsent(viewType.nsUri(), file.fileName()); + if (nsUriOwner != null) { + problems.add( + problem( + file, + export.start(2) - 1, + String.format( + "exports to '%s', which %s exports to as well", + viewType.nsUri(), nsUriOwner)) + .withHint("Each view definition needs its own export nsURI")); + } + } + if (problems.size() == count) { + viewTypes.add(viewType); + } + } + + if (!problems.isEmpty()) { + throw new VsumBuildException( + VsumErrorCodes.VIEWS_ERROR, "The uploaded view definitions are invalid:", problems); + } + return viewTypes; + } + + private static List checkImports( + UploadedFile file, String source, Set metamodelNsUris) { + List problems = new ArrayList<>(); + Matcher imports = IMPORT.matcher(source); + while (imports.find()) { + String nsUri = imports.group(1); + if (!metamodelNsUris.contains(nsUri) && !EcorePackage.eNS_URI.equals(nsUri)) { + problems.add( + problem( + file, + imports.start(1) - 1, + String.format( + "imports '%s', which is not the nsURI of an uploaded metamodel", nsUri)) + .withHint( + "Import a metamodel by its nsURI; the uploaded metamodels have: " + + String.join(", ", metamodelNsUris))); + } + } + return problems; + } + + private static BuildProblem problem(UploadedFile file, int offset, String message) { + String text = file.text(); + return BuildProblem.at( + Source.VIEWS, + file.fileName(), + text, + Excerpts.lineOf(text, offset), + Excerpts.columnOf(text, offset), + message); } } diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/views/ViewDefinitionProcessor.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/views/ViewDefinitionProcessor.java index aecad2a..2dc73d0 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/views/ViewDefinitionProcessor.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/views/ViewDefinitionProcessor.java @@ -5,19 +5,33 @@ import java.util.List; import tools.vitruv.methodologist.setup.vsum.service.UploadedFile; import tools.vitruv.methodologist.setup.vsum.service.metamodel.GeneratedMetamodel; +import tools.vitruv.methodologist.setup.vsum.service.problem.VsumBuildException; /** Integrates view definitions into the generated VSUM project. */ public interface ViewDefinitionProcessor { /** - * Adds the view definitions to the generated project. + * Checks the view definitions and adds them to the generated project. * * @param viewDefinitions uploaded view definition files * @param metamodels the processed metamodels the views are defined on * @param projectRoot root of the generated project + * @return the view types generated from the view definitions, in upload order + * @throws VsumBuildException when a view definition is invalid * @throws IOException when writing to the project fails */ - void process( + List process( List viewDefinitions, List metamodels, Path projectRoot) throws IOException; + + /** + * Runs the same checks as {@link #process(List, List, Path)} without writing anything. + * + * @param viewDefinitions uploaded view definition files + * @param metamodels the checked metamodels the views are defined on + * @return the view types generated from the view definitions, in upload order + * @throws VsumBuildException when a view definition is invalid + */ + List check( + List viewDefinitions, List metamodels); } diff --git a/src/main/resources/templates/vsum/rootPom.ftl b/src/main/resources/templates/vsum/rootPom.ftl index 6bcea88..4103cb8 100644 --- a/src/main/resources/templates/vsum/rootPom.ftl +++ b/src/main/resources/templates/vsum/rootPom.ftl @@ -25,6 +25,10 @@ model consistency vsum +<#if viewTypes?has_content> + + viewtype + @@ -34,6 +38,8 @@ [=vitruvDslsVersion] [=vitruvServerVersion] [=vitruvoclVersion] + + [=neojoinVitruvVersion] @@ -95,6 +101,17 @@ tools.vitruv.vitruvocl.language ${vitruvocl.version} + + + tools.vitruv + tools.vitruv.neojoin.vitruv.views + ${neojoin.vitruv.version} + + + tools.vitruv + tools.vitruv.neojoin.vitruv.change + ${neojoin.vitruv.version} + diff --git a/src/main/resources/templates/vsum/viewtypePluginXml.ftl b/src/main/resources/templates/vsum/viewtypePluginXml.ftl new file mode 100644 index 0000000..5286f6a --- /dev/null +++ b/src/main/resources/templates/vsum/viewtypePluginXml.ftl @@ -0,0 +1,16 @@ + + + + +<#list viewTypes as viewType> + + + + + + + + diff --git a/src/main/resources/templates/vsum/viewtypePom.ftl b/src/main/resources/templates/vsum/viewtypePom.ftl new file mode 100644 index 0000000..c17c1f9 --- /dev/null +++ b/src/main/resources/templates/vsum/viewtypePom.ftl @@ -0,0 +1,157 @@ + + + + 4.0.0 + + + [=groupId] + [=rootArtifactId] + [=version] + + + [=viewtypeArtifactId] + + Viewtype + View types generated from the NeoJoin view definitions in src/main/neojoin + + + + + ${project.groupId} + [=modelArtifactId] + ${project.version} + + + + + tools.vitruv + tools.vitruv.neojoin.vitruv.views + + + tools.vitruv + tools.vitruv.neojoin.vitruv.change + + + + + tools.vitruv + tools.vitruv.change.atomic + + + tools.vitruv + tools.vitruv.change.composite + + + tools.vitruv + tools.vitruv.framework.views + + + + + org.eclipse.emf + org.eclipse.emf.ecore + + + + + + + + ${project.basedir}/[=generatedNeojoinSources]/ecore + [=generatedNeojoinSources]/ecore + + **/*.ecore + **/*.genmodel + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-source-neojoin + generate-sources + + add-source + + + + ${project.basedir}/src/main/neojoin + ${project.basedir}/[=generatedNeojoinSources] + + + + + + + + org.eclipse.xtext + xtext-maven-plugin + + + + ${project.artifactId} + ${project.basedir} + + + + + tools.vitruv.neojoin.vitruv.generator.NeoJoinVitruvBuildSetup + + + ${project.basedir}/[=generatedNeojoinSources] + + + + + + + + tools.vitruv + tools.vitruv.neojoin.vitruv.generator + ${neojoin.vitruv.version} + + + tools.vitruv + tools.vitruv.neojoin.vitruv.views + ${neojoin.vitruv.version} + + + tools.vitruv + tools.vitruv.neojoin.vitruv.change + ${neojoin.vitruv.version} + + + + ${project.groupId} + [=modelArtifactId] + ${project.version} + + + + + + org.codehaus.mojo + exec-maven-plugin + + + execute-mwe2-generate + generate-sources + + + + + tools.vitruv + tools.vitruv.neojoin.vitruv.generator + ${neojoin.vitruv.version} + + + + + + diff --git a/src/main/resources/templates/vsum/viewtypeProject.ftl b/src/main/resources/templates/vsum/viewtypeProject.ftl new file mode 100644 index 0000000..a136ed3 --- /dev/null +++ b/src/main/resources/templates/vsum/viewtypeProject.ftl @@ -0,0 +1,18 @@ + + + [=viewtypeArtifactId] + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.jdt.core.javanature + + diff --git a/src/main/resources/templates/vsum/viewtypeWorkflow.ftl b/src/main/resources/templates/vsum/viewtypeWorkflow.ftl new file mode 100644 index 0000000..18f1b19 --- /dev/null +++ b/src/main/resources/templates/vsum/viewtypeWorkflow.ftl @@ -0,0 +1,22 @@ +module [=viewtypeArtifactId] + +import tools.vitruv.neojoin.vitruv.generator.AggregateEcoreGenerator +import org.eclipse.emf.mwe.utils.StandaloneSetup + +var workspaceRoot = ".." + +Workflow { + + bean = StandaloneSetup { + scanClassPath = true + platformUri = workspaceRoot + } + + // generates the code of all view metamodels NeoJoin generated from the view definitions + component = AggregateEcoreGenerator { + genModels = "platform:/resource/[=viewtypeArtifactId]/[=generatedNeojoinSources]/ecore" + srcPath = "platform:/resource/[=viewtypeArtifactId]/target/generated-sources/ecore" + generateCustomClasses = false + } + +} diff --git a/src/main/resources/templates/vsum/vsumMain.ftl b/src/main/resources/templates/vsum/vsumMain.ftl index 03f2623..df6405c 100644 --- a/src/main/resources/templates/vsum/vsumMain.ftl +++ b/src/main/resources/templates/vsum/vsumMain.ftl @@ -48,6 +48,10 @@ public class [=vsumMainClass] { /** Storage folder of the VSUM. */ static final Path STORAGE_FOLDER = Path.of("vsumexample").toAbsolutePath(); + /** Names of the view types generated from the NeoJoin view definitions of this VSUM. */ + static final List NEOJOIN_VIEW_TYPES = List.of(<#list viewTypes as viewType> + [=viewType.viewTypeClass].NAME<#sep>,); + /** Classpath resources containing the VitruvOCL constraints of this VSUM. */ static final List CONSTRAINT_RESOURCES = List.of(<#list constraintResources as resource> "[=resource]"<#sep>,); @@ -96,6 +100,10 @@ public class [=vsumMainClass] { new TestUserInteraction.ResultProvider(new TestUserInteraction())) .withChangePropagationSpecifications(createChangePropagationSpecifications()) .withViewTypes(createViewTypes()) +<#list viewTypes as viewType> + // view type generated from [=viewType.fileName] + .withViewType([=viewType.viewTypeClass]::new) + <#if constraintResources?has_content> // the Vitruv server lists, validates and manages the constraints via REST .withConstraintChecker(createConstraintChecker()) @@ -135,6 +143,12 @@ public class [=vsumMainClass] { return specifications; } + /** + * Creates the identity view types of the metamodels. The view types generated from the NeoJoin + * view definitions are added separately, because they need the VSUM as their view type provider. + * + * @return the identity view types + */ static Collection> createViewTypes() { List> viewTypes = new ArrayList<>(); <#list metamodels as metamodel> diff --git a/src/main/resources/templates/vsum/vsumPom.ftl b/src/main/resources/templates/vsum/vsumPom.ftl index b25b268..dfaa010 100644 --- a/src/main/resources/templates/vsum/vsumPom.ftl +++ b/src/main/resources/templates/vsum/vsumPom.ftl @@ -57,6 +57,14 @@ [=consistencyArtifactId] ${project.version} +<#if viewTypes?has_content> + + + ${project.groupId} + [=viewtypeArtifactId] + ${project.version} + + <#if constraintResources?has_content> diff --git a/src/main/resources/templates/vsum/vsumTest.ftl b/src/main/resources/templates/vsum/vsumTest.ftl index 17b1417..e3562d7 100644 --- a/src/main/resources/templates/vsum/vsumTest.ftl +++ b/src/main/resources/templates/vsum/vsumTest.ftl @@ -4,24 +4,29 @@ import java.io.IOException; import java.nio.file.Path; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +<#if constraintResources?has_content || viewTypes?has_content> +import org.junit.jupiter.api.Assertions; +import tools.vitruv.framework.vsum.internal.InternalVirtualModel; + <#if constraintResources?has_content> import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.List; import java.util.stream.Collectors; -import org.junit.jupiter.api.Assertions; import tools.vitruv.dsls.vitruvocl.vitruv.VitruvOclConstraintChecker; import tools.vitruv.framework.vsum.constraints.ConstraintDescriptor; import tools.vitruv.framework.vsum.constraints.ConstraintStatus; import tools.vitruv.framework.vsum.constraints.ConstraintValidationReport; import tools.vitruv.framework.vsum.constraints.ConstraintValidationResult; -import tools.vitruv.framework.vsum.internal.InternalVirtualModel; + +<#if viewTypes?has_content> +import tools.vitruv.framework.views.ViewType; /** * Generated by the Methodologist setup service. Smoke test that runs during the build to check - * that the VSUM can actually be created from the metamodels, reactions, and constraints. + * that the VSUM can actually be created from the metamodels, reactions, constraints, and views. */ class [=vsumMainClass]Test { @@ -60,4 +65,30 @@ class [=vsumMainClass]Test { } } +<#if viewTypes?has_content> + + /** + * The Vitruv server offers every view type of the VSUM under {@code /vsum/view/types} and creates + * views of them under {@code /vsum/view}; both must work for the generated view types. + */ + @Test + void viewTypesCanBeCreated(@TempDir Path storageFolder) throws IOException { + InternalVirtualModel vsum = [=vsumMainClass].createVirtualModel(storageFolder); + try { + for (String name : [=vsumMainClass].NEOJOIN_VIEW_TYPES) { + ViewType viewType = + vsum.getViewTypes().stream() + .filter(candidate -> candidate.getName().equals(name)) + .findFirst() + .orElse(null); + Assertions.assertNotNull(viewType, () -> "the VSUM registers the view type " + name); + Assertions.assertNotNull( + vsum.createSelector(viewType).createView(), + () -> "a view of the view type " + name + " can be created"); + } + } finally { + vsum.dispose(); + } + } + } diff --git a/src/main/resources/vsum-sample/components.nj b/src/main/resources/vsum-sample/components.nj new file mode 100644 index 0000000..e23b2bb --- /dev/null +++ b/src/main/resources/vsum-sample/components.nj @@ -0,0 +1,9 @@ +export components to "http://vitruv.tools/methodologisttemplate/components" + +import "http://vitruv.tools/methodologisttemplate/model" + +// shows every Component of the first model as a Thing with its name +from Component c +create Thing { + c.name +} 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..296dc7c 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 @@ -26,9 +26,9 @@ import tools.vitruv.methodologist.setup.vsum.service.views.NeoJoinViewDefinitionProcessor; /** - * Builds a VSUM with constraints, starts it and checks that its Vitruv server lists and validates - * the uploaded constraints. Runs the real Maven build and needs port 8080, so it only runs with - * {@code -Dvsum.integration=true}. + * Builds VSUMs, starts them and checks that their Vitruv server serves the uploaded constraints and + * views. Runs the real Maven build and needs port 8080, so it only runs with {@code + * -Dvsum.integration=true}. */ @EnabledIfSystemProperty(named = "vsum.integration", matches = "true") class VsumBuildEndToEndTest { @@ -57,13 +57,7 @@ void builtVsumServesTheUploadedConstraints() throws Exception { List.of(fixture("constraints.ocl")), List.of())); - Path jarFile = Files.write(runDirectory.resolve("vsum.jar"), jar); - Process server = - new ProcessBuilder("java", "-jar", jarFile.toString()) - .directory(runDirectory.toFile()) - .redirectErrorStream(true) - .redirectOutput(runDirectory.resolve("server.log").toFile()) - .start(); + Process server = start(jar); try { HttpClient http = HttpClient.newHttpClient(); awaitHealthy(http, server); @@ -83,10 +77,67 @@ void builtVsumServesTheUploadedConstraints() throws Exception { assertEquals(200, validation.statusCode()); assertTrue(validation.body().contains("\"satisfied\" : true"), validation.body()); } finally { - server.destroy(); - if (!server.waitFor(10, TimeUnit.SECONDS)) { - server.destroyForcibly(); - } + stop(server); + } + } + + @Test + void builtVsumServesTheUploadedViews() throws Exception { + byte[] jar = + service.buildProjectJar( + new VsumBuildRequest( + List.of(fixture("model.ecore"), fixture("model2.ecore")), + List.of(), + List.of(), + List.of(fixture("components.nj")))); + + Process server = start(jar); + try { + HttpClient http = HttpClient.newHttpClient(); + awaitHealthy(http, server); + + // the view type generated from components.nj is offered next to the identity view types + HttpResponse viewTypes = send(http, request("/vsum/view/types").GET()); + assertEquals(200, viewTypes.statusCode()); + assertTrue(viewTypes.body().contains("\"Components\""), viewTypes.body()); + assertTrue(viewTypes.body().contains("\"model\""), viewTypes.body()); + + // a view is fetched in two steps: a selector of the view type, then the view of its selection + HttpResponse selector = + send(http, request("/vsum/view/selector").header("View-Type", "Components").GET()); + assertEquals(200, selector.statusCode(), selector.body()); + String selectorUuid = selector.headers().firstValue("Selector-UUID").orElseThrow(); + + HttpResponse view = + send( + http, + request("/vsum/view") + .header("Selector-UUID", selectorUuid) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString("[]"))); + assertEquals(200, view.statusCode(), view.body()); + // the root of the view metamodel exported by components.nj + assertTrue( + view.body().contains("http://vitruv.tools/methodologisttemplate/components#//Root"), + view.body()); + } finally { + stop(server); + } + } + + private Process start(byte[] jar) throws IOException { + Path jarFile = Files.write(runDirectory.resolve("vsum.jar"), jar); + return new ProcessBuilder("java", "-jar", jarFile.toString()) + .directory(runDirectory.toFile()) + .redirectErrorStream(true) + .redirectOutput(runDirectory.resolve("server.log").toFile()) + .start(); + } + + private static void stop(Process server) throws InterruptedException { + server.destroy(); + if (!server.waitFor(10, TimeUnit.SECONDS)) { + server.destroyForcibly(); } } diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildWarmupTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildWarmupTest.java index fff96eb..431e59a 100644 --- a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildWarmupTest.java +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildWarmupTest.java @@ -34,6 +34,7 @@ void theSampleNeedsEveryKindOfInput() { sample.metamodels().stream().map(UploadedFile::fileName).toList()); assertEquals(1, sample.reactions().size()); assertEquals(1, sample.constraints().size(), "constraints pull in VitruvOCL"); + assertEquals(1, sample.viewDefinitions().size(), "views pull in NeoJoin"); assertTrue(sample.metamodels().stream().allMatch(file -> file.content().length > 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..b155066 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 @@ -47,7 +47,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 = @@ -82,7 +82,7 @@ void generatesAProjectFollowingTheMethodologistTemplate() throws IOException { + "templateReactions.reactions", "consistency/src/main/constraints/tools/vitruv/methodologisttemplate/consistency/" + "constraints.ocl", - "views/src/main/neojoin/components.nj", + "viewtype/src/main/neojoin/components.nj", "vsum/pom.xml", "vsum/src/main/java/tools/vitruv/methodologisttemplate/vsum/VSUMExample.java", "vsum/src/test/java/tools/vitruv/methodologisttemplate/vsum/VSUMExampleTest.java")) { 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..2239a78 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 @@ -46,11 +46,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 NeoJoinViewDefinitionProcessor()); @TempDir Path temporaryDirectory; diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/project/ProjectGeneratorTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/project/ProjectGeneratorTest.java index abf843d..bad8039 100644 --- a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/project/ProjectGeneratorTest.java +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/project/ProjectGeneratorTest.java @@ -31,7 +31,8 @@ class ProjectGeneratorTest { "tools.vitruv.framework.", "${vitruv.framework.version}", "tools.vitruv.dsls.", "${vitruv.dsls.version}", "tools.vitruv.server.", "${vitruv.server.version}", - "tools.vitruv.vitruvocl.", "${vitruvocl.version}"); + "tools.vitruv.vitruvocl.", "${vitruvocl.version}", + "tools.vitruv.neojoin.vitruv.", "${neojoin.vitruv.version}"); private static final List METAMODELS = List.of( @@ -133,7 +134,8 @@ void leavesNoUnsplitVitruviusVersionBehind() throws Exception { } private void generate(VsumBuildProperties properties) throws IOException { - new ProjectGenerator(properties).generate(projectRoot, METAMODELS, List.of(), List.of()); + new ProjectGenerator(properties) + .generate(projectRoot, METAMODELS, List.of(), List.of(), List.of()); } private static Document parse(Path file) throws Exception { From eae0a4b67e017066e98fb85a5b0733967dfb02eb Mon Sep 17 00:00:00 2001 From: davit Date: Mon, 16 Nov 2026 15:17:54 +0100 Subject: [PATCH 2/2] Add unit tests for the view checks and view error mapping --- .../service/VsumValidationServiceTest.java | 27 ++ .../problem/BuildOutputParserTest.java | 179 +++++++++++++ .../NeoJoinViewDefinitionProcessorTest.java | 244 ++++++++++++++++++ 3 files changed, 450 insertions(+) create mode 100644 src/test/java/tools/vitruv/methodologist/setup/vsum/service/views/NeoJoinViewDefinitionProcessorTest.java 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 f4db734..d298761 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 @@ -127,6 +127,33 @@ void reportsTheViewProblemsTheBuildReportsBeforeMaven() { assertEquals(problemsOfTheBuild(request), result); } + @Test + void reportsViewTypeNamesThatClashLikeTheBuild() { + // valid NeoJoin, so NeoJoin accepts both; but both files become the view type Components + String other = + fixture("components.nj") + .text() + .replace("export components to", "export others to") + .replace("/views/components\"", "/views/others\""); + VsumBuildRequest request = + new VsumBuildRequest( + List.of(fixture("model.ecore"), fixture("model2.ecore")), + List.of(), + List.of(), + List.of(fixture("components.nj"), text("components_.nj", other))); + + VsumValidationResult result = service.validate(request); + + assertFalse(result.valid()); + assertEquals(1, result.problems().size(), result.problems().toString()); + assertEquals(Source.VIEWS, result.problems().get(0).source()); + assertEquals("components_.nj", result.problems().get(0).file()); + assertEquals( + "the view type 'Components' is already defined by components.nj", + result.problems().get(0).message()); + assertEquals(problemsOfTheBuild(request), result); + } + @Test void leavesNoFilesBehind() throws IOException { Set before = buildWorkspaces(); diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/problem/BuildOutputParserTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/problem/BuildOutputParserTest.java index 181a34a..764b2bb 100644 --- a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/problem/BuildOutputParserTest.java +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/problem/BuildOutputParserTest.java @@ -38,6 +38,18 @@ class BuildOutputParserTest { execute actions in brake """; + private static final String COMPONENTS_VIEW = + """ + export components to "http://example.org/views/components" + + import "http://vitruv.tools/methodologisttemplate/model" + + from Component c + create Thing { + c.nmae + } + """; + @Test void reportsTheRootCauseOfTheOriginalReportAndHidesItsFollowUpErrors() { ProjectSources sources = new ProjectSources(ROOT); @@ -322,6 +334,161 @@ void attributesExceptionsWhileCreatingTheVsumToTheRoutine(@TempDir Path root) th problem.message()); } + @Test + void attributesNeoJoinCompilerErrorsToTheViewDefinition() { + ProjectSources sources = new ProjectSources(ROOT); + Path view = ProjectLayout.viewsDirectory(ROOT).resolve("components.nj"); + sources.add(Source.VIEWS, view, upload("components.nj", COMPONENTS_VIEW), null); + + List problems = + BuildOutputParser.parse( + failed( + "[ERROR] ERROR:The method or field nmae is undefined for the type Component (file:" + + view + + " line : 7 column : 7)"), + sources); + + BuildProblem problem = problems.get(0); + assertEquals(Source.VIEWS, problem.source()); + assertEquals("components.nj", problem.file()); + assertEquals(7, problem.line()); + assertEquals(7, problem.column()); + assertEquals(" c.nmae\n ^", problem.excerpt()); + } + + @Test + void attributesXtextErrorsOfUnknownNeoJoinFilesToTheViews() { + List problems = + BuildOutputParser.parse( + failed( + "[ERROR] ERROR:missing EOF at 'x' (file:/elsewhere/unknown.nj line : 1 column : 1)", + "[ERROR] ERROR:x cannot be resolved. (file:/elsewhere/unknown.reactions line : 1" + + " column : 1)"), + new ProjectSources(ROOT)); + + assertEquals( + List.of(Source.REACTIONS, Source.VIEWS), + problems.stream().map(BuildProblem::source).toList()); + assertNull(problems.get(1).file()); + } + + @Test + void attributesCompileErrorsOfTheGeneratedViewTypeToTheViewDefinition() { + ProjectSources sources = new ProjectSources(ROOT); + SourceFile file = addView(sources, ROOT, "my-entities.nj", "entities", "MyEntities"); + Path generated = + ProjectLayout.viewtypeModule(ROOT) + .resolve( + "target/generated-sources/neojoin/neojoin/viewtypes/entities" + + "/MyEntitiesViewTypeExpressions.java"); + + List problems = + BuildOutputParser.parse( + failed("[ERROR] " + generated + ":[12,20] incompatible types: int cannot be converted"), + sources); + + BuildProblem problem = problems.get(0); + assertEquals(Source.VIEWS, problem.source()); + assertEquals(file.fileName(), problem.file()); + assertTrue( + problem.message().startsWith("the Java code generated from the view definition"), + problem.message()); + assertFalse(problem.message().contains("/tmp/"), problem.message()); + assertTrue(problem.hint().contains("Java expressions in the view definition"), problem.hint()); + } + + @Test + void attributesCompileErrorsOfAnUnknownViewTypeToTheViews() { + // EMF code of a view metamodel whose export is not known + Path generated = + ProjectLayout.viewtypeModule(ROOT) + .resolve("target/generated-sources/ecore/neojoin/viewtypes/other/impl/RootImpl.java"); + + List problems = + BuildOutputParser.parse( + failed("[ERROR] " + generated + ":[3,1] cannot find symbol"), new ProjectSources(ROOT)); + + assertEquals(Source.VIEWS, problems.get(0).source()); + assertNull(problems.get(0).file()); + } + + @Test + void fallsBackToTheViewsWhenTheViewTypeModuleFailed() { + List problems = + BuildOutputParser.parse( + failed( + "[ERROR] Failed to execute goal org.eclipse.xtext:xtext-maven-plugin:2.43.0" + + ":generate (default) on project tools.vitruv.methodologisttemplate.viewtype:" + + " Execution failed"), + new ProjectSources(ROOT)); + + assertEquals(List.of(Source.VIEWS), problems.stream().map(BuildProblem::source).toList()); + } + + @Test + void attributesExceptionsInAGeneratedViewTypeToItsViewDefinition(@TempDir Path root) + throws IOException { + ProjectSources sources = new ProjectSources(root); + addView(sources, root, "my-entities.nj", "entities", "MyEntities"); + writeReport( + root, + "viewTypesCanBeCreated", + "java.lang.NullPointerException", + "name is null", + "java.lang.NullPointerException: name is null\n" + + "\tat neojoin.viewtypes.entities.MyEntitiesViewTypeExpressions.expression1" + + "(MyEntitiesViewTypeExpressions.java:20)\n" + + "\tat tools.vitruv.neojoin.vitruv.views.operations.Project.apply(Project.java:7)\n"); + + List problems = + BuildOutputParser.parse(failed("[ERROR] Tests run: 1, Errors: 1"), sources); + + BuildProblem problem = problems.get(0); + assertEquals(Source.VIEWS, problem.source()); + assertEquals("my-entities.nj", problem.file()); + assertEquals( + "creating the views failed: NullPointerException: name is null", problem.message()); + } + + @Test + void attributesAViewTypeMissingFromTheVsumToItsViewDefinition(@TempDir Path root) + throws IOException { + ProjectSources sources = new ProjectSources(root); + addView(sources, root, "my-entities.nj", "entities", "MyEntities"); + writeReport( + root, + "viewTypesCanBeCreated", + "org.opentest4j.AssertionFailedError", + "the VSUM registers the view type MyEntities ==> expected: not <null>", + "org.opentest4j.AssertionFailedError: the VSUM registers the view type MyEntities\n" + + "\tat tools.vitruv.methodologisttemplate.vsum.VSUMExampleTest" + + ".viewTypesCanBeCreated(VSUMExampleTest.java:40)\n"); + + List problems = + BuildOutputParser.parse(failed("[ERROR] Tests run: 1, Failures: 1"), sources); + + assertEquals(Source.VIEWS, problems.get(0).source()); + assertEquals("my-entities.nj", problems.get(0).file()); + } + + @Test + void attributesExceptionsInTheNeoJoinRuntimeToTheViews(@TempDir Path root) throws IOException { + writeReport( + root, + "viewTypesCanBeCreated", + "java.lang.IllegalStateException", + "no root", + "java.lang.IllegalStateException: no root\n" + + "\tat tools.vitruv.neojoin.vitruv.views.ViewTypeImpl.createView(ViewTypeImpl.java:9)\n"); + + List problems = + BuildOutputParser.parse( + failed("[ERROR] Tests run: 1, Errors: 1"), new ProjectSources(root)); + + assertEquals(Source.VIEWS, problems.get(0).source()); + assertNull(problems.get(0).file(), "the runtime frames do not name the view"); + } + private static MavenBuildFailedException failed(String... output) { return new MavenBuildFailedException( VsumErrorCodes.BUILD_FAILED, @@ -331,6 +498,18 @@ private static MavenBuildFailedException failed(String... output) { HttpStatus.UNPROCESSABLE_CONTENT); } + private static SourceFile addView( + ProjectSources sources, Path root, String fileName, String exportName, String name) { + SourceFile file = + sources.add( + Source.VIEWS, + ProjectLayout.viewsDirectory(root).resolve(fileName), + upload(fileName, COMPONENTS_VIEW), + null); + sources.addView(exportName, name, file); + return file; + } + private static UploadedFile upload(String name, String text) { return new UploadedFile(name, text.getBytes(StandardCharsets.UTF_8)); } diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/views/NeoJoinViewDefinitionProcessorTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/views/NeoJoinViewDefinitionProcessorTest.java new file mode 100644 index 0000000..f425665 --- /dev/null +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/views/NeoJoinViewDefinitionProcessorTest.java @@ -0,0 +1,244 @@ +package tools.vitruv.methodologist.setup.vsum.service.views; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +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.text; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +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.VsumBuildException; +import tools.vitruv.methodologist.setup.vsum.service.project.ProjectLayout; + +class NeoJoinViewDefinitionProcessorTest { + + private static final String MODEL_URI = "http://vitruv.tools/methodologisttemplate/model"; + private static final String MODEL2_URI = "http://vitruv.tools/methodologisttemplate/model2"; + private static final String SUBPACKAGE_URI = MODEL_URI + "/sub"; + + private static final List METAMODELS = + List.of( + new GeneratedMetamodel( + "model", + MODEL_URI, + "model.ecore", + "model.genmodel", + List.of( + new GeneratedMetamodel.GeneratedPackage(MODEL_URI, "x.model.ModelPackage"), + new GeneratedMetamodel.GeneratedPackage(SUBPACKAGE_URI, "x.model.SubPackage"))), + new GeneratedMetamodel( + "model2", + MODEL2_URI, + "model2.ecore", + "model2.genmodel", + List.of( + new GeneratedMetamodel.GeneratedPackage(MODEL2_URI, "x.model2.Model2Package")))); + + private final NeoJoinViewDefinitionProcessor processor = new NeoJoinViewDefinitionProcessor(); + + @TempDir Path projectRoot; + + @Test + void derivesTheNamesOfTheGeneratedClassesAndWritesTheViews() throws IOException { + List viewTypes = + processor.process( + List.of(view("components.nj", "components"), view("my-entities.nj", "entities")), + METAMODELS, + projectRoot); + + assertEquals(2, viewTypes.size()); + GeneratedViewType components = viewTypes.get(0); + assertEquals("Components", components.name()); + assertEquals("neojoin.viewtypes.components.ComponentsViewType", components.viewTypeClass()); + + // the class is named after the file, its package after the export + GeneratedViewType entities = viewTypes.get(1); + assertEquals("my-entities.nj", entities.fileName()); + assertEquals("MyEntities", entities.name()); + assertEquals("entities", entities.exportName()); + assertEquals("http://example.org/views/entities", entities.nsUri()); + assertEquals("neojoin.viewtypes.entities.MyEntitiesViewType", entities.viewTypeClass()); + assertEquals("neojoin.viewtypes.entities.EntitiesPackage", entities.packageInterface()); + assertEquals( + "target/generated-sources/neojoin/ecore/entities/my-entities.genmodel", + entities.genmodelPath()); + + Path views = ProjectLayout.viewsDirectory(projectRoot); + assertTrue(Files.isRegularFile(views.resolve("components.nj"))); + assertTrue(Files.isRegularFile(views.resolve("my-entities.nj"))); + } + + @Test + void writesNothingWithoutViews() throws IOException { + assertEquals(List.of(), processor.process(List.of(), METAMODELS, projectRoot)); + assertFalse(Files.exists(ProjectLayout.viewtypeModule(projectRoot))); + } + + @Test + void namesViewTypesLikeNeoJoin() { + assertEquals("Components", GeneratedViewType.pascalCase("components")); + assertEquals("MyView2", GeneratedViewType.pascalCase("my_View-2")); + // NeoJoin lower-cases everything but the first letter of each word + assertEquals("Myview", GeneratedViewType.pascalCase("myView")); + assertEquals("View", GeneratedViewType.pascalCase("_view")); + assertEquals("a.b", GeneratedViewType.baseName("a.b.nj")); + assertEquals("views", GeneratedViewType.baseName("views.NJ")); + } + + @Test + void rejectsFileNamesThatCannotNameAViewType() { + BuildProblem problem = + firstProblem( + rejected(view("1st.nj", "first"), view("a.b.nj", "ab"), view("ok.nj", "ok")), 2); + + assertEquals(Source.VIEWS, problem.source()); + assertEquals("1st.nj", problem.file()); + assertEquals("the file name cannot be the name of a view type", problem.message()); + assertNull(problem.line()); + assertTrue(problem.hint().contains("start the file name with a letter"), problem.hint()); + } + + @Test + void rejectsViewsWithoutExport() { + BuildProblem problem = + single(rejected(text("plain.nj", "import \"" + MODEL_URI + "\"\nfrom Component c\n"))); + + assertEquals("plain.nj", problem.file()); + assertEquals("declares no export", problem.message()); + assertTrue(problem.hint().contains("export to"), problem.hint()); + } + + @Test + void ignoresExportsInComments() { + BuildProblem problem = + single( + rejected( + text( + "commented.nj", + "// export components to \"http://example.org/views/components\"\n" + + "/* export components to \"http://example.org/views/components\" */\n" + + "from Component c\n"))); + + assertEquals("declares no export", problem.message()); + } + + @Test + void rejectsViewTypeNamesUsedTwice() { + // both files become the view type MyView + BuildProblem problem = + single(rejected(view("my-view.nj", "first"), view("My_View.nj", "second"))); + + assertEquals("My_View.nj", problem.file()); + assertEquals("the view type 'MyView' is already defined by my-view.nj", problem.message()); + assertEquals(1, problem.line()); + assertEquals(1, problem.column()); + } + + @Test + void rejectsViewTypeNamesOfAMetamodel() { + List metamodels = + List.of( + new GeneratedMetamodel( + "Components", + MODEL_URI, + "components.ecore", + "components.genmodel", + List.of( + new GeneratedMetamodel.GeneratedPackage(MODEL_URI, "x.ComponentsPackage")))); + + VsumBuildException exception = + assertThrows( + VsumBuildException.class, + () -> processor.check(List.of(view("components.nj", "components")), metamodels)); + + BuildProblem problem = single(exception); + assertEquals( + "the view type 'Components' has the same name as the view type of the metamodel" + + " 'Components'", + problem.message()); + assertTrue(problem.hint().contains("Rename the file"), problem.hint()); + } + + @Test + void rejectsExportsToTheNsUriOfAMetamodelOrItsSubpackage() { + VsumBuildException exception = + rejected( + text("a.nj", "export a to \"" + MODEL2_URI + "\"\n"), + text("b.nj", "\n\nexport b to \"" + SUBPACKAGE_URI + "\"\n")); + + assertEquals(2, exception.getProblems().size(), exception.getProblems().toString()); + BuildProblem metamodel = exception.getProblems().get(0); + assertEquals("a.nj", metamodel.file()); + assertEquals( + "exports to '" + MODEL2_URI + "', which is the nsURI of an uploaded metamodel", + metamodel.message()); + // points at the opening quote of the nsURI + assertEquals(1, metamodel.line()); + assertEquals(13, metamodel.column()); + BuildProblem subpackage = exception.getProblems().get(1); + assertEquals("b.nj", subpackage.file()); + assertEquals(3, subpackage.line()); + } + + @Test + void reportsTheProblemsOfAllViewsAndWritesNothing() { + VsumBuildException exception = + assertThrows( + VsumBuildException.class, + () -> + processor.process( + List.of( + text("none.nj", "from Component c"), + view("x.y.nj", "xy"), + view("valid.nj", "valid")), + METAMODELS, + projectRoot)); + + assertEquals(VsumErrorCodes.VIEWS_ERROR, exception.getErrorCode()); + assertEquals( + List.of("none.nj", "x.y.nj"), + exception.getProblems().stream().map(BuildProblem::file).toList()); + assertFalse(Files.exists(ProjectLayout.viewsDirectory(projectRoot))); + } + + /** A view definition exporting to its own nsURI. */ + private static UploadedFile view(String fileName, String exportName) { + return text( + fileName, + "export " + + exportName + + " to \"http://example.org/views/" + + exportName + + "\"\n\nimport \"" + + MODEL_URI + + "\"\n\nfrom Component c\ncreate Thing {\n c.name\n}\n"); + } + + private VsumBuildException rejected(UploadedFile... views) { + return assertThrows( + VsumBuildException.class, () -> processor.check(List.of(views), METAMODELS)); + } + + /** The only problem. */ + private static BuildProblem single(VsumBuildException exception) { + return firstProblem(exception, 1); + } + + /** The first problem, after checking how many there are. */ + private static BuildProblem firstProblem(VsumBuildException exception, int expectedProblems) { + assertEquals( + expectedProblems, exception.getProblems().size(), exception.getProblems().toString()); + return exception.getProblems().get(0); + } +}