Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ public class ProcessGenerator {
private static final String WPI = "wpi";
private static final String FACTORY = "factory";
private static final String CORRELATIONS = "correlations";
private static final String PROCESS_METHOD_NAME = "process";

private final String packageName;
private final KogitoWorkflowProcess process;
Expand Down Expand Up @@ -289,13 +290,20 @@ private MethodDeclaration createReadOnlyInstanceGenericWithWorkflowInstanceMetho
return methodDeclaration;
}

private MethodDeclaration process(ProcessMetaData processMetaData) {
return processMetaData.getGeneratedClassModel()
.findFirst(MethodDeclaration.class)
.orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a method declaration!"))
.setModifiers(Modifier.Keyword.PROTECTED)
private void addProcessMethods(ClassOrInterfaceDeclaration cls, ProcessMetaData processMetaData) {
ClassOrInterfaceDeclaration generatedClazz = processMetaData.getGeneratedClassModel()
.findFirst(ClassOrInterfaceDeclaration.class)
.orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class declaration!"));

MethodDeclaration processMethod = generatedClazz.getMethods().stream()
.filter(m -> m.getNameAsString().equals(PROCESS_METHOD_NAME))
.findFirst()
.orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a method declaration!"));
processMethod.setModifiers(Modifier.Keyword.PROTECTED)
.setType(Process.class.getCanonicalName())
.setName("process");
.setName(PROCESS_METHOD_NAME);

generatedClazz.getMethods().forEach(cls::addMember);
}

private MethodCallExpr createProcessRuntime() {
Expand Down Expand Up @@ -480,8 +488,8 @@ public ClassOrInterfaceDeclaration classDeclaration() {
.addMember(createInstanceGenericMethod(processInstanceFQCN))
.addMember(createInstanceGenericWithBusinessKeyMethod(processInstanceFQCN))
.addMember(createInstanceGenericWithWorkflowInstanceMethod(processInstanceFQCN))
.addMember(createReadOnlyInstanceGenericWithWorkflowInstanceMethod(processInstanceFQCN))
.addMember(process(processMetaData));
.addMember(createReadOnlyInstanceGenericWithWorkflowInstanceMethod(processInstanceFQCN));
addProcessMethods(cls, processMetaData);

internalConfigure(processMetaData).ifPresent(cls::addMember);
internalRegisterListeners(processMetaData).ifPresent(cls::addMember);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.kie.kogito.codegen.process;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;

import org.drools.io.FileSystemResource;
import org.jbpm.compiler.canonical.ProcessMetaData;
import org.jbpm.compiler.canonical.ProcessToExecModelGenerator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.kie.api.definition.process.Process;
import org.kie.api.definition.process.WorkflowProcess;

import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;

import static org.assertj.core.api.Assertions.assertThat;

/**
* Regression test for apache/incubator-kie-issues#2229, driving the two BPMN files from the minimal
* reproducer through the real {@link ProcessCodegen#parseProcessFile(org.drools.io.Resource)} entry point.
*/
public class ProcessCodeTooLargeReproducerTest {

private static final String REPRO_FAILS_BPMN = "/codetoolarge/repro-fails.bpmn";
private static final String REPRO_CONTROL_PASSES_BPMN = "/codetoolarge/repro-control-passes.bpmn";

@Test
void reproducerAt754TasksCompilesWithoutCodeTooLarge(@TempDir Path tempDir) throws IOException, InterruptedException {
assertCompilesWithoutCodeTooLarge(REPRO_FAILS_BPMN, tempDir);
}

@Test
void negativeControlAt753TasksStillCompiles(@TempDir Path tempDir) throws IOException, InterruptedException {
assertCompilesWithoutCodeTooLarge(REPRO_CONTROL_PASSES_BPMN, tempDir);
}

private void assertCompilesWithoutCodeTooLarge(String resourcePath, Path tempDir) throws IOException, InterruptedException {
WorkflowProcess process = parseProcess(resourcePath);

ProcessMetaData metadata = ProcessToExecModelGenerator.INSTANCE.generate(process);
CompilationUnit generatedClassModel = metadata.getGeneratedClassModel();
ClassOrInterfaceDeclaration clazz = generatedClassModel.findFirst(ClassOrInterfaceDeclaration.class).orElseThrow();
String className = clazz.getNameAsString();

assertThat(clazz.getMethodsByName("initNodes_0"))
.as("both reproducer files are large enough that initNodes() chunking must have fired")
.isNotEmpty();

File sourceFile = writeToDefaultPackageSourceFile(tempDir, className, generatedClassModel.toString());
String javacOutput = compileWithJavac(sourceFile, tempDir);

assertThat(javacOutput).doesNotContain("code too large");
}

private WorkflowProcess parseProcess(String resourcePath) throws IOException {
File file = new File(getClass().getResource(resourcePath).getFile());
Collection<Process> processes = ProcessCodegen.parseProcessFile(new FileSystemResource(file));
assertThat(processes).hasSize(1);
return (WorkflowProcess) processes.iterator().next();
}

private File writeToDefaultPackageSourceFile(Path tempDir, String className, String source) throws IOException {
String withoutPackageDeclaration = source.replaceFirst("(?m)^package .*;\\n", "");
File sourceFile = tempDir.resolve(className + ".java").toFile();
try (FileWriter writer = new FileWriter(sourceFile)) {
writer.write(withoutPackageDeclaration);
}
return sourceFile;
}

private String compileWithJavac(File sourceFile, Path tempDir) throws IOException, InterruptedException {
String classpath = System.getProperty("java.class.path");
ProcessBuilder processBuilder = new ProcessBuilder(
"javac", "-d", tempDir.toString(), "-cp", classpath, sourceFile.getAbsolutePath());
processBuilder.redirectErrorStream(true);
java.lang.Process javac = processBuilder.start();
String output = new String(javac.getInputStream().readAllBytes());
javac.waitFor();
return output;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.kie.kogito.codegen.process;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;

import org.jbpm.compiler.canonical.ProcessMetaData;
import org.jbpm.compiler.canonical.ProcessToExecModelGenerator;
import org.jbpm.ruleflow.core.RuleFlowProcessFactory;
import org.jbpm.ruleflow.core.WorkflowElementIdentifierFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.kie.api.definition.process.WorkflowElementIdentifier;
import org.kie.api.definition.process.WorkflowProcess;

import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;

import static org.assertj.core.api.Assertions.assertThat;

/**
* Regression test for apache/incubator-kie-issues#2229: a process with enough sequential nodes must not
* generate a {@code process()} method whose bytecode exceeds the JVM's 64KB per-method limit.
*/
public class ProcessGeneratorCodeSizeTest {

private static final int TASK_COUNT_KNOWN_TO_OVERFLOW_SINGLE_METHOD = 754;

@Test
void largeFlatProcessCompilesWithoutCodeTooLarge(@TempDir Path tempDir) throws IOException, InterruptedException {
WorkflowProcess process = buildSequentialScriptTaskProcess(TASK_COUNT_KNOWN_TO_OVERFLOW_SINGLE_METHOD);

ProcessMetaData metadata = ProcessToExecModelGenerator.INSTANCE.generate(process);
CompilationUnit generatedClassModel = metadata.getGeneratedClassModel();
String className = generatedClassModel.findFirst(ClassOrInterfaceDeclaration.class)
.orElseThrow()
.getNameAsString();

File sourceFile = writeToDefaultPackageSourceFile(tempDir, className, generatedClassModel.toString());
String javacOutput = compileWithJavac(sourceFile, tempDir);

assertThat(javacOutput).doesNotContain("code too large");
}

private WorkflowProcess buildSequentialScriptTaskProcess(int taskCount) {
RuleFlowProcessFactory factory = RuleFlowProcessFactory.createProcess("codesize.big");
factory.name("big").packageName("codesize").dynamic(false).version("1.0");

WorkflowElementIdentifier start = WorkflowElementIdentifierFactory.fromExternalFormat("start");
factory.startNode(start).name("start").done();

WorkflowElementIdentifier previous = start;
for (int i = 0; i < taskCount; i++) {
WorkflowElementIdentifier taskId = WorkflowElementIdentifierFactory.fromExternalFormat("task" + i);
factory.actionNode(taskId).name("task" + i).action("java", "System.out.println(\"step " + i + "\");").done();
factory.connection(previous, taskId);
previous = taskId;
}

WorkflowElementIdentifier end = WorkflowElementIdentifierFactory.fromExternalFormat("end");
factory.endNode(end).name("end").terminate(false).done();
factory.connection(previous, end);

return factory.validate().getProcess();
}

private File writeToDefaultPackageSourceFile(Path tempDir, String className, String source) throws IOException {
String withoutPackageDeclaration = source.replaceFirst("(?m)^package .*;\\n", "");
File sourceFile = tempDir.resolve(className + ".java").toFile();
try (FileWriter writer = new FileWriter(sourceFile)) {
writer.write(withoutPackageDeclaration);
}
return sourceFile;
}

private String compileWithJavac(File sourceFile, Path tempDir) throws IOException, InterruptedException {
String classpath = System.getProperty("java.class.path");
ProcessBuilder processBuilder = new ProcessBuilder(
"javac", "-d", tempDir.toString(), "-cp", classpath, sourceFile.getAbsolutePath());
processBuilder.redirectErrorStream(true);
java.lang.Process javac = processBuilder.start();
String output = new String(javac.getInputStream().readAllBytes());
javac.waitFor();
return output;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.kie.kogito.codegen.process;

import java.io.File;
import java.util.Collection;

import org.drools.io.FileSystemResource;
import org.jbpm.compiler.canonical.ProcessToExecModelGenerator;
import org.junit.jupiter.api.Test;
import org.kie.api.definition.process.Process;
import org.kie.kogito.codegen.api.AddonsConfig;
import org.kie.kogito.codegen.api.context.KogitoBuildContext;
import org.kie.kogito.codegen.api.context.impl.JavaKogitoBuildContext;
import org.kie.kogito.internal.process.runtime.KogitoWorkflowProcess;

import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;

import static org.assertj.core.api.Assertions.assertThat;

public class ProcessGeneratorTest {

private static final String TEST_PROCESS_FILE = "src/test/resources/startsignal/StartSignalEventNoPayload.bpmn2";

@Test
void classDeclarationExposesProcessEntryPoint() {
ClassOrInterfaceDeclaration cls = generateClassDeclaration(buildExecModelGenerator());

assertThat(cls.getMethodsByName("process")).hasSize(1);
MethodDeclaration processMethod = cls.getMethodsByName("process").get(0);
assertThat(processMethod.getModifiers()).containsExactly(Modifier.protectedModifier());
assertThat(processMethod.getType().asString()).isEqualTo(Process.class.getCanonicalName());
}

@Test
void classDeclarationTransplantsEveryGeneratedMethodNotJustTheFirst() {
ClassOrInterfaceDeclaration cls = generateClassDeclaration(buildExecModelGenerator());

assertThat(cls.getMethodsByName("process")).hasSize(1);
assertThat(cls.getMethodsByName("initVariables")).hasSize(1);
assertThat(cls.getMethodsByName("initMetadata")).hasSize(1);
assertThat(cls.getMethodsByName("initNodes")).hasSize(1);
assertThat(cls.getMethodsByName("initConnections")).hasSize(1);
}

@Test
void classDeclarationDoesNotChunkNodesForASmallProcess() {
ClassOrInterfaceDeclaration cls = generateClassDeclaration(buildExecModelGenerator());

assertThat(cls.getMethodsByName("initNodes")).hasSize(1);
assertThat(cls.getMethodsByName("initNodes_0")).isEmpty();
}

private ClassOrInterfaceDeclaration generateClassDeclaration(ProcessExecutableModelGenerator execModelGen) {
KogitoBuildContext context = buildContext();
KogitoWorkflowProcess process = execModelGen.process();
ProcessGenerator generator = new ProcessGenerator(
context,
process,
execModelGen,
execModelGen.className(),
new ModelClassGenerator(context, process).className(),
context.getPackageName() + ".Application");
return generator.classDeclaration();
}

private ProcessExecutableModelGenerator buildExecModelGenerator() {
KogitoBuildContext context = buildContext();
KogitoWorkflowProcess process = parseProcess(TEST_PROCESS_FILE);
return new ProcessExecutableModelGenerator(process, new ProcessToExecModelGenerator(context.getClassLoader()));
}

private KogitoWorkflowProcess parseProcess(String fileName) {
Collection<Process> processes = ProcessCodegen.parseProcessFile(new FileSystemResource(new File(fileName)));
assertThat(processes).hasSize(1);
Process process = processes.stream().findAny().orElseThrow();
assertThat(process).isInstanceOf(KogitoWorkflowProcess.class);
return (KogitoWorkflowProcess) process;
}

private KogitoBuildContext buildContext() {
AddonsConfig addonsConfig = AddonsConfig.builder()
.withMonitoring(false)
.withPrometheusMonitoring(false)
.build();
return JavaKogitoBuildContext.builder().withAddonsConfig(addonsConfig).build();
}
}
Loading
Loading