From c7c454244bafc3ff8fb68d6bdc68b61e95fee037 Mon Sep 17 00:00:00 2001 From: Max Oesterle Date: Tue, 27 Oct 2026 13:22:58 +0100 Subject: [PATCH 1/8] build OCL constraints into generated VSUM projects --- Dockerfile | 3 + .../config/GeneratedProjectVersions.java | 33 ++++ .../setup/vsum/controller/VsumController.java | 18 +- .../setup/vsum/service/ConstraintUploads.java | 176 ++++++++++++++++++ .../vsum/service/GenerateFromTemplate.java | 61 +++++- .../vsum/service/VsumProjectBuildService.java | 82 +++++++- .../setup/vsum/service/VsumService.java | 126 ++++++++++++- src/main/resources/application.properties | 3 + .../resources/templates/consistencyPom.ftl | 7 +- src/main/resources/templates/rootPom.ftl | 49 ++++- src/main/resources/templates/vsumExample.ftl | 21 ++- src/main/resources/templates/vsumPom.ftl | 13 +- src/main/resources/templates/vsumTest.ftl | 5 +- .../VsumControllerErrorHandlingTest.java | 3 +- .../vsum/controller/VsumControllerTest.java | 11 +- .../vsum/service/ConstraintUploadsTest.java | 157 ++++++++++++++++ .../GenerateFromTemplateConstraintsTest.java | 111 +++++++++++ .../vsum/service/VsumBuildEndToEndTest.java | 154 +++++++++++++++ ...sumProjectBuildServiceConstraintsTest.java | 143 ++++++++++++++ .../service/VsumServiceConstraintsTest.java | 113 +++++++++++ .../setup/vsum/service/VsumServiceTest.java | 2 +- .../Gr\303\266\303\237en & Preise (v1).ocl" | 5 + src/test/resources/e2e/model.ecore | 30 +++ src/test/resources/e2e/model.genmodel | 33 ++++ src/test/resources/e2e/model2.ecore | 23 +++ src/test/resources/e2e/model2.genmodel | 25 +++ .../resources/e2e/templateReactions.reactions | 160 ++++++++++++++++ 27 files changed, 1516 insertions(+), 51 deletions(-) create mode 100644 src/main/java/tools/vitruv/methodologist/setup/config/GeneratedProjectVersions.java create mode 100644 src/main/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintUploads.java create mode 100644 src/test/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintUploadsTest.java create mode 100644 src/test/java/tools/vitruv/methodologist/setup/vsum/service/GenerateFromTemplateConstraintsTest.java create mode 100644 src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildEndToEndTest.java create mode 100644 src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildServiceConstraintsTest.java create mode 100644 src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumServiceConstraintsTest.java create mode 100644 "src/test/resources/e2e/Gr\303\266\303\237en & Preise (v1).ocl" create mode 100644 src/test/resources/e2e/model.ecore create mode 100644 src/test/resources/e2e/model.genmodel create mode 100644 src/test/resources/e2e/model2.ecore create mode 100644 src/test/resources/e2e/model2.genmodel create mode 100644 src/test/resources/e2e/templateReactions.reactions diff --git a/Dockerfile b/Dockerfile index dbeaca0..b1344ce 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,6 +6,9 @@ RUN apt-get update \ COPY methodologist-setup-service-0.0.1-SNAPSHOT.jar /app/app.jar +# generated projects and constraint files may have non-ASCII names +ENV LANG=C.UTF-8 + EXPOSE 8090 ENTRYPOINT ["java", "-jar", "/app/app.jar"] \ No newline at end of file diff --git a/src/main/java/tools/vitruv/methodologist/setup/config/GeneratedProjectVersions.java b/src/main/java/tools/vitruv/methodologist/setup/config/GeneratedProjectVersions.java new file mode 100644 index 0000000..32c9179 --- /dev/null +++ b/src/main/java/tools/vitruv/methodologist/setup/config/GeneratedProjectVersions.java @@ -0,0 +1,33 @@ +package tools.vitruv.methodologist.setup.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * Versions of the Vitruvius artifacts used by generated VSUM projects, configurable via {@code + * vsum.generator.versions.*}. The framework must provide the constraint SPI ({@code + * tools.vitruv.framework.vsum.constraints}), which is available from 4.0.2. + */ +@Data +@Component +@ConfigurationProperties(prefix = "vsum.generator.versions") +public class GeneratedProjectVersions { + /** Version of the {@code tools.vitruv:parent} POM. */ + private String parent = "4.0.0"; + + /** Version of the Vitruv-Change artifacts ({@code tools.vitruv.change.*}). */ + private String change = "4.0.1"; + + /** Version of the Vitruv framework artifacts ({@code tools.vitruv.framework.*}). */ + private String framework = "4.0.2-SNAPSHOT"; + + /** Version of the Reactions language and runtime ({@code tools.vitruv.dsls.*}). */ + private String dsls = "4.0.0"; + + /** Version of the Vitruv server ({@code tools.vitruv.server.remote}). */ + private String server = "4.0.1-SNAPSHOT"; + + /** Version of VitruvOCL ({@code tools.vitruv.dsls:vitruvocl-language}). */ + private String vitruvocl = "0.1.0-SNAPSHOT"; +} 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 b2e187c..d2a7fa2 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 @@ -41,6 +41,7 @@ public class VsumController { * @param metamodelFiles metamodel files * @param genmodelFiles genmodel files paired by index with metamodel files * @param reactionFiles reaction files + * @param constraintFiles optional OCL constraint files * @return zip file response containing generated project * @throws NoSuchFileException when the build does not produce the expected artifact */ @@ -68,11 +69,15 @@ public ResponseEntity buildProject( @RequestPart("genmodelFiles") List genmodelFiles, @Parameter(description = "Reaction files", required = true) @RequestPart("reactionFiles") - List reactionFiles) + List reactionFiles, + @Parameter(description = "OCL constraint files, registered at the VSUM") + @RequestPart(value = "constraintFiles", required = false) + List constraintFiles) throws NoSuchFileException { byte[] archive = - vsumProjectBuildService.buildProjectArchive(metamodelFiles, genmodelFiles, reactionFiles); + vsumProjectBuildService.buildProjectArchive( + metamodelFiles, genmodelFiles, reactionFiles, constraintFiles); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/zip")); @@ -92,6 +97,7 @@ public ResponseEntity buildProject( * @param metamodelFiles metamodel files * @param genmodelFiles genmodel files paired by index with metamodel files * @param reactionFiles reaction files + * @param constraintFiles optional OCL constraint files * @return response containing the built VSUM jar */ @PostMapping(value = "/jar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @@ -118,10 +124,14 @@ public ResponseEntity buildJar( @RequestPart("genmodelFiles") List genmodelFiles, @Parameter(description = "Reaction files", required = true) @RequestPart("reactionFiles") - List reactionFiles) { + List reactionFiles, + @Parameter(description = "OCL constraint files, registered at the VSUM") + @RequestPart(value = "constraintFiles", required = false) + List constraintFiles) { byte[] jar = - vsumProjectBuildService.buildProjectJar(metamodelFiles, genmodelFiles, reactionFiles); + vsumProjectBuildService.buildProjectJar( + metamodelFiles, genmodelFiles, reactionFiles, constraintFiles); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/java-archive")); diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintUploads.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintUploads.java new file mode 100644 index 0000000..8ad828b --- /dev/null +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintUploads.java @@ -0,0 +1,176 @@ +package tools.vitruv.methodologist.setup.vsum.service; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.springframework.web.multipart.MultipartFile; +import tools.vitruv.methodologist.setup.exception.MethodologistSetupException; + +/** Stores and checks uploaded OCL constraint files of a VSUM build. */ +final class ConstraintUploads { + private static final String VSUM_INPUT_ERROR_CODE = "VSUM_INPUT_ERROR"; + private static final String EXTENSION = ".ocl"; + private static final String DEFAULT_NAME = "constraints"; + + /** + * Maximum number of characters of a file name without extension, well below the limits of file + * systems and of paths within the generated project. + */ + private static final int MAX_NAME_LENGTH = 100; + + /** + * Characters that are not allowed in file names on Windows, Linux or macOS, and invisible + * formatting characters, which would make names misleading. + */ + private static final Pattern INVALID_FILE_NAME_CHARACTERS = + Pattern.compile("[\\\\/:*?\"<>|\\p{Cntrl}\\p{Cf}]", Pattern.UNICODE_CHARACTER_CLASS); + + private static final Pattern RESERVED_WINDOWS_NAMES = + Pattern.compile("(?i)(con|prn|aux|nul|com\\d|lpt\\d)(\\..*)?"); + + /** + * Matches a context declaration, capturing the metamodel of a qualified context type such as + * {@code context model::Component} or {@code context c : model::Component}. + */ + private static final Pattern CONTEXT_PATTERN = + Pattern.compile("\\bcontext\\s+(?:\\w+\\s*:\\s*)?(\\w+)(\\s*::)?"); + + private static final Pattern STRING_LITERAL = Pattern.compile("\"(?:[^\"\\\\]|\\\\.)*\""); + private static final Pattern BLOCK_COMMENT = Pattern.compile("/\\*.*?\\*/", Pattern.DOTALL); + private static final Pattern LINE_COMMENT = Pattern.compile("--[^\\r\\n]*"); + + private ConstraintUploads() {} + + /** + * Validates the uploaded constraint files and writes them into the given directory. Each file + * gets a distinct name ending in {@code .ocl}. Parts without a file, as sent by forms without a + * selected file, are ignored. + * + * @param directory the directory to write the files to + * @param constraintFiles the uploaded files, may be {@code null} + * @return the written files in upload order, empty if there are none + * @throws IOException when writing a file fails + * @throws MethodologistSetupException when a file is empty + */ + static List write(Path directory, List constraintFiles) throws IOException { + if (constraintFiles == null || constraintFiles.isEmpty()) { + return List.of(); + } + Set usedNames = new HashSet<>(); + List files = new ArrayList<>(); + for (int index = 0; index < constraintFiles.size(); index++) { + MultipartFile constraintFile = constraintFiles.get(index); + if (constraintFile == null || isMissingFile(constraintFile)) { + continue; + } + if (constraintFile.isEmpty()) { + throw new MethodologistSetupException( + VSUM_INPUT_ERROR_CODE, + "Uploaded constraint file " + constraintFile.getOriginalFilename() + " is empty"); + } + String name = uniqueName(constraintFile.getOriginalFilename(), index, usedNames); + Path target = Files.createDirectories(directory).resolve(name); + constraintFile.transferTo(target); + files.add(target.toFile()); + } + return files; + } + + /** + * Checks that every context declaration names its metamodel and that the metamodel is one of the + * given metamodels, so that invalid constraints fail fast with a clear message instead of failing + * the VSUM at runtime. The constraints are not parsed completely, so other errors are only + * detected when the VSUM loads them. + * + * @param constraintFiles the constraint files + * @param metamodelNames the package names of the uploaded metamodels + * @throws IOException when reading a file fails + * @throws MethodologistSetupException when a context is unqualified or refers to an unknown + * metamodel + */ + static void checkMetamodels(List constraintFiles, Collection metamodelNames) + throws IOException { + for (File constraintFile : constraintFiles) { + String content = withoutCommentsAndStrings(Files.readString(constraintFile.toPath())); + Set unknown = new TreeSet<>(); + Set unqualified = new TreeSet<>(); + Matcher matcher = CONTEXT_PATTERN.matcher(content); + while (matcher.find()) { + if (matcher.group(2) == null) { + unqualified.add(matcher.group(1)); + } else if (!metamodelNames.contains(matcher.group(1))) { + unknown.add(matcher.group(1)); + } + } + if (!unqualified.isEmpty()) { + throw new MethodologistSetupException( + VSUM_INPUT_ERROR_CODE, + String.format( + "Constraint file %s declares context(s) %s without metamodel; use" + + " ::", + constraintFile.getName(), unqualified)); + } + if (!unknown.isEmpty()) { + throw new MethodologistSetupException( + VSUM_INPUT_ERROR_CODE, + String.format( + "Constraint file %s refers to unknown metamodel(s) %s; available metamodels: %s", + constraintFile.getName(), unknown, new TreeSet<>(metamodelNames))); + } + } + } + + private static boolean isMissingFile(MultipartFile file) { + String name = file.getOriginalFilename(); + return file.isEmpty() && (name == null || name.isBlank()); + } + + private static String withoutCommentsAndStrings(String content) { + String withoutStrings = STRING_LITERAL.matcher(content).replaceAll("\"\""); + String withoutBlockComments = BLOCK_COMMENT.matcher(withoutStrings).replaceAll(" "); + return LINE_COMMENT.matcher(withoutBlockComments).replaceAll(""); + } + + /** + * Derives a file name from the uploaded name, which keeps the name, e.g. of a rule set, as far as + * possible: only the directory part and characters that are invalid in file names are removed. + * The result differs case-insensitively from all names used so far. + */ + private static String uniqueName(String originalName, int index, Set usedNames) { + String baseName = originalName == null ? "" : originalName; + if (baseName.toLowerCase(Locale.ROOT).endsWith(EXTENSION)) { + baseName = baseName.substring(0, baseName.length() - EXTENSION.length()); + } + // path separators are replaced as well, so "Prices/Discounts" stays one recognizable name + baseName = INVALID_FILE_NAME_CHARACTERS.matcher(baseName).replaceAll("_"); + baseName = + baseName + .codePoints() + .limit(MAX_NAME_LENGTH) + .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) + .toString(); + // leading dots would hide the file, trailing dots and spaces are dropped by Windows + baseName = baseName.replaceAll("^[.\\s]+|[.\\s]+$", ""); + if (baseName.isEmpty() || baseName.matches("_+")) { + baseName = DEFAULT_NAME; + } + if (RESERVED_WINDOWS_NAMES.matcher(baseName).matches()) { + baseName = "_" + baseName; + } + String name = baseName + EXTENSION; + for (int suffix = index; !usedNames.add(name.toLowerCase(Locale.ROOT)); suffix++) { + name = baseName + "-" + suffix + EXTENSION; + } + return name; + } +} diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/GenerateFromTemplate.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/GenerateFromTemplate.java index b12f161..73b7cfe 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/GenerateFromTemplate.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/GenerateFromTemplate.java @@ -8,12 +8,15 @@ import java.io.FileWriter; import java.io.IOException; import java.io.Writer; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import tools.vitruv.methodologist.setup.config.GeneratedProjectVersions; import tools.vitruv.methodologist.setup.config.MetamodelLocation; import tools.vitruv.methodologist.setup.config.VitruvConfiguration; import tools.vitruv.methodologist.setup.exception.MissingModelException; @@ -26,8 +29,22 @@ public class GenerateFromTemplate { private static final String PACKAGE_NAME = "packageName"; private static final String CHANGE_PROPAGATION_SPECIFICATIONS = "changePropagationSpecifications"; - /** Constructor. */ - public GenerateFromTemplate() {} + private final GeneratedProjectVersions versions; + + /** Creates a generator using the default Vitruvius versions. */ + public GenerateFromTemplate() { + this(new GeneratedProjectVersions()); + } + + /** + * Creates a generator using the given Vitruvius versions. + * + * @param versions the versions of the Vitruvius artifacts used by generated projects + */ + @Autowired + public GenerateFromTemplate(GeneratedProjectVersions versions) { + this.versions = versions; + } private Configuration getConfiguration() { Configuration cfg = new Configuration(Configuration.VERSION_2_3_31); @@ -42,7 +59,8 @@ private Configuration getConfiguration() { private void writeTemplate(Template template, File filePath, Map data) throws IOException { FileUtils.createFile(filePath.getAbsolutePath()); - try (Writer fileWriter = new FileWriter(filePath.getAbsolutePath(), false)) { + try (Writer fileWriter = + new FileWriter(filePath.getAbsolutePath(), StandardCharsets.UTF_8, false)) { template.process(data, fileWriter); fileWriter.flush(); log.info("writing to " + filePath.getAbsolutePath()); @@ -78,6 +96,7 @@ public void generateRootPom(File filePath, String packageName) Map data = new HashMap<>(); data.put("packageName", packageName.trim()); + data.put("versions", versions); Template template = loadTemplate(cfg, "rootPom.ftl"); writeTemplate(template, filePath, data); @@ -91,10 +110,24 @@ public void generateRootPom(File filePath, String packageName) * @throws java.io.IOException If the file cannot be written. */ public void generateVsumPom(File filePath, String packageName) throws IOException { + generateVsumPom(filePath, packageName, false); + } + + /** + * Generates the vsum pom file. + * + * @param filePath The file path to write the vsum pom file to. + * @param packageName The package name from the genmodel. + * @param hasConstraints Whether the project contains OCL constraints, which requires VitruvOCL. + * @throws java.io.IOException If the file cannot be written. + */ + public void generateVsumPom(File filePath, String packageName, boolean hasConstraints) + throws IOException { Configuration cfg = getConfiguration(); Map data = new HashMap<>(); data.put("packageName", packageName.trim()); + data.put("hasConstraints", hasConstraints); Template template = loadTemplate(cfg, "vsumPom.ftl"); writeTemplate(template, filePath, data); @@ -115,12 +148,34 @@ public void generateVsumExample( List models, List changePropagationSpecifications) throws IOException { + generateVsumExample(filePath, packageName, models, changePropagationSpecifications, List.of()); + } + + /** + * Generates the vsum example file. + * + * @param filePath The file path to write the vsum example file to. + * @param packageName The package name from the genmodel. + * @param models The model names to create view types for. + * @param changePropagationSpecifications The change propagation specification class names. + * @param constraintResources The classpath resource names of the OCL constraint files to register + * at the virtual model, may be empty. + * @throws java.io.IOException If the file cannot be written. + */ + public void generateVsumExample( + File filePath, + String packageName, + List models, + List changePropagationSpecifications, + List constraintResources) + throws IOException { Configuration cfg = getConfiguration(); Map data = new HashMap<>(); data.put("packageName", packageName.trim()); data.put("models", models); data.put(CHANGE_PROPAGATION_SPECIFICATIONS, changePropagationSpecifications); + data.put("constraintResources", constraintResources); Template template = loadTemplate(cfg, "vsumExample.ftl"); writeTemplate(template, filePath, data); 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 602962a..eaa5bca 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 @@ -50,8 +50,33 @@ public byte[] buildProjectArchive( List metamodelFiles, List genmodelFiles, List reactionFiles) { + return buildProjectArchive(metamodelFiles, genmodelFiles, reactionFiles, null); + } + + /** + * Builds a VSUM project including OCL constraints from uploaded files and returns a zip archive + * of the whole project. + * + * @param metamodelFiles metamodel files + * @param genmodelFiles genmodel files in the same order as metamodel files + * @param reactionFiles reaction files + * @param constraintFiles optional OCL constraint files, may be {@code null} + * @return built project archive bytes + */ + public byte[] buildProjectArchive( + List metamodelFiles, + List genmodelFiles, + List reactionFiles, + List constraintFiles) { return buildArtifact( - metamodelFiles, genmodelFiles, reactionFiles, vsumService::generateProjectArchive); + metamodelFiles, + genmodelFiles, + reactionFiles, + constraintFiles, + (models, reactions, constraints, namespaces) -> + constraints.isEmpty() + ? vsumService.generateProjectArchive(models, reactions, namespaces) + : vsumService.generateProjectArchive(models, reactions, constraints, namespaces)); } /** @@ -68,8 +93,33 @@ public byte[] buildProjectJar( List metamodelFiles, List genmodelFiles, List reactionFiles) { + return buildProjectJar(metamodelFiles, genmodelFiles, reactionFiles, null); + } + + /** + * Builds a VSUM project including OCL constraints from uploaded files and returns only the + * executable VSUM jar-with-dependencies. + * + * @param metamodelFiles metamodel files + * @param genmodelFiles genmodel files in the same order as metamodel files + * @param reactionFiles reaction files + * @param constraintFiles optional OCL constraint files, may be {@code null} + * @return the bytes of the built VSUM jar + */ + public byte[] buildProjectJar( + List metamodelFiles, + List genmodelFiles, + List reactionFiles, + List constraintFiles) { return buildArtifact( - metamodelFiles, genmodelFiles, reactionFiles, vsumService::generateProjectJar); + metamodelFiles, + genmodelFiles, + reactionFiles, + constraintFiles, + (models, reactions, constraints, namespaces) -> + constraints.isEmpty() + ? vsumService.generateProjectJar(models, reactions, namespaces) + : vsumService.generateProjectJar(models, reactions, constraints, namespaces)); } /** @@ -80,6 +130,7 @@ public byte[] buildProjectJar( * @param metamodelFiles metamodel files * @param genmodelFiles genmodel files in the same order as metamodel files * @param reactionFiles reaction files + * @param constraintFiles optional OCL constraint files, may be {@code null} * @param generator the VSUM generation strategy producing the artifact bytes * @return the produced artifact bytes */ @@ -87,6 +138,7 @@ private byte[] buildArtifact( List metamodelFiles, List genmodelFiles, List reactionFiles, + List constraintFiles, ProjectArtifactGenerator generator) { validateInputs(metamodelFiles, genmodelFiles, reactionFiles); @@ -98,7 +150,12 @@ private byte[] buildArtifact( List copiedReactionFiles = toReactionFiles(uploadWorkspace, reactionFiles); normalizeReactionImports(modelPairs, copiedReactionFiles); Map metamodelNamespaceMap = extractMetamodelNamespaceMap(modelPairs); - return generator.generate(modelPairs, copiedReactionFiles, metamodelNamespaceMap); + List copiedConstraintFiles = + ConstraintUploads.write(uploadWorkspace.resolve("constraints"), constraintFiles); + ConstraintUploads.checkMetamodels( + copiedConstraintFiles, extractMetamodelPackageNames(modelPairs)); + return generator.generate( + modelPairs, copiedReactionFiles, copiedConstraintFiles, metamodelNamespaceMap); } catch (IOException | MissingModelException e) { String reason = e.getMessage() != null ? e.getMessage() : e.toString(); throw new MethodologistSetupException( @@ -274,6 +331,23 @@ private String normalizeReactionImports( return rewritten.toString(); } + /** + * Reads the package names of the uploaded metamodels. + * + * @param modelPairs metamodel/genmodel file pairs + * @return the names of the root packages of all readable metamodels + */ + Set extractMetamodelPackageNames(List modelPairs) { + Set packageNames = new HashSet<>(); + for (VsumService.ModelFiles pair : modelPairs) { + MetamodelInfo info = readMetamodelInfo(pair.metamodelFile()); + if (info != null && info.packageName != null && !info.packageName.isBlank()) { + packageNames.add(info.packageName); + } + } + return packageNames; + } + /** * Stores metamodel nsURI information for build-time EMF initialization. * @@ -414,6 +488,7 @@ private interface ProjectArtifactGenerator { * * @param modelPairs metamodel/genmodel file pairs * @param reactionFiles copied reaction files + * @param constraintFiles copied OCL constraint files, may be empty * @param metamodelNamespaceMap map of model names to nsURIs * @return the produced artifact bytes * @throws IOException when file IO or artifact extraction fails @@ -423,6 +498,7 @@ private interface ProjectArtifactGenerator { byte[] generate( List modelPairs, List reactionFiles, + List constraintFiles, Map metamodelNamespaceMap) throws IOException, InterruptedException, MissingModelException; } diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumService.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumService.java index b9b533a..d18a2ff 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumService.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumService.java @@ -16,6 +16,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.ZipEntry; @@ -24,6 +25,7 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import tools.vitruv.methodologist.setup.config.VitruvConfiguration; +import tools.vitruv.methodologist.setup.exception.MethodologistSetupException; import tools.vitruv.methodologist.setup.exception.MissingModelException; import tools.vitruv.methodologist.setup.messages.ErrorMessages; import tools.vitruv.methodologist.setup.model.service.EcoreToGenmodelService; @@ -42,6 +44,22 @@ public class VsumService { "vsum/target/tools.vitruv.methodologisttemplate." + "vsum-0.1.0-SNAPSHOT-jar-with-dependencies.jar"; + /** Directory, relative to the generated project root, containing the OCL constraint files. */ + static final String CONSTRAINTS_RESOURCE_DIRECTORY = "vsum/src/main/resources/constraints"; + + /** The Maven executable; on Windows, Maven is started via its {@code mvn.cmd} script. */ + private static final String MAVEN_EXECUTABLE = + System.getProperty("os.name", "").toLowerCase(java.util.Locale.ROOT).startsWith("windows") + ? "mvn.cmd" + : "mvn"; + + private static final Pattern SAFE_PROPERTY_NAME = Pattern.compile("[A-Za-z_][A-Za-z0-9_.-]*"); + private static final Pattern SAFE_NS_URI = + Pattern.compile("[A-Za-z][A-Za-z0-9+.-]*:[A-Za-z0-9/._~:#?=%@+-]*"); + + /** Classpath prefix of the OCL constraint files in the generated VSUM. */ + private static final String CONSTRAINTS_RESOURCE_PREFIX = "constraints/"; + private final GenerateFromTemplate generateFromTemplate; private final EcoreToGenmodelService ecoreToGenmodelService; @@ -61,7 +79,30 @@ public byte[] generateProjectArchive( List reactionFiles, Map metamodelNamespaceMap) throws IOException, InterruptedException, MissingModelException { - return buildProject(modelFiles, reactionFiles, metamodelNamespaceMap, this::zipDirectory); + return generateProjectArchive(modelFiles, reactionFiles, List.of(), metamodelNamespaceMap); + } + + /** + * Generates a full VSUM project including OCL constraints, builds it with Maven, and returns the + * project archive as bytes. + * + * @param modelFiles paired metamodel/genmodel files + * @param reactionFiles optional reaction files + * @param constraintFiles optional OCL constraint files with distinct names + * @param metamodelNamespaceMap map of model names to nsURIs + * @return zip archive bytes containing generated project and build artifacts + * @throws IOException when file IO or build execution fails + * @throws InterruptedException when the build process is interrupted + * @throws MissingModelException when the model configuration is invalid + */ + public byte[] generateProjectArchive( + List modelFiles, + List reactionFiles, + List constraintFiles, + Map metamodelNamespaceMap) + throws IOException, InterruptedException, MissingModelException { + return buildProject( + modelFiles, reactionFiles, constraintFiles, metamodelNamespaceMap, this::zipDirectory); } /** @@ -97,7 +138,30 @@ public byte[] generateProjectJar( List reactionFiles, Map metamodelNamespaceMap) throws IOException, InterruptedException, MissingModelException { - return buildProject(modelFiles, reactionFiles, metamodelNamespaceMap, this::extractVsumJar); + return generateProjectJar(modelFiles, reactionFiles, List.of(), metamodelNamespaceMap); + } + + /** + * Generates a full VSUM project including OCL constraints, builds it with Maven, and returns only + * the executable VSUM jar as bytes. + * + * @param modelFiles paired metamodel/genmodel files + * @param reactionFiles optional reaction files + * @param constraintFiles optional OCL constraint files with distinct names + * @param metamodelNamespaceMap map of model names to nsURIs + * @return the bytes of the built VSUM jar-with-dependencies + * @throws IOException when file IO, build execution, or jar extraction fails + * @throws InterruptedException when the build process is interrupted + * @throws MissingModelException when the model configuration is invalid + */ + public byte[] generateProjectJar( + List modelFiles, + List reactionFiles, + List constraintFiles, + Map metamodelNamespaceMap) + throws IOException, InterruptedException, MissingModelException { + return buildProject( + modelFiles, reactionFiles, constraintFiles, metamodelNamespaceMap, this::extractVsumJar); } /** @@ -122,6 +186,7 @@ public byte[] generateProjectJar(List modelFiles, List reactio * * @param modelFiles paired metamodel/genmodel files * @param reactionFiles optional reaction files + * @param constraintFiles optional OCL constraint files with distinct names * @param metamodelNamespaceMap map of model names to nsURIs passed to the build * @param artifactExtractor extracts the resulting bytes from the built workspace * @return the extracted artifact bytes @@ -132,6 +197,7 @@ public byte[] generateProjectJar(List modelFiles, List reactio private byte[] buildProject( List modelFiles, List reactionFiles, + List constraintFiles, Map metamodelNamespaceMap, ArtifactExtractor artifactExtractor) throws IOException, InterruptedException, MissingModelException { @@ -148,7 +214,9 @@ private byte[] buildProject( List copiedReactionFiles = copyReactionFiles(workspace, reactionFiles); configuration.setReactionLocations(copiedReactionFiles); - generateProjectFiles(configuration); + List constraintResources = copyConstraintFiles(workspace, constraintFiles); + + generateProjectFiles(configuration, constraintResources); runMavenBuild(workspace, metamodelNamespaceMap); return artifactExtractor.extract(workspace); } finally { @@ -255,6 +323,35 @@ private List copyReactionFiles(Path workspace, List reactionFiles) return copied; } + /** + * Copies the OCL constraint files into the resources of the VSUM module, so that the generated + * VSUM can load them from the classpath. + * + * @param workspace root directory of the generated project + * @param constraintFiles the constraint files to copy, may be {@code null} + * @return the classpath resource names of the copied files, empty if there are none + * @throws IOException when copying a file fails + */ + private List copyConstraintFiles(Path workspace, List constraintFiles) + throws IOException { + if (constraintFiles == null || constraintFiles.isEmpty()) { + return List.of(); + } + Path constraintsDirectory = + Files.createDirectories(workspace.resolve(CONSTRAINTS_RESOURCE_DIRECTORY)); + List resources = new ArrayList<>(); + for (File constraintFile : constraintFiles) { + String resource = CONSTRAINTS_RESOURCE_PREFIX + constraintFile.getName(); + if (resources.contains(resource)) { + throw new IllegalArgumentException( + "Constraint files must have distinct names: " + constraintFile.getName()); + } + copyFile(constraintFile, constraintsDirectory); + resources.add(resource); + } + return resources; + } + /** * Copies a single file into the target directory, overwriting any existing file with the same * name. @@ -294,10 +391,12 @@ private String buildModelLocations(List copiedModelFiles) { * descriptor. * * @param configuration the Vitruv configuration describing the project to generate + * @param constraintResources the classpath resource names of the OCL constraint files * @throws IOException when writing a generated file fails * @throws MissingModelException when the model configuration is invalid */ - private void generateProjectFiles(VitruvConfiguration configuration) + private void generateProjectFiles( + VitruvConfiguration configuration, List constraintResources) throws IOException, MissingModelException { generateFromTemplate.generateRootPom( new File((configuration.getLocalPath() + "/pom.xml").trim()), @@ -310,7 +409,8 @@ private void generateProjectFiles(VitruvConfiguration configuration) configuration.getPackageName()); generateFromTemplate.generateVsumPom( new File((configuration.getLocalPath() + "/vsum/pom.xml").trim()), - configuration.getPackageName()); + configuration.getPackageName(), + !constraintResources.isEmpty()); generateFromTemplate.generateP2WrappersPom( new File((configuration.getLocalPath() + "/p2wrappers/pom.xml").trim()), configuration.getPackageName()); @@ -330,7 +430,8 @@ private void generateProjectFiles(VitruvConfiguration configuration) new File((configuration.getLocalPath() + "/vsum/src/main/java/VSUMExample.java").trim()), configuration.getPackageName(), configuration.getModelNames(), - changePropagationSpecifications); + changePropagationSpecifications, + constraintResources); generateFromTemplate.generateVsumTest( new File( (configuration.getLocalPath() + "/vsum/src/test/java/VSUMExampleTest.java").trim()), @@ -401,11 +502,22 @@ protected void runMavenBuild(Path projectRoot, Map metamodelName */ private ProcessBuilder createMavenProcessBuilder( Path projectRoot, Map metamodelNamespaceMap) { - ProcessBuilder processBuilder = new ProcessBuilder("mvn", "clean", "verify", "-DskipTests"); + ProcessBuilder processBuilder = + new ProcessBuilder(MAVEN_EXECUTABLE, "clean", "verify", "-DskipTests"); // Pass metamodel namespace information as system properties if (metamodelNamespaceMap != null && !metamodelNamespaceMap.isEmpty()) { for (var entry : metamodelNamespaceMap.entrySet()) { + // the values stem from uploaded files and end up on a command line, which on Windows is + // interpreted by cmd.exe, so only plain names and URIs are accepted + if (!SAFE_PROPERTY_NAME.matcher(entry.getKey()).matches() + || !SAFE_NS_URI.matcher(entry.getValue()).matches()) { + throw new MethodologistSetupException( + "VSUM_INPUT_ERROR", + String.format( + "Metamodel %s has an unsupported name or nsURI %s", + entry.getKey(), entry.getValue())); + } String propName = "metamodel." + entry.getKey() + ".nsuri"; String propValue = "-D" + propName + "=" + entry.getValue(); processBuilder.command().add(propValue); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index cc79419..d3fbaf9 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -3,3 +3,6 @@ server.port=8090 springdoc.swagger-ui.path=/swagger-ui.html springdoc.api-docs.path=/api-docs logging.level.tools.vitruv.methodologist=DEBUG +# Vitruvius versions of generated VSUM projects can be overridden with +# vsum.generator.versions.{parent,change,framework,dsls,server,vitruvocl}; +# the defaults are defined in GeneratedProjectVersions diff --git a/src/main/resources/templates/consistencyPom.ftl b/src/main/resources/templates/consistencyPom.ftl index 4c2b6af..42fb7fc 100644 --- a/src/main/resources/templates/consistencyPom.ftl +++ b/src/main/resources/templates/consistencyPom.ftl @@ -89,7 +89,6 @@ org.eclipse.xtext xtext-maven-plugin - 2.39.0 @@ -116,17 +115,17 @@ tools.vitruv tools.vitruv.dsls.reactions.language - 3.1.0 + ${vitruv-dsls.version} tools.vitruv tools.vitruv.dsls.reactions.runtime - 3.1.0 + ${vitruv-dsls.version} tools.vitruv tools.vitruv.dsls.common - 3.1.0 + ${vitruv-dsls.version} ${project.groupId} diff --git a/src/main/resources/templates/rootPom.ftl b/src/main/resources/templates/rootPom.ftl index 1c0876a..a4042e7 100644 --- a/src/main/resources/templates/rootPom.ftl +++ b/src/main/resources/templates/rootPom.ftl @@ -9,14 +9,13 @@ tools.vitruv parent - 3.2.0 + ${versions.parent} ${packageName} 0.1.0-SNAPSHOT pom - <#noparse> Methodologist Template @@ -31,8 +30,28 @@ - 3.2.3 + UTF-8 + ${versions.change} + ${versions.framework} + ${versions.dsls} + ${versions.server} + ${versions.vitruvocl} + <#noparse> + + + + + central-snapshots + https://central.sonatype.com/repository/maven-snapshots/ + + false + + + true + + + @@ -40,32 +59,32 @@ tools.vitruv tools.vitruv.change.atomic - ${vitruv.version} + ${vitruv-change.version} tools.vitruv tools.vitruv.change.composite - ${vitruv.version} + ${vitruv-change.version} tools.vitruv tools.vitruv.change.interaction - ${vitruv.version} + ${vitruv-change.version} tools.vitruv tools.vitruv.change.propagation - ${vitruv.version} + ${vitruv-change.version} tools.vitruv tools.vitruv.change.testutils.integration - ${vitruv.version} + ${vitruv-change.version} tools.vitruv tools.vitruv.dsls.reactions.runtime - ${vitruv.version} + ${vitruv-dsls.version} tools.vitruv @@ -77,6 +96,16 @@ tools.vitruv.framework.vsum ${vitruv.version} + + tools.vitruv + tools.vitruv.server.remote + ${vitruv-server.version} + + + tools.vitruv.dsls + vitruvocl-language + ${vitruvocl.version} + @@ -97,4 +126,4 @@ - \ No newline at end of file + diff --git a/src/main/resources/templates/vsumExample.ftl b/src/main/resources/templates/vsumExample.ftl index 31ad385..8b1fd98 100644 --- a/src/main/resources/templates/vsumExample.ftl +++ b/src/main/resources/templates/vsumExample.ftl @@ -16,6 +16,10 @@ import tools.vitruv.framework.vsum.VirtualModel; import tools.vitruv.framework.remote.server.*; import java.util.Scanner; import java.io.IOException; +import java.io.UncheckedIOException; +<#if constraintResources?has_content> +import tools.vitruv.dsls.vitruvocl.vitruv.VitruvOclConstraintChecker; + /** * This class provides an example how to define and use a VSUM. @@ -38,13 +42,20 @@ public class VSUMExample { private static VirtualModel createDefaultVirtualModel() { Collection> viewTypes = createDefaultViewTypes(); - VirtualModel model = new VirtualModelBuilder() - .withStorageFolder(Path.of("vsumexample")) - .withUserInteractorForResultProvider(new TestUserInteraction.ResultProvider(new TestUserInteraction())) - .withChangePropagationSpecifications(<#list changePropagationSpecifications as specification>new ${specification}()<#sep>, ).withViewTypes(viewTypes) - .buildAndInitialize(); + try { + VirtualModel model = new VirtualModelBuilder() + .withStorageFolder(Path.of("vsumexample")) + .withUserInteractorForResultProvider(new TestUserInteraction.ResultProvider(new TestUserInteraction())) + .withChangePropagationSpecifications(<#list changePropagationSpecifications as specification>new ${specification}()<#sep>, ).withViewTypes(viewTypes) +<#if constraintResources?has_content> + .withConstraintChecker(VitruvOclConstraintChecker.fromClasspath(<#list constraintResources as resource>"${resource?j_string}"<#sep>, )) + + .buildAndInitialize(); getDefaultView(model); return model; + } catch (IOException e) { + throw new UncheckedIOException("Could not initialize the virtual model", e); + } } private static View getDefaultView(VirtualModel vsum) { diff --git a/src/main/resources/templates/vsumPom.ftl b/src/main/resources/templates/vsumPom.ftl index f10fa3d..e88ac82 100644 --- a/src/main/resources/templates/vsumPom.ftl +++ b/src/main/resources/templates/vsumPom.ftl @@ -43,12 +43,14 @@ - - 3.2.3 - - - +<#if hasConstraints> + + + tools.vitruv.dsls + vitruvocl-language + + <#noparse> @@ -68,7 +70,6 @@ tools.vitruv tools.vitruv.server.remote - ${vitruv.version} diff --git a/src/main/resources/templates/vsumTest.ftl b/src/main/resources/templates/vsumTest.ftl index c8216ce..084f53c 100644 --- a/src/main/resources/templates/vsumTest.ftl +++ b/src/main/resources/templates/vsumTest.ftl @@ -2,6 +2,7 @@ package ${packageName}.vsum; import tools.vitruv.framework.vsum.VirtualModelBuilder; +import java.io.IOException; import java.nio.file.Path; import org.eclipse.emf.ecore.resource.Resource; @@ -30,12 +31,12 @@ public class VSUMExampleTest { @Disabled @Test - void test() { + void test() throws IOException { VirtualModel vsum = createDefaultVirtualModel(); Assertions.assertNotNull(getDefaultView(vsum), "Creating the default view failed"); } - private VirtualModel createDefaultVirtualModel() { + private VirtualModel createDefaultVirtualModel() throws IOException { return new VirtualModelBuilder() .withStorageFolder(projectPath) .withUserInteractorForResultProvider(new TestUserInteraction.ResultProvider(new TestUserInteraction())) 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 7ea8da6..f329c26 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 @@ -1,5 +1,6 @@ package tools.vitruv.methodologist.setup.vsum.controller; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -31,7 +32,7 @@ void buildProject_shouldReturnJsonErrorForZipAcceptHeader() throws Exception { .setControllerAdvice(new GlobalExceptionHandler()) .build(); - when(buildService.buildProjectArchive(anyList(), anyList(), anyList())) + when(buildService.buildProjectArchive(anyList(), anyList(), anyList(), any())) .thenThrow( new MethodologistSetupException( "VSUM_INPUT_ERROR", diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/controller/VsumControllerTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/controller/VsumControllerTest.java index eb6c2f2..1f59dd8 100644 --- a/src/test/java/tools/vitruv/methodologist/setup/vsum/controller/VsumControllerTest.java +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/controller/VsumControllerTest.java @@ -115,7 +115,8 @@ void buildProjectArchiveNormalizesReactionImportUris() throws Exception { void buildProjectReturnsZipResponse() throws Exception { VsumProjectBuildService buildService = mock(VsumProjectBuildService.class); byte[] archive = {1, 2, 3, 4}; - when(buildService.buildProjectArchive(anyList(), anyList(), anyList())).thenReturn(archive); + when(buildService.buildProjectArchive(anyList(), anyList(), anyList(), any())) + .thenReturn(archive); VsumController controller = new VsumController(buildService); @@ -127,7 +128,7 @@ void buildProjectReturnsZipResponse() throws Exception { "genmodelFiles", "model.genmodel", "application/octet-stream", "gen".getBytes()); ResponseEntity response = - controller.buildProject(List.of(metamodel), List.of(genmodel), List.of()); + controller.buildProject(List.of(metamodel), List.of(genmodel), List.of(), null); assertEquals(200, response.getStatusCode().value()); assertArrayEquals(archive, response.getBody()); @@ -143,7 +144,7 @@ void buildProjectReturnsZipResponse() throws Exception { void buildJarReturnsJarResponse() throws NoSuchFileException { VsumProjectBuildService buildService = mock(VsumProjectBuildService.class); byte[] jar = {9, 8, 7}; - when(buildService.buildProjectJar(anyList(), anyList(), any())).thenReturn(jar); + when(buildService.buildProjectJar(anyList(), anyList(), any(), any())).thenReturn(jar); VsumController controller = new VsumController(buildService); @@ -155,7 +156,7 @@ void buildJarReturnsJarResponse() throws NoSuchFileException { "genmodelFiles", "model.genmodel", "application/octet-stream", "gen".getBytes()); ResponseEntity response = - controller.buildJar(List.of(metamodel), List.of(genmodel), null); + controller.buildJar(List.of(metamodel), List.of(genmodel), null, null); assertEquals(200, response.getStatusCode().value()); assertArrayEquals(jar, response.getBody()); @@ -165,6 +166,6 @@ void buildJarReturnsJarResponse() throws NoSuchFileException { "tools.vitruv.methodologisttemplate.vsum-0.1.0-SNAPSHOT-jar-with-dependencies.jar", response.getHeaders().getContentDisposition().getFilename()); - verify(buildService).buildProjectJar(anyList(), anyList(), any()); + verify(buildService).buildProjectJar(anyList(), anyList(), any(), any()); } } diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintUploadsTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintUploadsTest.java new file mode 100644 index 0000000..a9468fb --- /dev/null +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintUploadsTest.java @@ -0,0 +1,157 @@ +package tools.vitruv.methodologist.setup.vsum.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.mock.web.MockMultipartFile; +import tools.vitruv.methodologist.setup.exception.MethodologistSetupException; + +class ConstraintUploadsTest { + @TempDir Path tempDir; + + @Test + void namesAreSafeAndDistinct() throws Exception { + List files = + ConstraintUploads.write( + tempDir, + List.of( + upload("a-1-3.ocl"), + upload("a-1.ocl"), + upload("x.ocl"), + upload("a-1.ocl"), + upload("A-1.OCL"), + upload("../../etc/passwd"), + upload("dir/sub\\name with spaces.ocl"), + upload("/"), + upload(".."))); + + List names = files.stream().map(File::getName).toList(); + Set lowerCase = + names.stream().map(name -> name.toLowerCase(Locale.ROOT)).collect(Collectors.toSet()); + assertThat(lowerCase).hasSize(names.size()); + assertThat(names) + .allMatch(name -> name.endsWith(".ocl") && !name.matches(".*[\\\\/:*?\"<>|].*")); + assertThat(names).noneMatch(name -> name.startsWith(".")); + assertThat(files).allMatch(file -> file.toPath().getParent().equals(tempDir)); + assertThat(names).contains("_.._etc_passwd.ocl", "dir_sub_name with spaces.ocl"); + } + + @Test + void keepsRuleSetNames() throws Exception { + List files = + ConstraintUploads.write( + tempDir, + List.of( + upload("Preise & Regeln.ocl"), + upload("Komponenten (Benennung).ocl"), + upload("con.ocl"), + upload("what?.ocl"))); + + assertThat(files) + .extracting(File::getName) + .containsExactly( + "Preise & Regeln.ocl", "Komponenten (Benennung).ocl", "_con.ocl", "what_.ocl"); + } + + @Test + void keepsGroupingOfRuleSetNamesWithSlashes() throws Exception { + List files = + ConstraintUploads.write(tempDir, List.of(upload("A/Regeln.ocl"), upload("B/Regeln.ocl"))); + + assertThat(files).extracting(File::getName).containsExactly("A_Regeln.ocl", "B_Regeln.ocl"); + } + + @Test + void shortensLongNames() throws Exception { + String longName = "Ä".repeat(300) + ".ocl"; + + File file = ConstraintUploads.write(tempDir, List.of(upload(longName))).get(0); + + assertThat(file.getName()).isEqualTo("Ä".repeat(100) + ".ocl"); + } + + @Test + void ignoresPartsWithoutFile() throws Exception { + MockMultipartFile noFile = + new MockMultipartFile("constraintFiles", "", "application/octet-stream", new byte[0]); + + assertThat(ConstraintUploads.write(tempDir, List.of(noFile))).isEmpty(); + } + + @Test + void rejectsEmptyFiles() { + MockMultipartFile empty = + new MockMultipartFile("constraintFiles", "empty.ocl", "text/plain", new byte[0]); + + assertThatThrownBy(() -> ConstraintUploads.write(tempDir, List.of(empty))) + .isInstanceOf(MethodologistSetupException.class) + .hasMessageContaining("empty.ocl"); + } + + @Test + void acceptsKnownQualifiedContexts() { + assertThatCode( + () -> + check( + """ + context model::Component inv a: true + context c : model::Link inv b: true + """)) + .doesNotThrowAnyException(); + } + + @Test + void ignoresContextsInCommentsAndStrings() { + assertThatCode( + () -> + check( + """ + -- context shop::Item inv old: true + /* context shop::Item + inv older: true */ + context model::Component inv a: + @message "see context shop::Item -- not a context" + true + """)) + .doesNotThrowAnyException(); + } + + @Test + void rejectsUnknownMetamodels() { + assertThatThrownBy(() -> check("context shop::Item inv a: true")) + .isInstanceOf(MethodologistSetupException.class) + .hasMessageContaining("shop"); + } + + @Test + void rejectsUnqualifiedContexts() { + assertThatThrownBy(() -> check("context Component inv a: true")) + .isInstanceOf(MethodologistSetupException.class) + .hasMessageContaining("Component") + .hasMessageContaining("without metamodel"); + } + + private void check(String content) throws Exception { + File file = Files.writeString(tempDir.resolve("c.ocl"), content).toFile(); + ConstraintUploads.checkMetamodels(List.of(file), Set.of("model")); + } + + private static MockMultipartFile upload(String name) { + return new MockMultipartFile( + "constraintFiles", + name, + "text/plain", + "context model::Component inv a: true".getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/GenerateFromTemplateConstraintsTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/GenerateFromTemplateConstraintsTest.java new file mode 100644 index 0000000..1ca605c --- /dev/null +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/GenerateFromTemplateConstraintsTest.java @@ -0,0 +1,111 @@ +package tools.vitruv.methodologist.setup.vsum.service; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import tools.vitruv.methodologist.setup.config.GeneratedProjectVersions; + +/** Tests the Vitruvius versions and the constraint wiring of generated projects. */ +class GenerateFromTemplateConstraintsTest { + private static final String PACKAGE_NAME = "tools.vitruv.methodologisttemplate"; + + @TempDir Path tempDir; + + private GenerateFromTemplate generator; + + @BeforeEach + void setUp() { + GeneratedProjectVersions versions = new GeneratedProjectVersions(); + versions.setParent("9.0.0"); + versions.setChange("9.1.0"); + versions.setFramework("9.2.0-SNAPSHOT"); + versions.setDsls("9.3.0"); + versions.setServer("9.4.0-SNAPSHOT"); + versions.setVitruvocl("9.5.0-SNAPSHOT"); + generator = new GenerateFromTemplate(versions); + } + + @Test + @DisplayName("root pom uses the configured versions and the snapshot repository") + void rootPomUsesConfiguredVersions() throws Exception { + Path target = tempDir.resolve("pom.xml"); + + generator.generateRootPom(target.toFile(), PACKAGE_NAME); + + String content = Files.readString(target); + assertTrue(content.contains("parent\n 9.0.0")); + assertTrue(content.contains("9.1.0")); + assertTrue(content.contains("9.2.0-SNAPSHOT")); + assertTrue(content.contains("9.3.0")); + assertTrue(content.contains("9.4.0-SNAPSHOT")); + assertTrue(content.contains("9.5.0-SNAPSHOT")); + assertTrue(content.contains("https://central.sonatype.com/repository/maven-snapshots/")); + assertFalse(content.contains("3.2.3")); + } + + @Test + @DisplayName("consistency pom uses the configured Reactions version") + void consistencyPomUsesConfiguredDslsVersion() throws Exception { + Path target = tempDir.resolve("consistency/pom.xml"); + + generator.generateConsistencyPom(target.toFile(), PACKAGE_NAME); + + String content = Files.readString(target); + assertTrue(content.contains("${vitruv-dsls.version}")); + assertFalse(content.contains("3.1.0")); + } + + @Test + @DisplayName("vsum pom depends on VitruvOCL only if the project has constraints") + void vsumPomDependsOnVitruvOclOnlyWithConstraints() throws Exception { + Path without = tempDir.resolve("without/pom.xml"); + Path with = tempDir.resolve("with/pom.xml"); + + generator.generateVsumPom(without.toFile(), PACKAGE_NAME); + generator.generateVsumPom(with.toFile(), PACKAGE_NAME, true); + + assertFalse(Files.readString(without).contains("vitruvocl-language")); + String content = Files.readString(with); + assertTrue(content.contains("vitruvocl-language")); + assertFalse(content.contains("3.2.3")); + } + + @Test + @DisplayName("VSUM example registers the constraints from the classpath") + void vsumExampleRegistersConstraints() throws Exception { + Path target = tempDir.resolve("VSUMExample.java"); + + generator.generateVsumExample( + target.toFile(), + PACKAGE_NAME, + List.of("Alpha"), + List.of("mir.reactions.a.ASpecification"), + List.of("constraints/first.ocl", "constraints/second.ocl")); + + String content = Files.readString(target); + assertTrue( + content.contains("import tools.vitruv.dsls.vitruvocl.vitruv.VitruvOclConstraintChecker;")); + assertTrue( + content.contains( + ".withConstraintChecker(VitruvOclConstraintChecker.fromClasspath(" + + "\"constraints/first.ocl\", \"constraints/second.ocl\"))")); + } + + @Test + @DisplayName("VSUM example without constraints does not use VitruvOCL") + void vsumExampleWithoutConstraints() throws Exception { + Path target = tempDir.resolve("VSUMExample.java"); + + generator.generateVsumExample( + target.toFile(), PACKAGE_NAME, List.of("Alpha"), List.of("mir.reactions.a.A"), List.of()); + + assertFalse(Files.readString(target).contains("VitruvOcl")); + } +} 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 new file mode 100644 index 0000000..6f1ff7e --- /dev/null +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumBuildEndToEndTest.java @@ -0,0 +1,154 @@ +package tools.vitruv.methodologist.setup.vsum.service; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.mock.web.MockMultipartFile; +import tools.vitruv.methodologist.setup.model.service.EcoreToGenmodelService; + +/** + * Builds a real VSUM project with Maven, starts the resulting jar and queries the constraints of + * the running Vitruv server. Requires Maven and the configured Vitruvius versions; enable with + * {@code -Dvsum.e2e=true}. + */ +@EnabledIfSystemProperty(named = "vsum.e2e", matches = "true") +class VsumBuildEndToEndTest { + private static final String SERVER_URL = "http://localhost:8080"; + + @TempDir Path runDirectory; + + @Test + void builtVsumServesTheUploadedConstraints() throws Exception { + VsumProjectBuildService buildService = + new VsumProjectBuildService( + new VsumService(new GenerateFromTemplate(), new EcoreToGenmodelService())); + + byte[] jar = + buildService.buildProjectJar( + List.of(file("metamodelFiles", "model.ecore"), file("metamodelFiles", "model2.ecore")), + List.of( + file("genmodelFiles", "model.genmodel"), file("genmodelFiles", "model2.genmodel")), + List.of(file("reactionFiles", "templateReactions.reactions")), + List.of(file("constraintFiles", "Größen & Preise (v1).ocl"))); + + 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(); + try { + HttpClient http = HttpClient.newHttpClient(); + awaitHealthy(http, server); + // otherwise another process answered on the port + assertThat(server.isAlive()).as("the built VSUM server is running").isTrue(); + + String constraints = get(http, "/vsum/constraints"); + assertThat(constraints).contains("model::Component::componentHasName"); + + String validation = post(http, "/vsum/constraints/validate", "{}"); + assertThat(validation).contains("\"status\" : \"SATISFIED\""); + } finally { + stop(server); + } + } + + @Test + void builtVsumWithoutConstraintsStarts() throws Exception { + VsumProjectBuildService buildService = + new VsumProjectBuildService( + new VsumService(new GenerateFromTemplate(), new EcoreToGenmodelService())); + + byte[] jar = + buildService.buildProjectJar( + List.of(file("metamodelFiles", "model.ecore"), file("metamodelFiles", "model2.ecore")), + List.of( + file("genmodelFiles", "model.genmodel"), file("genmodelFiles", "model2.genmodel")), + List.of(file("reactionFiles", "templateReactions.reactions"))); + + Path jarFile = Files.write(runDirectory.resolve("vsum-plain.jar"), jar); + Process server = + new ProcessBuilder("java", "-jar", jarFile.toString()) + .directory(runDirectory.toFile()) + .redirectErrorStream(true) + .redirectOutput(runDirectory.resolve("server-plain.log").toFile()) + .start(); + try { + HttpClient http = HttpClient.newHttpClient(); + awaitHealthy(http, server); + assertThat(server.isAlive()).as("the built VSUM server is running").isTrue(); + + assertThat(get(http, "/vsum/constraints")).isEqualTo("[ ]"); + } finally { + stop(server); + } + } + + private static void awaitHealthy(HttpClient http, Process server) throws Exception { + Instant deadline = Instant.now().plus(Duration.ofMinutes(2)); + while (Instant.now().isBefore(deadline)) { + if (!server.isAlive()) { + throw new IllegalStateException("VSUM server terminated with " + server.exitValue()); + } + try { + if (http.send(request("/health").GET().build(), HttpResponse.BodyHandlers.ofString()) + .statusCode() + == 200) { + return; + } + } catch (IOException notYetStarted) { + // the server is still starting + } + Thread.sleep(500); + } + throw new IllegalStateException("VSUM server did not start"); + } + + private static String get(HttpClient http, String path) throws Exception { + return http.send(request(path).GET().build(), HttpResponse.BodyHandlers.ofString()).body(); + } + + private static String post(HttpClient http, String path, String body) throws Exception { + return http.send( + request(path).POST(HttpRequest.BodyPublishers.ofString(body)).build(), + HttpResponse.BodyHandlers.ofString()) + .body(); + } + + private static HttpRequest.Builder request(String path) { + return HttpRequest.newBuilder(URI.create(SERVER_URL + path)).timeout(Duration.ofSeconds(10)); + } + + private static void stop(Process server) throws InterruptedException { + try (OutputStream input = server.getOutputStream()) { + input.write("quit\n".getBytes()); + } catch (IOException alreadyStopped) { + // nothing to do + } + if (!server.waitFor( + Duration.ofSeconds(10).toMillis(), java.util.concurrent.TimeUnit.MILLISECONDS)) { + server.destroyForcibly(); + } + } + + private static MockMultipartFile file(String part, String name) throws IOException { + try (InputStream content = VsumBuildEndToEndTest.class.getResourceAsStream("/e2e/" + name)) { + return new MockMultipartFile(part, name, "application/octet-stream", content); + } + } +} diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildServiceConstraintsTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildServiceConstraintsTest.java new file mode 100644 index 0000000..e5d4790 --- /dev/null +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildServiceConstraintsTest.java @@ -0,0 +1,143 @@ +package tools.vitruv.methodologist.setup.vsum.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.mock.web.MockMultipartFile; +import tools.vitruv.methodologist.setup.exception.MethodologistSetupException; + +/** Tests the handling of uploaded OCL constraint files. */ +class VsumProjectBuildServiceConstraintsTest { + + private final VsumService vsumService = mock(VsumService.class); + private final VsumProjectBuildService service = new VsumProjectBuildService(vsumService); + + @Test + @SuppressWarnings("unchecked") + void passesUploadedConstraintsToTheBuild() throws Exception { + List contents = new ArrayList<>(); + when(vsumService.generateProjectJar(anyList(), anyList(), anyList(), anyMap())) + .thenAnswer( + invocation -> { + for (File file : (List) invocation.getArgument(2)) { + contents.add(Files.readString(file.toPath())); + } + return new byte[] {1}; + }); + + byte[] jar = + service.buildProjectJar( + List.of(metamodel()), + List.of(genmodel()), + List.of(reaction()), + List.of(constraint("prices.ocl", "context pcm::Item inv positive: self.price > 0"))); + + assertThat(jar).containsExactly(1); + assertThat(contents).containsExactly("context pcm::Item inv positive: self.price > 0"); + } + + @Test + void buildsWithoutConstraintsAsBefore() throws Exception { + when(vsumService.generateProjectArchive(anyList(), anyList(), anyMap())) + .thenReturn(new byte[] {2}); + + service.buildProjectArchive( + List.of(metamodel()), List.of(genmodel()), List.of(reaction()), null); + + verify(vsumService).generateProjectArchive(anyList(), anyList(), anyMap()); + } + + @Test + @SuppressWarnings("unchecked") + void keepsConstraintFilesWithEqualNamesApart() throws Exception { + ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); + when(vsumService.generateProjectJar(anyList(), anyList(), captor.capture(), anyMap())) + .thenReturn(new byte[] {1}); + + service.buildProjectJar( + List.of(metamodel()), + List.of(genmodel()), + List.of(reaction()), + List.of( + constraint("rules.ocl", "context pcm::Item inv a: true"), + constraint("rules.ocl", "context pcm::Item inv b: true"))); + + List files = captor.getValue(); + assertThat(files).hasSize(2); + assertThat(files.get(0).getName()).isNotEqualTo(files.get(1).getName()); + assertThat(files).allMatch(file -> file.getName().endsWith(".ocl")); + } + + @Test + void rejectsConstraintsOfUnknownMetamodels() { + assertThatThrownBy( + () -> + service.buildProjectJar( + List.of(metamodel()), + List.of(genmodel()), + List.of(reaction()), + List.of(constraint("shop.ocl", "context shop::Item inv a: true")))) + .isInstanceOf(MethodologistSetupException.class) + .hasMessageContaining("shop") + .hasMessageContaining("shop.ocl"); + } + + @Test + void rejectsEmptyConstraintFiles() { + assertThatThrownBy( + () -> + service.buildProjectJar( + List.of(metamodel()), + List.of(genmodel()), + List.of(reaction()), + List.of(constraint("empty.ocl", "")))) + .isInstanceOf(MethodologistSetupException.class) + .hasMessageContaining("constraint file"); + } + + private static MockMultipartFile constraint(String name, String content) { + return new MockMultipartFile( + "constraintFiles", name, "text/plain", content.getBytes(StandardCharsets.UTF_8)); + } + + private static MockMultipartFile reaction() { + return new MockMultipartFile( + "reactionFiles", + "sample.reactions", + "text/plain", + "import \"pcm\"\n".getBytes(StandardCharsets.UTF_8)); + } + + private static MockMultipartFile genmodel() { + return new MockMultipartFile( + "genmodelFiles", + "model.genmodel", + "application/xml", + "content".getBytes(StandardCharsets.UTF_8)); + } + + private static MockMultipartFile metamodel() { + return new MockMultipartFile( + "metamodelFiles", + "model.ecore", + "application/xml", + """ + + + """ + .getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumServiceConstraintsTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumServiceConstraintsTest.java new file mode 100644 index 0000000..2592cae --- /dev/null +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumServiceConstraintsTest.java @@ -0,0 +1,113 @@ +package tools.vitruv.methodologist.setup.vsum.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import tools.vitruv.methodologist.setup.exception.MethodologistSetupException; +import tools.vitruv.methodologist.setup.model.service.EcoreToGenmodelService; + +/** Tests that uploaded constraints become part of the generated VSUM project. */ +class VsumServiceConstraintsTest { + + private final GenerateFromTemplate generateFromTemplate = mock(GenerateFromTemplate.class); + @TempDir Path tempDir; + + @Test + void copiesConstraintsIntoTheVsumResourcesAndRegistersThem() throws Exception { + File ecore = writeEcore(); + File genmodel = Files.writeString(tempDir.resolve("model.genmodel"), "x").toFile(); + File constraint = + Files.writeString(tempDir.resolve("prices.ocl"), "context pcm::Item inv a: true").toFile(); + VsumService service = spy(new VsumService(generateFromTemplate, new EcoreToGenmodelService())); + doNothing().when(service).runMavenBuild(any(Path.class), anyMap()); + + byte[] archive = + service.generateProjectArchive( + List.of(new VsumService.ModelFiles(ecore, genmodel)), + List.of(), + List.of(constraint), + Map.of()); + + assertThat(readZipEntry(archive, "vsum/src/main/resources/constraints/prices.ocl")) + .isEqualTo("context pcm::Item inv a: true"); + verify(generateFromTemplate).generateVsumPom(any(File.class), anyString(), eq(true)); + verify(generateFromTemplate) + .generateVsumExample( + any(File.class), + anyString(), + anyList(), + anyList(), + eq(List.of("constraints/prices.ocl"))); + } + + @Test + void generatesProjectWithoutConstraints() throws Exception { + File ecore = writeEcore(); + File genmodel = Files.writeString(tempDir.resolve("model.genmodel"), "x").toFile(); + VsumService service = spy(new VsumService(generateFromTemplate, new EcoreToGenmodelService())); + doNothing().when(service).runMavenBuild(any(Path.class), anyMap()); + + service.generateProjectArchive( + List.of(new VsumService.ModelFiles(ecore, genmodel)), List.of(), Map.of()); + + verify(generateFromTemplate).generateVsumPom(any(File.class), anyString(), eq(false)); + verify(generateFromTemplate) + .generateVsumExample(any(File.class), anyString(), anyList(), anyList(), eq(List.of())); + } + + @Test + void rejectsNsUrisThatCouldInjectCommands() throws Exception { + VsumService service = new VsumService(generateFromTemplate, new EcoreToGenmodelService()); + var method = + VsumService.class.getDeclaredMethod("createMavenProcessBuilder", Path.class, Map.class); + method.setAccessible(true); + + assertThatThrownBy(() -> method.invoke(service, tempDir, Map.of("pcm", "http://x&calc"))) + .hasCauseInstanceOf(MethodologistSetupException.class); + assertThatThrownBy(() -> method.invoke(service, tempDir, Map.of("a|b", "http://pcm"))) + .hasCauseInstanceOf(MethodologistSetupException.class); + } + + private File writeEcore() throws IOException { + return Files.writeString( + tempDir.resolve("model.ecore"), + """ + + + """) + .toFile(); + } + + private static String readZipEntry(byte[] archive, String name) throws IOException { + try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(archive))) { + for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { + if (entry.getName().equals(name)) { + return new String(zip.readAllBytes(), StandardCharsets.UTF_8); + } + } + } + return null; + } +} diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumServiceTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumServiceTest.java index 69fdd94..04b27a6 100644 --- a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumServiceTest.java +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumServiceTest.java @@ -289,7 +289,7 @@ void runMavenBuild_shouldFailWhenExitCodeNonZero() throws Exception { Path projectRoot = tempDir; - assertThatThrownBy(() -> service.runMavenBuild(projectRoot, Map.of("invalid", "value"))) + assertThatThrownBy(() -> service.runMavenBuild(projectRoot, Map.of("invalid", "http://value"))) .isInstanceOf(IOException.class); } diff --git "a/src/test/resources/e2e/Gr\303\266\303\237en & Preise (v1).ocl" "b/src/test/resources/e2e/Gr\303\266\303\237en & Preise (v1).ocl" new file mode 100644 index 0000000..968c448 --- /dev/null +++ "b/src/test/resources/e2e/Gr\303\266\303\237en & Preise (v1).ocl" @@ -0,0 +1,5 @@ +-- every component must be named +context model::Component inv componentHasName: + @severity CRITICAL + @message "Component without name" + self.name != "" diff --git a/src/test/resources/e2e/model.ecore b/src/test/resources/e2e/model.ecore new file mode 100644 index 0000000..008b60a --- /dev/null +++ b/src/test/resources/e2e/model.ecore @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/e2e/model.genmodel b/src/test/resources/e2e/model.genmodel new file mode 100644 index 0000000..23db66a --- /dev/null +++ b/src/test/resources/e2e/model.genmodel @@ -0,0 +1,33 @@ + + + model.ecore + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/e2e/model2.ecore b/src/test/resources/e2e/model2.ecore new file mode 100644 index 0000000..385b16f --- /dev/null +++ b/src/test/resources/e2e/model2.ecore @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/e2e/model2.genmodel b/src/test/resources/e2e/model2.genmodel new file mode 100644 index 0000000..94c9258 --- /dev/null +++ b/src/test/resources/e2e/model2.genmodel @@ -0,0 +1,25 @@ + + + model2.ecore + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/e2e/templateReactions.reactions b/src/test/resources/e2e/templateReactions.reactions new file mode 100644 index 0000000..b31a2e3 --- /dev/null +++ b/src/test/resources/e2e/templateReactions.reactions @@ -0,0 +1,160 @@ + +import java.io.File; + +import "http://vitruv.tools/methodologisttemplate/model" as model +import "http://vitruv.tools/methodologisttemplate/model2" as model2 + +reactions: model2Model2 +in reaction to changes in model +execute actions in model2 + +// insert a System, which is the root element of model, into an instance of model +// as a reaction, an element of type Root should be created, persisted relatively, +// and a correspondence should be added (see the called routine) +reaction SystemInsertedAsRoot { + after element model::System inserted as root + // newValue refers to the newly inserted element of type System (provided by the reactions runtime environment at runtime) + call createAndRegisterRoot(newValue) +} + +routine createAndRegisterRoot(model::System system) { + match { + // we do only want to create a new corresponding Root if we not have one already and the old one has, e.g., only been moved + require absence of model2::Root corresponding to system + } + create { + // short way of using the respective Factory calls, which would be used in the update-block + val mRoot = new model2::Root + } + update { + // save the newly created Root element at the specified location + persistProjectRelative(system, mRoot, new File("").toString() + "example.model2") + // register the correspondence so we can find mRoot later, if we modify something in system and need to adapt mRoot accordingly + addCorrespondenceBetween(system, mRoot) + } +} + +// a Component is mapped to an Entity in model2. +reaction ComponentInsertedIntoSystem { + // the brackets [ ] are used to denote a reference inside a metaclass (see model.ecore line 23 in the model project) + after element model::Component inserted in model::System[components] + call createAndInsertEntity(affectedEObject, newValue) +} + +routine createAndInsertEntity(model::System system, model::Component component) { + match { + require absence of model2::Entity corresponding to component + // retrieve the mRoot we added a correspondence in the createAndRegisterRoot routine in the update block (line 33 in this file) + val mRoot = retrieve model2::Root corresponding to system + } + create { + val entity = new model2::Entity + } + update { + entity.name = component.name + mRoot.entities.add(entity) + addCorrespondenceBetween(component, entity) + } +} + +// we replaced a single-valued attribute value, in this case the name of a component, with a new name. +reaction ComponentRenamed { + after attribute replaced at model::Component[name] + // affectedEObject refers to the modified element (provided by the reactions runtime environment at runtime). The change is already applied, so affectedEObject.name is the new name. alternatively, we could use newValue to get the name. + call renameEntity(affectedEObject) +} + +routine renameEntity(model::Component component) { + match { + val entity = retrieve model2::Entity corresponding to component + } + // we can omit blocks like the update block if we do not need them + update { + entity.name = component.name + } +} + +reaction ComponentDeleted { + after element model::Component deleted + call deleteEntity(affectedEObject) +} + +routine deleteEntity(model::Component component) { + match { + val entity = retrieve model2::Entity corresponding to component + } + update { + // remove the corresponding object as well + removeObject(entity) + // cleanup of the correspondence model so it does not contain links to invalid, i.e., deleted, model elements + removeCorrespondenceBetween(entity, component) + } +} + +reaction ProtocolInsertedIntoSystem { + after element model::Protocol inserted in model::System[protocols] + call createAndInsertProtocol(affectedEObject, newValue) +} + +routine createAndInsertProtocol(model::System system, model::Protocol protocol) { + match { + require absence of model2::CommunicationStandard corresponding to protocol + val mRoot = retrieve model2::Root corresponding to system + } + create { + val mStandard = new model2::CommunicationStandard + } + update { + mStandard.name = protocol.name + addCorrespondenceBetween(protocol, mStandard) + } +} + +reaction LinkInsertedIntoSystem { + after element model::Link inserted in model::System[links] + call createAndInsertLink(affectedEObject, newValue) +} + +routine createAndInsertLink(model::System system, model::Link link) { + match { + require absence of model2::Link corresponding to link + val mRoot = retrieve model2::Root corresponding to system + } + create { + val mLink = new model2::Link + } + update { + mRoot.links.add(mLink) + addCorrespondenceBetween(link, mLink) + } +} + +reaction ComponentInsertedIntoLink { + after element model::Component inserted in model::Link[components] + call updateLinkEntities(affectedEObject, newValue) +} + +routine updateLinkEntities(model::Link link, model::Component component) { + match { + val mEntity = retrieve model2::Entity corresponding to component + val mLink = retrieve model2::Link corresponding to link + } + update { + mLink.entities.add(mEntity) + } +} + +reaction ProtocolInsertedIntoLink { + after element model::Protocol replaced at model::Link[protocol] + call updateLinkProtocols(affectedEObject, newValue) +} + +routine updateLinkProtocols(model::Link link, model::Protocol protocol) { + match { + val mStandard = retrieve model2::CommunicationStandard corresponding to protocol + val mLink = retrieve model2::Link corresponding to link + } + update { + mLink.standard = mStandard + } +} \ No newline at end of file From 9d869d9ebc56267b939d9262b3a10eadb9b1b397 Mon Sep 17 00:00:00 2001 From: Max Oesterle Date: Wed, 28 Oct 2026 14:46:17 +0100 Subject: [PATCH 2/8] describe constraint files and versions of generated VSUM projects --- README.md | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 5a48ba8..a1e6e87 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ A Spring Boot REST API service for the Vitruv methodologist workflow. It validates and standardizes GenModel files for MWE2 compatibility, and generates ready-to-build VSUM projects from uploaded -metamodel, genmodel, and reaction files. +metamodel, genmodel, reaction, and OCL constraint files. ## Features @@ -11,6 +11,8 @@ metamodel, genmodel, and reaction files. - **VSUM Project Generation**: Build a complete VSUM project from metamodels, genmodels, and reactions, returned as a zip archive - **VSUM Jar Build**: Build the project and return only the executable jar-with-dependencies +- **OCL Constraints**: Build VitruvOCL constraint files into the VSUM, where its Vitruv server + lists, validates, and manages them via REST - **OpenAPI / Swagger UI**: Interactive API documentation - **Error Handling**: Centralized exception handling with structured error responses - **Docker Support**: Dockerfile and Compose setup included @@ -103,6 +105,7 @@ Parts: | `metamodelFiles` | yes | One or more `.ecore` metamodel files | | `genmodelFiles` | yes | `.genmodel` files, paired **by index** with `metamodelFiles` | | `reactionFiles` | yes | One or more `.reactions` files | +| `constraintFiles` | no | VitruvOCL constraint files (`.ocl`), see [Constraints](#constraints) | `metamodelFiles` and `genmodelFiles` must have the same count — index *n* of one is matched with index *n* of the other. Reaction imports are normalized against the uploaded metamodels' nsURIs. @@ -112,10 +115,25 @@ curl -X POST \ -F "metamodelFiles=@model.ecore" \ -F "genmodelFiles=@model.genmodel" \ -F "reactionFiles=@example.reactions" \ + -F "constraintFiles=@Prices.ocl" \ -o vsum-project.zip \ http://localhost:8090/api/vsum/build ``` +#### Constraints + +Each constraint file is copied to `vsum/src/main/resources/constraints/` and registered in the +generated `VSUMExample` with the `VitruvOclConstraintChecker` of VitruvOCL. The running VSUM then +lists, validates, creates, updates, and deletes its constraints via the constraint endpoints of the +[Vitruv-Server](https://github.com/vitruv-tools/Vitruv-Server) (`/vsum/constraints`). + +- The file name is kept, e.g. the name of a rule set; only characters that are invalid in file + names are replaced, and duplicates get a numeric suffix. +- Every context must name its metamodel (`context model::Component inv …`), and the metamodel must + be one of the uploaded ones. Otherwise the request fails fast with `400` and error code + `VSUM_INPUT_ERROR`; all other errors in a constraint show up when the VSUM loads it. +- Empty constraint files are rejected with `400`. + ### Build VSUM Jar **POST** `/api/vsum/jar` (`multipart/form-data`) @@ -191,6 +209,27 @@ Default settings: - OpenAPI docs: `/api-docs` - Log level for `tools.vitruv.methodologist`: `DEBUG` +### Versions of generated projects + +Generated VSUM projects use the Vitruvius versions of `GeneratedProjectVersions`, which can be +overridden with `vsum.generator.versions.{parent,change,framework,dsls,server,vitruvocl}`: + +| Property | Default | Artifacts | +| --- | --- | --- | +| `parent` | `4.0.0` | `tools.vitruv:parent` | +| `change` | `4.0.1` | `tools.vitruv.change.*` | +| `framework` | `4.0.2-SNAPSHOT` | `tools.vitruv.framework.*`, must provide the constraint SPI | +| `dsls` | `4.0.0` | Reactions language and runtime | +| `server` | `4.0.1-SNAPSHOT` | `tools.vitruv.server.remote`, must provide the constraint endpoints | +| `vitruvocl` | `0.1.0-SNAPSHOT` | `tools.vitruv.dsls:vitruvocl-language` | + +Snapshot versions are resolved from the Maven Central snapshots. The service builds the projects +with the local Maven installation, so artifacts installed into the local repository +(`mvn install`) are used as well — e.g. to test unreleased changes of Vitruv, VitruvOCL, or the +Vitruv-Server. When running the service in Docker, the container has its own Maven repository. + +Generated VSUM jars need Java 21 to run. + ## Technologies - **Framework**: Spring Boot 4.0.6 From 106a2b0413c07a9bf8f5e9cd3c40d080e4877c03 Mon Sep 17 00:00:00 2001 From: Max Oesterle Date: Sun, 1 Nov 2026 21:16:47 +0100 Subject: [PATCH 3/8] generate projects with VitruviusOCL --- README.md | 9 +++++---- .../setup/config/GeneratedProjectVersions.java | 4 ++-- src/main/resources/templates/rootPom.ftl | 4 ++-- src/main/resources/templates/vsumPom.ftl | 4 ++-- .../service/GenerateFromTemplateConstraintsTest.java | 7 ++++--- 5 files changed, 15 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index a1e6e87..affd6a7 100644 --- a/README.md +++ b/README.md @@ -217,16 +217,17 @@ overridden with `vsum.generator.versions.{parent,change,framework,dsls,server,vi | Property | Default | Artifacts | | --- | --- | --- | | `parent` | `4.0.0` | `tools.vitruv:parent` | -| `change` | `4.0.1` | `tools.vitruv.change.*` | +| `change` | `4.0.2-SNAPSHOT` | `tools.vitruv.change.*`, must provide `Uuid.getRawValue()` | | `framework` | `4.0.2-SNAPSHOT` | `tools.vitruv.framework.*`, must provide the constraint SPI | | `dsls` | `4.0.0` | Reactions language and runtime | | `server` | `4.0.1-SNAPSHOT` | `tools.vitruv.server.remote`, must provide the constraint endpoints | -| `vitruvocl` | `0.1.0-SNAPSHOT` | `tools.vitruv.dsls:vitruvocl-language` | +| `vitruvocl` | `0.1.0-SNAPSHOT` | `tools.vitruv:tools.vitruv.vitruvocl.language` from [VitruviusOCL](https://github.com/vitruv-tools/VitruviusOCL) | Snapshot versions are resolved from the Maven Central snapshots. The service builds the projects with the local Maven installation, so artifacts installed into the local repository -(`mvn install`) are used as well — e.g. to test unreleased changes of Vitruv, VitruvOCL, or the -Vitruv-Server. When running the service in Docker, the container has its own Maven repository. +(`mvn install`) are used as well — e.g. to test unreleased changes of Vitruv-Change, Vitruv, +VitruviusOCL, or the Vitruv-Server (install them in this order). When running the service in +Docker, the container has its own Maven repository. Generated VSUM jars need Java 21 to run. diff --git a/src/main/java/tools/vitruv/methodologist/setup/config/GeneratedProjectVersions.java b/src/main/java/tools/vitruv/methodologist/setup/config/GeneratedProjectVersions.java index 32c9179..d6c7673 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/config/GeneratedProjectVersions.java +++ b/src/main/java/tools/vitruv/methodologist/setup/config/GeneratedProjectVersions.java @@ -17,7 +17,7 @@ public class GeneratedProjectVersions { private String parent = "4.0.0"; /** Version of the Vitruv-Change artifacts ({@code tools.vitruv.change.*}). */ - private String change = "4.0.1"; + private String change = "4.0.2-SNAPSHOT"; /** Version of the Vitruv framework artifacts ({@code tools.vitruv.framework.*}). */ private String framework = "4.0.2-SNAPSHOT"; @@ -28,6 +28,6 @@ public class GeneratedProjectVersions { /** Version of the Vitruv server ({@code tools.vitruv.server.remote}). */ private String server = "4.0.1-SNAPSHOT"; - /** Version of VitruvOCL ({@code tools.vitruv.dsls:vitruvocl-language}). */ + /** Version of VitruvOCL ({@code tools.vitruv:tools.vitruv.vitruvocl.language}). */ private String vitruvocl = "0.1.0-SNAPSHOT"; } diff --git a/src/main/resources/templates/rootPom.ftl b/src/main/resources/templates/rootPom.ftl index a4042e7..b1ae9c9 100644 --- a/src/main/resources/templates/rootPom.ftl +++ b/src/main/resources/templates/rootPom.ftl @@ -102,8 +102,8 @@ ${vitruv-server.version} - tools.vitruv.dsls - vitruvocl-language + tools.vitruv + tools.vitruv.vitruvocl.language ${vitruvocl.version} diff --git a/src/main/resources/templates/vsumPom.ftl b/src/main/resources/templates/vsumPom.ftl index e88ac82..fcab2a7 100644 --- a/src/main/resources/templates/vsumPom.ftl +++ b/src/main/resources/templates/vsumPom.ftl @@ -47,8 +47,8 @@ <#if hasConstraints> - tools.vitruv.dsls - vitruvocl-language + tools.vitruv + tools.vitruv.vitruvocl.language diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/GenerateFromTemplateConstraintsTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/GenerateFromTemplateConstraintsTest.java index 1ca605c..730c332 100644 --- a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/GenerateFromTemplateConstraintsTest.java +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/GenerateFromTemplateConstraintsTest.java @@ -39,7 +39,8 @@ void rootPomUsesConfiguredVersions() throws Exception { generator.generateRootPom(target.toFile(), PACKAGE_NAME); - String content = Files.readString(target); + // templates may have CRLF line endings depending on the checkout + String content = Files.readString(target).replace("\r\n", "\n"); assertTrue(content.contains("parent\n 9.0.0")); assertTrue(content.contains("9.1.0")); assertTrue(content.contains("9.2.0-SNAPSHOT")); @@ -71,9 +72,9 @@ void vsumPomDependsOnVitruvOclOnlyWithConstraints() throws Exception { generator.generateVsumPom(without.toFile(), PACKAGE_NAME); generator.generateVsumPom(with.toFile(), PACKAGE_NAME, true); - assertFalse(Files.readString(without).contains("vitruvocl-language")); + assertFalse(Files.readString(without).contains("tools.vitruv.vitruvocl.language")); String content = Files.readString(with); - assertTrue(content.contains("vitruvocl-language")); + assertTrue(content.contains("tools.vitruv.vitruvocl.language")); assertFalse(content.contains("3.2.3")); } From 6536e74fe95007b7104403105ebedb0c7e6753f2 Mon Sep 17 00:00:00 2001 From: Max Oesterle Date: Mon, 2 Nov 2026 15:48:01 +0100 Subject: [PATCH 4/8] type-check uploaded OCL constraints before building a VSUM --- pom.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/pom.xml b/pom.xml index 16180ee..62b04d6 100644 --- a/pom.xml +++ b/pom.xml @@ -33,6 +33,9 @@ vitruv-tools vitruv-tools_Methodologist-SetupService + + 0.1.0-SNAPSHOT @@ -69,6 +72,11 @@ org.eclipse.emf.codegen.ecore 2.35.0 + + tools.vitruv + tools.vitruv.vitruvocl.language + ${vitruvocl.version} + org.springdoc From 00c4f0e632d4a78a60f662192cbdeaedbee78af6 Mon Sep 17 00:00:00 2001 From: Max Oesterle Date: Mon, 2 Nov 2026 16:39:43 +0100 Subject: [PATCH 5/8] reject uploaded OCL constraints with syntax or type errors before the build --- .../vsum/service/ConstraintTypeCheck.java | 80 +++++++++++++++++++ .../setup/vsum/service/ConstraintUploads.java | 4 +- .../vsum/service/VsumProjectBuildService.java | 3 + ...sumProjectBuildServiceConstraintsTest.java | 67 +++++++++++++++- 4 files changed, 150 insertions(+), 4 deletions(-) create mode 100644 src/main/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintTypeCheck.java diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintTypeCheck.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintTypeCheck.java new file mode 100644 index 0000000..127e4f7 --- /dev/null +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintTypeCheck.java @@ -0,0 +1,80 @@ +package tools.vitruv.methodologist.setup.vsum.service; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.List; +import java.util.stream.Collectors; +import tools.vitruv.dsls.vitruvocl.common.CompileError; +import tools.vitruv.dsls.vitruvocl.pipeline.ConstraintResult; +import tools.vitruv.dsls.vitruvocl.pipeline.MetamodelWrapper; +import tools.vitruv.dsls.vitruvocl.pipeline.VitruvOCL; +import tools.vitruv.methodologist.setup.exception.MethodologistSetupException; + +/** + * Compiles uploaded VitruviusOCL constraint files against the uploaded metamodels, so that a VSUM + * with invalid constraints is not built: the generated VSUM would load the constraints only when it + * starts, and fail then. + * + *

The metamodels are loaded into a wrapper of each check instead of the global package registry, + * so concurrent builds do not affect each other. + */ +final class ConstraintTypeCheck { + private static final String VSUM_INPUT_ERROR_CODE = "VSUM_INPUT_ERROR"; + + /** At most this many errors are reported per file, the first ones are the most helpful. */ + private static final int MAX_REPORTED_ERRORS = 5; + + private ConstraintTypeCheck() {} + + /** + * Compiles each constraint file against the given metamodels. + * + * @param constraintFiles the constraint files + * @param metamodelFiles the {@code .ecore} files of the VSUM + * @throws IOException when reading a file fails + * @throws MethodologistSetupException when a file has syntax or type errors, naming the file and + * the line (from 1) and column (from 0) of each error + */ + static void check(List constraintFiles, List metamodelFiles) throws IOException { + if (constraintFiles.isEmpty()) { + return; + } + MetamodelWrapper metamodels = new MetamodelWrapper(); + for (File metamodelFile : metamodelFiles) { + metamodels.loadMetamodel(metamodelFile.toPath()); + } + for (File constraintFile : constraintFiles) { + String content = withoutImports(Files.readString(constraintFile.toPath())); + if (content.isBlank()) { + continue; + } + ConstraintResult result = VitruvOCL.evaluateConstraint(content, metamodels); + List errors = result.getCompilerErrors(); + if (!errors.isEmpty()) { + throw new MethodologistSetupException( + VSUM_INPUT_ERROR_CODE, + String.format( + "Constraint file %s has errors: %s", + constraintFile.getName(), + errors.stream() + .limit(MAX_REPORTED_ERRORS) + .map( + error -> + String.format( + "line %d, column %d: %s", + error.getLine(), error.getColumn(), error.getMessage())) + .collect(Collectors.joining("; ")))); + } + } + } + + /** Removes import declarations, keeping the line count so that positions stay valid. */ + private static String withoutImports(String content) { + StringBuilder result = new StringBuilder(); + for (String line : content.split("\\R", -1)) { + result.append(line.strip().startsWith("import ") ? "" : line).append('\n'); + } + return result.toString(); + } +} diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintUploads.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintUploads.java index 8ad828b..b1033a7 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintUploads.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintUploads.java @@ -89,8 +89,8 @@ static List write(Path directory, List constraintFiles) thr /** * Checks that every context declaration names its metamodel and that the metamodel is one of the * given metamodels, so that invalid constraints fail fast with a clear message instead of failing - * the VSUM at runtime. The constraints are not parsed completely, so other errors are only - * detected when the VSUM loads them. + * the VSUM at runtime. Other errors are found by compiling the constraints, see {@link + * ConstraintTypeCheck}. * * @param constraintFiles the constraint files * @param metamodelNames the package names of the uploaded metamodels 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 eaa5bca..5c506f4 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 @@ -154,6 +154,9 @@ private byte[] buildArtifact( ConstraintUploads.write(uploadWorkspace.resolve("constraints"), constraintFiles); ConstraintUploads.checkMetamodels( copiedConstraintFiles, extractMetamodelPackageNames(modelPairs)); + ConstraintTypeCheck.check( + copiedConstraintFiles, + modelPairs.stream().map(VsumService.ModelFiles::metamodelFile).toList()); return generator.generate( modelPairs, copiedReactionFiles, copiedConstraintFiles, metamodelNamespaceMap); } catch (IOException | MissingModelException e) { diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildServiceConstraintsTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildServiceConstraintsTest.java index e5d4790..84c425d 100644 --- a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildServiceConstraintsTest.java +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildServiceConstraintsTest.java @@ -6,6 +6,7 @@ import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.io.File; @@ -94,6 +95,61 @@ void rejectsConstraintsOfUnknownMetamodels() { .hasMessageContaining("shop.ocl"); } + @Test + void rejectsConstraintsWithTypeErrorsBeforeTheBuild() { + assertThatThrownBy( + () -> + service.buildProjectJar( + List.of(metamodel()), + List.of(genmodel()), + List.of(reaction()), + List.of( + constraint( + "Prices.ocl", + "-- prices\ncontext pcm::Item inv heavy: self.weight > 0")))) + .isInstanceOf(MethodologistSetupException.class) + .hasMessageContaining("Constraint file Prices.ocl has errors") + .hasMessageContaining("line 2, column " + "context pcm::Item inv heavy: self.".length()) + .hasMessageContaining("weight"); + verifyNoInteractions(vsumService); + } + + @Test + void rejectsConstraintsWithSyntaxErrorsBeforeTheBuild() { + assertThatThrownBy( + () -> + service.buildProjectJar( + List.of(metamodel()), + List.of(genmodel()), + List.of(reaction()), + List.of(constraint("Prices.ocl", "context pcm::Item inv a: self.price >")))) + .isInstanceOf(MethodologistSetupException.class) + .hasMessageContaining("Constraint file Prices.ocl has errors") + .hasMessageContaining("line 1"); + verifyNoInteractions(vsumService); + } + + @Test + void acceptsValidConstraintsWithImports() throws Exception { + when(vsumService.generateProjectJar(anyList(), anyList(), anyList(), anyMap())) + .thenReturn(new byte[] {3}); + + byte[] jar = + service.buildProjectJar( + List.of(metamodel()), + List.of(genmodel()), + List.of(reaction()), + List.of( + constraint( + "Prices.ocl", + "import pcm : 'http://pcm'\n" + + "context pcm::Item\n" + + " inv positive: self.price > 0\n" + + " inv cheap: self.price < 1000"))); + + assertThat(jar).containsExactly(3); + } + @Test void rejectsEmptyConstraintFiles() { assertThatThrownBy( @@ -135,8 +191,15 @@ private static MockMultipartFile metamodel() { "application/xml", """ - + + + + + """ .getBytes(StandardCharsets.UTF_8)); } From f6359bf5ce285df5c8eb6278a328e0798bd6027d Mon Sep 17 00:00:00 2001 From: Max Oesterle Date: Mon, 2 Nov 2026 19:46:04 +0100 Subject: [PATCH 6/8] keep generated VSUMs running without input and stop them on a stop signal --- src/main/resources/templates/vsumExample.ftl | 33 +++++++++++---- .../GenerateFromTemplateConstraintsTest.java | 15 +++++++ .../vsum/service/VsumBuildEndToEndTest.java | 42 +++++++++++++++++++ 3 files changed, 83 insertions(+), 7 deletions(-) diff --git a/src/main/resources/templates/vsumExample.ftl b/src/main/resources/templates/vsumExample.ftl index 8b1fd98..bd6c49a 100644 --- a/src/main/resources/templates/vsumExample.ftl +++ b/src/main/resources/templates/vsumExample.ftl @@ -15,6 +15,7 @@ import tools.vitruv.framework.views.ViewType; import tools.vitruv.framework.vsum.VirtualModel; import tools.vitruv.framework.remote.server.*; import java.util.Scanner; +import java.util.concurrent.CountDownLatch; import java.io.IOException; import java.io.UncheckedIOException; <#if constraintResources?has_content> @@ -25,21 +26,39 @@ import tools.vitruv.dsls.vitruvocl.vitruv.VitruvOclConstraintChecker; * This class provides an example how to define and use a VSUM. */ public class VSUMExample { - public static void main(String[] args) { + public static void main(String[] args) throws InterruptedException { try { VitruvServer server = new VitruvServer(VSUMExample::createDefaultVirtualModel); server.start(); - Scanner scanner = new Scanner(System.in); - while (!scanner.nextLine().equals("quit")) { - - } - scanner.close(); - server.stop(); + CountDownLatch stopped = new CountDownLatch(1); + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + server.stop(); + stopped.countDown(); + })); + stopOnQuit(); + stopped.await(); } catch (IOException e) { System.out.println("Something went wrong " + e); } } + /** + * Stops the server when "quit" is entered. Without input, e.g. in a container or as a service, + * the server keeps running until it is stopped with Ctrl+C or a stop signal. + */ + private static void stopOnQuit() { + Thread reader = new Thread(() -> { + Scanner scanner = new Scanner(System.in); + while (scanner.hasNextLine()) { + if (scanner.nextLine().equals("quit")) { + System.exit(0); + } + } + }, "quit-reader"); + reader.setDaemon(true); + reader.start(); + } + private static VirtualModel createDefaultVirtualModel() { Collection> viewTypes = createDefaultViewTypes(); try { diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/GenerateFromTemplateConstraintsTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/GenerateFromTemplateConstraintsTest.java index 730c332..c7ccdb6 100644 --- a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/GenerateFromTemplateConstraintsTest.java +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/GenerateFromTemplateConstraintsTest.java @@ -109,4 +109,19 @@ void vsumExampleWithoutConstraints() throws Exception { assertFalse(Files.readString(target).contains("VitruvOcl")); } + + @Test + @DisplayName("the VSUM keeps running without input and stops on a stop signal") + void vsumExampleRunsWithoutInput() throws Exception { + Path target = tempDir.resolve("VSUMExample.java"); + + generator.generateVsumExample( + target.toFile(), PACKAGE_NAME, List.of("Alpha"), List.of("mir.reactions.a.A"), List.of()); + + String example = Files.readString(target); + assertTrue(example.contains("Runtime.getRuntime().addShutdownHook(")); + assertTrue(example.contains("while (scanner.hasNextLine())")); + assertTrue(example.contains("reader.setDaemon(true);")); + assertFalse(example.contains("while (!scanner.nextLine().equals(\"quit\"))")); + } } 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 6f1ff7e..ddd4745 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 @@ -97,6 +97,48 @@ void builtVsumWithoutConstraintsStarts() throws Exception { } finally { stop(server); } + assertThat(server.exitValue()).as("quit stops the server normally").isZero(); + } + + @Test + void builtVsumKeepsRunningWithoutInput() throws Exception { + VsumProjectBuildService buildService = + new VsumProjectBuildService( + new VsumService(new GenerateFromTemplate(), new EcoreToGenmodelService())); + + byte[] jar = + buildService.buildProjectJar( + List.of(file("metamodelFiles", "model.ecore"), file("metamodelFiles", "model2.ecore")), + List.of( + file("genmodelFiles", "model.genmodel"), file("genmodelFiles", "model2.genmodel")), + List.of(file("reactionFiles", "templateReactions.reactions"))); + + Path jarFile = Files.write(runDirectory.resolve("vsum-detached.jar"), jar); + // like in a container or as a service: the input ends immediately + Path noInput = Files.createFile(runDirectory.resolve("no-input")); + Process server = + new ProcessBuilder("java", "-jar", jarFile.toString()) + .directory(runDirectory.toFile()) + .redirectInput(noInput.toFile()) + .redirectErrorStream(true) + .redirectOutput(runDirectory.resolve("server-detached.log").toFile()) + .start(); + try { + HttpClient http = HttpClient.newHttpClient(); + awaitHealthy(http, server); + Thread.sleep(2000); + assertThat(server.isAlive()).as("the VSUM server keeps running without input").isTrue(); + assertThat(get(http, "/vsum/constraints")).isEqualTo("[ ]"); + assertThat(runDirectory.resolve("server-detached.log")) + .as("the end of the input is no error") + .content() + .doesNotContain("Exception in thread"); + } finally { + server.destroy(); + if (!server.waitFor(10, java.util.concurrent.TimeUnit.SECONDS)) { + server.destroyForcibly(); + } + } } private static void awaitHealthy(HttpClient http, Process server) throws Exception { From 35206672cf02cfbba48203aa042ca3586e66b0fb Mon Sep 17 00:00:00 2001 From: Max Oesterle Date: Mon, 2 Nov 2026 21:27:10 +0100 Subject: [PATCH 7/8] describe that type-checked metamodels stay in the global package registry --- .../setup/vsum/service/ConstraintTypeCheck.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintTypeCheck.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintTypeCheck.java index 127e4f7..adb086b 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintTypeCheck.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/ConstraintTypeCheck.java @@ -16,8 +16,11 @@ * with invalid constraints is not built: the generated VSUM would load the constraints only when it * starts, and fail then. * - *

The metamodels are loaded into a wrapper of each check instead of the global package registry, - * so concurrent builds do not affect each other. + *

The metamodels are loaded into a wrapper of each check, which resolves the types of the + * constraints, so concurrent builds type-check against their own metamodels. The wrapper also + * registers the packages by nsURI in the global {@link org.eclipse.emf.ecore.EPackage.Registry}: + * there, builds with the same nsURI replace each other's packages, and the packages stay registered + * after the check. */ final class ConstraintTypeCheck { private static final String VSUM_INPUT_ERROR_CODE = "VSUM_INPUT_ERROR"; From 3ca402bd34c129cd47d89202aef6310a0f41ecbf Mon Sep 17 00:00:00 2001 From: Max Oesterle Date: Tue, 3 Nov 2026 15:16:52 +0100 Subject: [PATCH 8/8] style: apply spotless formatting --- .../methodologist/setup/vsum/service/VsumBuildProperties.java | 4 ++-- .../setup/vsum/service/VsumProjectBuildServiceTest.java | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) 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 f956b70..3d7e229 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 @@ -71,8 +71,8 @@ public class VsumBuildProperties { // Vitruvius is released per repository, so the artifact groups can have different versions. /** - * Version of the Vitruv-Change artifacts ({@code tools.vitruv.change.*}). It must provide the - * raw value of UUIDs, which the Vitruv server returns for violating elements. + * Version of the Vitruv-Change artifacts ({@code tools.vitruv.change.*}). It must provide the raw + * value of UUIDs, which the Vitruv server returns for violating elements. */ private String vitruvChangeVersion = "4.0.2-SNAPSHOT"; 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 1bc28ac..b39b462 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 @@ -91,7 +91,8 @@ void generatesAProjectFollowingTheMethodologistTemplate() throws IOException { String rootPom = Files.readString(projectRoot.resolve("pom.xml")); assertTrue(rootPom.contains("${vitruv.change.version}"), rootPom); - assertTrue(rootPom.contains("4.0.2-SNAPSHOT"), rootPom); + assertTrue( + rootPom.contains("4.0.2-SNAPSHOT"), rootPom); assertTrue(rootPom.contains("4.0.0"), rootPom); String workflow = Files.readString(projectRoot.resolve("model/workflow/generate.mwe2"));