Search in sources :

Example 1 with Proto

use of org.kie.kogito.codegen.process.persistence.proto.Proto in project kogito-runtimes by kiegroup.

the class AbstractMarshallerGeneratorTest method testEnumMarshallers.

@Test
void testEnumMarshallers() {
    Stream.of(Answer.class, AnswerWithAnnotations.class).forEach(e -> {
        ProtoGenerator generator = protoGeneratorBuilder().withDataClasses(convertTypes(e)).build(null);
        Proto proto = generator.protoOfDataClasses("org.kie.kogito.test");
        assertThat(proto).isNotNull();
        assertThat(proto.getEnums()).hasSize(1);
        MarshallerGenerator marshallerGenerator = withGenerator(e);
        List<CompilationUnit> classes = null;
        try {
            classes = marshallerGenerator.generate(proto.serialize());
        } catch (IOException ex) {
            fail("Error generating marshaller for " + e.getName(), e);
        }
        assertThat(classes).isNotNull();
        assertThat(classes).hasSize(1);
        Optional<ClassOrInterfaceDeclaration> marshallerClass = classes.get(0).getClassByName(e.getSimpleName() + "EnumMarshaller");
        assertThat(marshallerClass).isPresent();
    });
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) Answer(org.kie.kogito.codegen.data.Answer) Proto(org.kie.kogito.codegen.process.persistence.proto.Proto) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) IOException(java.io.IOException) AnswerWithAnnotations(org.kie.kogito.codegen.data.AnswerWithAnnotations) ProtoGenerator(org.kie.kogito.codegen.process.persistence.proto.ProtoGenerator) AbstractProtoGenerator(org.kie.kogito.codegen.process.persistence.proto.AbstractProtoGenerator) Test(org.junit.jupiter.api.Test)

Example 2 with Proto

use of org.kie.kogito.codegen.process.persistence.proto.Proto in project kogito-runtimes by kiegroup.

the class AbstractMarshallerGeneratorTest method testEnumInPojosMarshallers.

@Test
void testEnumInPojosMarshallers() {
    Stream.of(Question.class, QuestionWithAnnotatedEnum.class).forEach(c -> {
        ProtoGenerator generator = protoGeneratorBuilder().withDataClasses(convertTypes(c)).build(null);
        Proto proto = generator.protoOfDataClasses("org.kie.kogito.test");
        assertThat(proto).isNotNull();
        assertThat(proto.getMessages()).hasSize(1);
        MarshallerGenerator marshallerGenerator = withGenerator(c);
        List<CompilationUnit> classes = null;
        try {
            classes = marshallerGenerator.generate(proto.serialize());
        } catch (IOException e) {
            fail("Error generating marshaller for " + c.getName(), e);
        }
        assertThat(classes).isNotNull();
        assertThat(classes).hasSize(2);
        Optional<ClassOrInterfaceDeclaration> marshallerClass = classes.get(0).getClassByName(c.getSimpleName() + "MessageMarshaller");
        assertThat(marshallerClass).isPresent();
        String answerType = null;
        try {
            answerType = c.getDeclaredField("answer").getType().getSimpleName();
        } catch (NoSuchFieldException e) {
            fail("Unable to get answer field type for " + c.getName(), e);
        }
        marshallerClass = classes.get(1).getClassByName(answerType + "EnumMarshaller");
        assertThat(marshallerClass).isPresent();
    });
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) Proto(org.kie.kogito.codegen.process.persistence.proto.Proto) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) Question(org.kie.kogito.codegen.data.Question) IOException(java.io.IOException) QuestionWithAnnotatedEnum(org.kie.kogito.codegen.data.QuestionWithAnnotatedEnum) ProtoGenerator(org.kie.kogito.codegen.process.persistence.proto.ProtoGenerator) AbstractProtoGenerator(org.kie.kogito.codegen.process.persistence.proto.AbstractProtoGenerator) Test(org.junit.jupiter.api.Test)

Example 3 with Proto

use of org.kie.kogito.codegen.process.persistence.proto.Proto 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 4 with Proto

use of org.kie.kogito.codegen.process.persistence.proto.Proto in project kogito-runtimes by kiegroup.

the class JandexProtoGenerator method generateModelClassProto.

@Override
protected Optional<GeneratedFile> generateModelClassProto(ClassInfo modelClazz) {
    String processId = getReferenceOfModel(modelClazz, "reference");
    String name = getReferenceOfModel(modelClazz, "name");
    if (processId != null) {
        Proto modelProto = generate("@Indexed", INDEX_COMMENT, modelClazz.name().prefix().toString() + "." + processId, modelClazz, "import \"kogito-index.proto\";", "import \"kogito-types.proto\";", "option kogito_model = \"" + name + "\";", "option kogito_id = \"" + processId + "\";");
        if (modelProto.getMessages().isEmpty()) {
            // no messages, nothing to do
            return Optional.empty();
        }
        ProtoMessage modelMessage = modelProto.getMessages().stream().filter(msg -> msg.getName().equals(name)).findFirst().orElseThrow(() -> new IllegalStateException("Unable to find model message"));
        modelMessage.addField("optional", "org.kie.kogito.index.model.KogitoMetadata", "metadata").setComment(INDEX_COMMENT);
        return Optional.of(generateProtoFiles(processId, modelProto));
    }
    return Optional.empty();
}
Also used : Proto(org.kie.kogito.codegen.process.persistence.proto.Proto) ProtoMessage(org.kie.kogito.codegen.process.persistence.proto.ProtoMessage)

Example 5 with Proto

use of org.kie.kogito.codegen.process.persistence.proto.Proto in project kogito-runtimes by kiegroup.

the class AbstractMarshallerGeneratorTest method testPersonWithAddressMarshallers.

@Test
void testPersonWithAddressMarshallers() throws Exception {
    ProtoGenerator generator = protoGeneratorBuilder().withDataClasses(convertTypes(PersonWithAddress.class)).build(null);
    Proto proto = generator.protoOfDataClasses("org.kie.kogito.test");
    assertThat(proto).isNotNull();
    assertThat(proto.getMessages()).hasSize(2);
    MarshallerGenerator marshallerGenerator = withGenerator(PersonWithAddresses.class);
    List<CompilationUnit> classes = marshallerGenerator.generate(proto.serialize());
    assertThat(classes).isNotNull();
    assertThat(classes).hasSize(2);
    Optional<ClassOrInterfaceDeclaration> marshallerClass = classes.get(0).getClassByName("AddressMessageMarshaller");
    assertThat(marshallerClass).isPresent();
    marshallerClass = classes.get(1).getClassByName("PersonWithAddressMessageMarshaller");
    assertThat(marshallerClass).isPresent();
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) Proto(org.kie.kogito.codegen.process.persistence.proto.Proto) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) ProtoGenerator(org.kie.kogito.codegen.process.persistence.proto.ProtoGenerator) AbstractProtoGenerator(org.kie.kogito.codegen.process.persistence.proto.AbstractProtoGenerator) Test(org.junit.jupiter.api.Test)

Aggregations

Proto (org.kie.kogito.codegen.process.persistence.proto.Proto)8 CompilationUnit (com.github.javaparser.ast.CompilationUnit)7 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)7 ProtoGenerator (org.kie.kogito.codegen.process.persistence.proto.ProtoGenerator)7 Test (org.junit.jupiter.api.Test)6 AbstractProtoGenerator (org.kie.kogito.codegen.process.persistence.proto.AbstractProtoGenerator)6 IOException (java.io.IOException)3 NodeList (com.github.javaparser.ast.NodeList)1 ConstructorDeclaration (com.github.javaparser.ast.body.ConstructorDeclaration)1 Parameter (com.github.javaparser.ast.body.Parameter)1 EnclosedExpr (com.github.javaparser.ast.expr.EnclosedExpr)1 Expression (com.github.javaparser.ast.expr.Expression)1 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)1 NameExpr (com.github.javaparser.ast.expr.NameExpr)1 ObjectCreationExpr (com.github.javaparser.ast.expr.ObjectCreationExpr)1 StringLiteralExpr (com.github.javaparser.ast.expr.StringLiteralExpr)1 BlockStmt (com.github.javaparser.ast.stmt.BlockStmt)1 CatchClause (com.github.javaparser.ast.stmt.CatchClause)1 TryStmt (com.github.javaparser.ast.stmt.TryStmt)1 ClassOrInterfaceType (com.github.javaparser.ast.type.ClassOrInterfaceType)1