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