Search in sources :

Example 26 with GeneratedFile

use of org.drools.codegen.common.GeneratedFile in project kogito-runtimes by kiegroup.

the class JsonSchemaGeneratorTest method testJsonSchemaGeneratorWithSpace.

@Test
public void testJsonSchemaGeneratorWithSpace() throws IOException {
    Collection<GeneratedFile> files = new JsonSchemaGenerator.ClassBuilder(Stream.of(WhitespacesTask.class)).build().generate();
    assertEquals(1, files.size());
    GeneratedFile file = files.iterator().next();
    assertEquals(JsonSchemaUtil.getJsonDir().resolve("InputOutput_name_with_spaces.json").toString(), file.relativePath());
}
Also used : GeneratedFile(org.drools.codegen.common.GeneratedFile) Test(org.junit.jupiter.api.Test)

Example 27 with GeneratedFile

use of org.drools.codegen.common.GeneratedFile in project kogito-runtimes by kiegroup.

the class ProcessCodegenTest method isEmpty.

@ParameterizedTest
@MethodSource("org.kie.kogito.codegen.api.utils.KogitoContextTestUtils#contextBuilders")
public void isEmpty(KogitoBuildContext.Builder contextBuilder) {
    KogitoBuildContext context = contextBuilder.build();
    ProcessCodegen emptyCodeGenerator = ProcessCodegen.ofCollectedResources(context, Collections.emptyList());
    assertThat(emptyCodeGenerator.isEmpty()).isTrue();
    assertThat(emptyCodeGenerator.isEnabled()).isFalse();
    Collection<GeneratedFile> emptyGeneratedFiles = emptyCodeGenerator.generate();
    assertThat(emptyGeneratedFiles.size()).isEqualTo(0);
    ProcessCodegen codeGenerator = ProcessCodegen.ofCollectedResources(context, CollectedResourceProducer.fromFiles(BASE_PATH, MESSAGE_USERTASK_SOURCE_FULL_SOURCE.toFile()));
    assertThat(codeGenerator.isEmpty()).isFalse();
    assertThat(codeGenerator.isEnabled()).isTrue();
    Collection<GeneratedFile> generatedFiles = codeGenerator.generate();
    assertThat(generatedFiles).hasSizeGreaterThanOrEqualTo(10);
}
Also used : KogitoBuildContext(org.kie.kogito.codegen.api.context.KogitoBuildContext) GeneratedFile(org.drools.codegen.common.GeneratedFile) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 28 with GeneratedFile

use of org.drools.codegen.common.GeneratedFile in project kogito-runtimes by kiegroup.

the class CodegenUserTaskTest method testRESTApiForMessageStartEvent.

@ParameterizedTest
@MethodSource("org.kie.kogito.codegen.api.utils.KogitoContextTestUtils#contextBuilders")
public void testRESTApiForMessageStartEvent(KogitoBuildContext.Builder contextBuilder) {
    KogitoBuildContext context = contextBuilder.build();
    ProcessCodegen codeGenerator = ProcessCodegen.ofCollectedResources(context, CollectedResourceProducer.fromFiles(BASE_PATH, MESSAGE_USERTASK_SOURCE_FULL_SOURCE.toFile()));
    Collection<GeneratedFile> generatedFiles = codeGenerator.generate();
    assertThat(generatedFiles).isNotEmpty();
    List<GeneratedFile> resources = generatedFiles.stream().filter(generatedFile -> generatedFile.relativePath().endsWith("org/kie/kogito/test/UserTasksProcessResource.java")).collect(Collectors.toList());
    if (context.hasRESTForGenerator(codeGenerator)) {
        assertThat(resources.size()).isEqualTo(1);
        CompilationUnit parsedResource = StaticJavaParser.parse(new String(resources.get(0).contents()));
        List<MethodDeclaration> completeTaskMethods = parsedResource.findAll(MethodDeclaration.class, md -> md.getNameAsString().startsWith("completeTask"));
        assertThat(completeTaskMethods).hasSize(2);
        completeTaskMethods.forEach(completeTaskMethod -> assertThat(context.getRestAnnotator().getEndpointValue(completeTaskMethod).map(url -> url.contains("/{id}/FirstTask/{taskId}") || url.contains("/{id}/SecondTask/{taskId}")).orElse(true)).isTrue());
    } else {
        assertThat(resources.size()).isZero();
    }
}
Also used : java.util(java.util) ProcessCodegen(org.kie.kogito.codegen.process.ProcessCodegen) KogitoBuildContext(org.kie.kogito.codegen.api.context.KogitoBuildContext) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Collectors(java.util.stream.Collectors) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) StaticJavaParser(com.github.javaparser.StaticJavaParser) Paths(java.nio.file.Paths) CollectedResourceProducer(org.kie.kogito.codegen.core.io.CollectedResourceProducer) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) CompilationUnit(com.github.javaparser.ast.CompilationUnit) Path(java.nio.file.Path) GeneratedFile(org.drools.codegen.common.GeneratedFile) MethodSource(org.junit.jupiter.params.provider.MethodSource) CompilationUnit(com.github.javaparser.ast.CompilationUnit) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) KogitoBuildContext(org.kie.kogito.codegen.api.context.KogitoBuildContext) ProcessCodegen(org.kie.kogito.codegen.process.ProcessCodegen) GeneratedFile(org.drools.codegen.common.GeneratedFile) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 29 with GeneratedFile

use of org.drools.codegen.common.GeneratedFile in project kogito-runtimes by kiegroup.

the class PersistenceGenerator method generateProtoMarshaller.

protected Collection<GeneratedFile> generateProtoMarshaller() {
    if (!hasProtoMarshaller(context())) {
        // TODO implement a validation check to verify that data classes implement Serializable
        LOGGER.debug("Proto marshaller generation is skipped because " + KOGITO_PERSISTENCE_PROTO_MARSHALLER + "=false");
        return Collections.emptyList();
    }
    Proto proto = protoGenerator.protoOfDataClasses(context().getPackageName(), "import \"kogito-types.proto\";");
    List<String> variableMarshallers = new ArrayList<>();
    String protoContent = proto.serialize();
    List<CompilationUnit> marshallers;
    try {
        marshallers = marshallerGenerator.generate(protoContent);
    } catch (IOException e) {
        throw new UncheckedIOException("Impossible to obtain marshaller CompilationUnits", e);
    }
    Collection<GeneratedFile> protoFiles = new ArrayList<>();
    try {
        String typesURI = "META-INF/kogito-types.proto";
        protoFiles.add(new GeneratedFile(GeneratedFileType.INTERNAL_RESOURCE, typesURI, IOUtils.toString(context().getClassLoader().getResourceAsStream(typesURI))));
    } catch (IOException e) {
        throw new UncheckedIOException("Cannot find kogito types protobuf!", e);
    }
    // generate proto files leads to problems as it has a reverse dependency of kogito-index
    String typesURI = "META-INF/application-types.proto";
    protoFiles.add(new GeneratedFile(GeneratedFileType.INTERNAL_RESOURCE, typesURI, protoContent));
    Collection<GeneratedFile> generatedFiles = new ArrayList<>(protoFiles);
    if (!marshallers.isEmpty()) {
        List<CompilationUnit> files = new ArrayList<>(marshallers);
        variableMarshallers.add("org.kie.kogito.persistence.StringProtostreamBaseMarshaller");
        variableMarshallers.add("org.kie.kogito.persistence.BooleanProtostreamBaseMarshaller");
        variableMarshallers.add("org.kie.kogito.persistence.DateProtostreamBaseMarshaller");
        variableMarshallers.add("org.kie.kogito.persistence.DoubleProtostreamBaseMarshaller");
        variableMarshallers.add("org.kie.kogito.persistence.FloatProtostreamBaseMarshaller");
        variableMarshallers.add("org.kie.kogito.persistence.IntegerProtostreamBaseMarshaller");
        variableMarshallers.add("org.kie.kogito.persistence.LongProtostreamBaseMarshaller");
        variableMarshallers.add("org.kie.kogito.persistence.InstantProtostreamBaseMarshaller");
        variableMarshallers.add("org.kie.kogito.persistence.SerializableProtostreamBaseMarshaller");
        for (CompilationUnit unit : files) {
            String packageName = unit.getPackageDeclaration().map(pd -> pd.getName().toString()).orElse("");
            Optional<ClassOrInterfaceDeclaration> clazz = unit.findFirst(ClassOrInterfaceDeclaration.class);
            clazz.ifPresent(c -> {
                String clazzName = packageName + "." + c.getName().toString();
                variableMarshallers.add(clazzName);
                generatedFiles.add(new GeneratedFile(GeneratedFileType.SOURCE, clazzName.replace('.', '/') + JAVA, unit.toString()));
            });
        }
        // we build the marshaller for protostream
        TemplatedGenerator generatorProtostreamSerialization = TemplatedGenerator.builder().withTemplateBasePath(CLASS_TEMPLATES_PERSISTENCE).withFallbackContext(JavaKogitoBuildContext.CONTEXT_NAME).withPackageName(KOGITO_PROCESS_INSTANCE_PACKAGE).build(context(), "ProtostreamObjectMarshaller");
        CompilationUnit parsedClazzFile = generatorProtostreamSerialization.compilationUnitOrThrow();
        String packageName = parsedClazzFile.getPackageDeclaration().map(pd -> pd.getName().toString()).orElse("");
        ClassOrInterfaceDeclaration clazz = parsedClazzFile.findFirst(ClassOrInterfaceDeclaration.class).orElseThrow(() -> new InvalidTemplateException(generatorProtostreamSerialization, "Failed to find template for ProtostreamObjectMarshaller"));
        ConstructorDeclaration constructor = clazz.getDefaultConstructor().orElseThrow(() -> new InvalidTemplateException(generatorProtostreamSerialization, "Failed to find default constructor in template for ProtostreamObjectMarshaller"));
        // register protofiles and marshallers
        BlockStmt body = new BlockStmt();
        Expression newFileDescriptorSource = new ObjectCreationExpr(null, new ClassOrInterfaceType(null, FileDescriptorSource.class.getCanonicalName()), NodeList.nodeList());
        Expression getClassLoader = new MethodCallExpr(new MethodCallExpr(null, "getClass", NodeList.nodeList()), "getClassLoader", NodeList.nodeList());
        Expression chainExpression = newFileDescriptorSource;
        for (GeneratedFile generatedFile : protoFiles) {
            String path = generatedFile.relativePath();
            String name = generatedFile.path().getFileName().toString();
            if (!name.endsWith(".proto")) {
                continue;
            }
            Expression getISKogito = new MethodCallExpr(getClassLoader, "getResourceAsStream", NodeList.nodeList(new StringLiteralExpr(path)));
            chainExpression = new MethodCallExpr(new EnclosedExpr(chainExpression), "addProtoFile", NodeList.nodeList(new StringLiteralExpr(name), getISKogito));
        }
        body.addStatement(new MethodCallExpr(new NameExpr("context"), "registerProtoFiles", NodeList.nodeList(chainExpression)));
        for (String baseMarshallers : variableMarshallers) {
            Expression newMarshallerExpr = new ObjectCreationExpr(null, new ClassOrInterfaceType(null, baseMarshallers), NodeList.nodeList());
            body.addStatement(new MethodCallExpr(new NameExpr("context"), "registerMarshaller", NodeList.nodeList(newMarshallerExpr)));
        }
        CatchClause catchClause = new CatchClause(new Parameter().setType(IOException.class).setName("e"), new BlockStmt());
        TryStmt tryStmt = new TryStmt(body, NodeList.nodeList(catchClause), null);
        constructor.getBody().addStatement(tryStmt);
        String fqnProtoStreamMarshaller = packageName + "." + clazz.getName().toString();
        generatedFiles.add(new GeneratedFile(GeneratedFileType.SOURCE, fqnProtoStreamMarshaller.replace('.', '/') + JAVA, parsedClazzFile.toString()));
        String objectMarshallerStrategyServiceDescriptor = "";
        try {
            // try to find an existing ObjectMarshallerStrategy descriptor in the classpath to be appended to the ProtoStream generated one
            objectMarshallerStrategyServiceDescriptor = IOUtils.toString(getClass().getResourceAsStream("/META-INF/services/org.kie.kogito.serialization.process.ObjectMarshallerStrategy"), "UTF-8");
        } catch (Exception e) {
            LOGGER.warn("No existing ObjectMarshallerStrategy found the the classpath to be included with the ProtoS generated one for SPI.");
        }
        objectMarshallerStrategyServiceDescriptor += "\n" + fqnProtoStreamMarshaller + "\n";
        generatedFiles.add(new GeneratedFile(GeneratedFileType.INTERNAL_RESOURCE, "META-INF/services/org.kie.kogito.serialization.process.ObjectMarshallerStrategy", objectMarshallerStrategyServiceDescriptor));
    }
    return generatedFiles;
}
Also used : ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) Parameter(com.github.javaparser.ast.body.Parameter) LoggerFactory(org.slf4j.LoggerFactory) ProtoGenerator(org.kie.kogito.codegen.process.persistence.proto.ProtoGenerator) ArrayList(java.util.ArrayList) Proto(org.kie.kogito.codegen.process.persistence.proto.Proto) CatchClause(com.github.javaparser.ast.stmt.CatchClause) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) AbstractGenerator(org.kie.kogito.codegen.core.AbstractGenerator) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) Expression(com.github.javaparser.ast.expr.Expression) CompilationUnit(com.github.javaparser.ast.CompilationUnit) MarshallerGenerator(org.kie.kogito.codegen.process.persistence.marshaller.MarshallerGenerator) FileDescriptorSource(org.infinispan.protostream.FileDescriptorSource) NodeList(com.github.javaparser.ast.NodeList) KogitoBuildContext(org.kie.kogito.codegen.api.context.KogitoBuildContext) InvalidTemplateException(org.kie.kogito.codegen.api.template.InvalidTemplateException) Logger(org.slf4j.Logger) JavaKogitoBuildContext(org.kie.kogito.codegen.api.context.impl.JavaKogitoBuildContext) TemplatedGenerator(org.kie.kogito.codegen.api.template.TemplatedGenerator) Collection(java.util.Collection) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) IOException(java.io.IOException) ApplicationSection(org.kie.kogito.codegen.api.ApplicationSection) NameExpr(com.github.javaparser.ast.expr.NameExpr) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) EnclosedExpr(com.github.javaparser.ast.expr.EnclosedExpr) UncheckedIOException(java.io.UncheckedIOException) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) TryStmt(com.github.javaparser.ast.stmt.TryStmt) Optional(java.util.Optional) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) Collections(java.util.Collections) GeneratedFile(org.drools.codegen.common.GeneratedFile) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) GeneratedFileType(org.drools.codegen.common.GeneratedFileType) TemplatedGenerator(org.kie.kogito.codegen.api.template.TemplatedGenerator) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) ArrayList(java.util.ArrayList) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) NameExpr(com.github.javaparser.ast.expr.NameExpr) UncheckedIOException(java.io.UncheckedIOException) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) GeneratedFile(org.drools.codegen.common.GeneratedFile) Proto(org.kie.kogito.codegen.process.persistence.proto.Proto) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) CompilationUnit(com.github.javaparser.ast.CompilationUnit) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) TryStmt(com.github.javaparser.ast.stmt.TryStmt) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) CatchClause(com.github.javaparser.ast.stmt.CatchClause) InvalidTemplateException(org.kie.kogito.codegen.api.template.InvalidTemplateException) InvalidTemplateException(org.kie.kogito.codegen.api.template.InvalidTemplateException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) Expression(com.github.javaparser.ast.expr.Expression) Parameter(com.github.javaparser.ast.body.Parameter) EnclosedExpr(com.github.javaparser.ast.expr.EnclosedExpr) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 30 with GeneratedFile

use of org.drools.codegen.common.GeneratedFile in project kogito-runtimes by kiegroup.

the class AbstractCodegenIT method generateCode.

protected Application generateCode(Map<TYPE, List<String>> resourcesTypeMap, KogitoBuildContext context) throws Exception {
    ApplicationGenerator appGen = new ApplicationGenerator(context);
    for (TYPE type : TYPE.values()) {
        if (resourcesTypeMap.containsKey(type) && !resourcesTypeMap.get(type).isEmpty()) {
            appGen.registerGeneratorIfEnabled(generatorTypeMap.get(type).apply(context, resourcesTypeMap.get(type)));
        }
    }
    Collection<GeneratedFile> generatedFiles = appGen.generate();
    MemoryFileSystem srcMfs = new MemoryFileSystem();
    MemoryFileSystem trgMfs = new MemoryFileSystem();
    List<String> sources = new ArrayList<>();
    for (GeneratedFile entry : generatedFiles) {
        String fileName = entry.relativePath();
        if (!fileName.endsWith(".java")) {
            continue;
        }
        sources.add(fileName);
        srcMfs.write(fileName, entry.contents());
        log(new String(entry.contents()));
    }
    if (resourcesTypeMap.size() == 1 && resourcesTypeMap.containsKey(TYPE.PROCESS)) {
        sources.add("org/drools/project/model/ProjectRuntime.java");
        srcMfs.write("org/drools/project/model/ProjectRuntime.java", DUMMY_PROCESS_RUNTIME.getBytes());
    }
    if (LOGGER.isDebugEnabled()) {
        Path temp = Files.createTempDirectory("KOGITO_TESTS");
        LOGGER.debug("Dumping generated files in " + temp);
        for (GeneratedFile entry : generatedFiles) {
            Path fpath = temp.resolve(entry.relativePath());
            fpath.getParent().toFile().mkdirs();
            Files.write(fpath, entry.contents());
        }
    }
    CompilationResult result = JAVA_COMPILER.compile(sources.toArray(new String[sources.size()]), srcMfs, trgMfs, this.getClass().getClassLoader());
    assertThat(result).isNotNull();
    assertThat(result.getErrors()).describedAs(String.join("\n\n", Arrays.toString(result.getErrors()))).hasSize(0);
    classloader = new TestClassLoader(this.getClass().getClassLoader(), trgMfs.getMap());
    @SuppressWarnings("unchecked") Class<Application> app = (Class<Application>) Class.forName(context.getPackageName() + ".Application", true, classloader);
    return app.getDeclaredConstructor().newInstance();
}
Also used : Path(java.nio.file.Path) PortablePath(org.drools.util.PortablePath) ArrayList(java.util.ArrayList) GeneratedFile(org.drools.codegen.common.GeneratedFile) MemoryFileSystem(org.drools.compiler.compiler.io.memory.MemoryFileSystem) ApplicationGenerator(org.kie.kogito.codegen.core.ApplicationGenerator) CompilationResult(org.kie.memorycompiler.CompilationResult) Application(org.kie.kogito.Application)

Aggregations

GeneratedFile (org.drools.codegen.common.GeneratedFile)79 KogitoBuildContext (org.kie.kogito.codegen.api.context.KogitoBuildContext)39 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)36 MethodSource (org.junit.jupiter.params.provider.MethodSource)36 CompilationUnit (com.github.javaparser.ast.CompilationUnit)21 Collection (java.util.Collection)20 ArrayList (java.util.ArrayList)19 List (java.util.List)19 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)15 Collectors (java.util.stream.Collectors)15 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)15 File (java.io.File)13 Test (org.junit.jupiter.api.Test)12 Paths (java.nio.file.Paths)11 Collections (java.util.Collections)10 GeneratedFileType (org.drools.codegen.common.GeneratedFileType)10 CollectedResourceProducer (org.kie.kogito.codegen.core.io.CollectedResourceProducer)10 Path (java.nio.file.Path)9 Optional (java.util.Optional)9 CollectedResource (org.kie.kogito.codegen.api.io.CollectedResource)8