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();
});
}
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();
});
}
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;
}
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();
}
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();
}
Aggregations