use of org.kie.kogito.Model in project kogito-runtimes by kiegroup.
the class ProcessGenerator method classDeclaration.
public ClassOrInterfaceDeclaration classDeclaration() {
ClassOrInterfaceDeclaration cls = new ClassOrInterfaceDeclaration().setName(targetTypeName).setModifiers(Modifier.Keyword.PUBLIC);
ProcessMetaData processMetaData = processExecutable.generate();
ConstructorDeclaration constructor = getConstructorDeclaration().addParameter(appCanonicalName, APPLICATION);
MethodCallExpr handlersCollection = new MethodCallExpr(new NameExpr("java.util.Arrays"), "asList");
MethodCallExpr superMethod = new MethodCallExpr(null, "super").addArgument(new NameExpr(APPLICATION)).addArgument(handlersCollection);
if (context.getAddonsConfig().usePersistence()) {
constructor.addParameter(ProcessInstancesFactory.class.getCanonicalName(), FACTORY);
superMethod.addArgument(new NameExpr(FACTORY));
}
constructor.setBody(new BlockStmt().addStatement(superMethod).addStatement(new MethodCallExpr("activate")));
if (context.hasDI()) {
context.getDependencyInjectionAnnotator().withNamedApplicationComponent(cls, process.getId());
context.getDependencyInjectionAnnotator().withEagerStartup(cls);
context.getDependencyInjectionAnnotator().withInjection(constructor);
}
Map<String, CompilationUnit> handlers = processMetaData.getGeneratedHandlers();
if (!handlers.isEmpty()) {
MethodCallExpr initMethodCall = new MethodCallExpr(null, "this").addArgument(new NameExpr(APPLICATION));
ConstructorDeclaration decl = getConstructorDeclaration().addParameter(appCanonicalName, APPLICATION).setBody(new BlockStmt().addStatement(initMethodCall));
if (context.getAddonsConfig().usePersistence()) {
initMethodCall.addArgument(new NameExpr(FACTORY));
decl.addParameter(ProcessInstancesFactory.class.getCanonicalName(), FACTORY);
}
cls.addMember(decl);
for (Entry<String, CompilationUnit> handler : handlers.entrySet()) {
String varName = handler.getKey().substring(handler.getKey().lastIndexOf('.') + 1);
varName = Character.toLowerCase(varName.charAt(0)) + varName.substring(1);
ClassOrInterfaceDeclaration handlerClazz = handler.getValue().findFirst(ClassOrInterfaceDeclaration.class).orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a method declaration!"));
String clazzName = handler.getValue().getPackageDeclaration().map(pd -> pd.getName().toString() + '.' + handlerClazz.getName()).orElse(handlerClazz.getName().asString());
ClassOrInterfaceType clazzNameType = parseClassOrInterfaceType(clazzName);
Parameter parameter = new Parameter(clazzNameType, varName);
if (context.hasDI()) {
context.getDependencyInjectionAnnotator().withApplicationComponent(handlerClazz);
context.getDependencyInjectionAnnotator().withOptionalInjection(handlerClazz.getConstructors().stream().filter(c -> !c.getParameters().isEmpty()).findFirst().orElseThrow(() -> new IllegalStateException("Cannot find a non empty constructor to annotate in handler class " + handlerClazz)));
}
initMethodCall.addArgument(new ObjectCreationExpr(null, clazzNameType, NodeList.nodeList()));
constructor.addParameter(parameter);
handlersCollection.addArgument(new NameExpr(varName));
additionalClasses.add(handler.getValue());
}
}
String processInstanceFQCN = ProcessInstanceGenerator.qualifiedName(packageName, typeName);
cls.addExtendedType(abstractProcessType(modelTypeName)).addMember(constructor).addMember(getConstructorDeclaration()).addMember(createInstanceMethod(processInstanceFQCN)).addMember(createInstanceWithBusinessKeyMethod(processInstanceFQCN)).addMember(new MethodDeclaration().addModifier(Keyword.PUBLIC).setName(CREATE_MODEL).setType(modelTypeName).addAnnotation(Override.class).setBody(new BlockStmt().addStatement(new ReturnStmt(new ObjectCreationExpr(null, new ClassOrInterfaceType(null, modelTypeName), NodeList.nodeList()))))).addMember(createInstanceGenericMethod(processInstanceFQCN)).addMember(createInstanceGenericWithBusinessKeyMethod(processInstanceFQCN)).addMember(createInstanceGenericWithWorkflowInstanceMethod(processInstanceFQCN)).addMember(createReadOnlyInstanceGenericWithWorkflowInstanceMethod(processInstanceFQCN)).addMember(process(processMetaData));
internalConfigure(processMetaData).ifPresent(cls::addMember);
internalRegisterListeners(processMetaData).ifPresent(cls::addMember);
if (!processMetaData.getSubProcesses().isEmpty()) {
for (Entry<String, String> subProcess : processMetaData.getSubProcesses().entrySet()) {
FieldDeclaration subprocessFieldDeclaration = new FieldDeclaration();
String fieldName = "process" + subProcess.getKey();
ClassOrInterfaceType modelType = new ClassOrInterfaceType(null, new SimpleName(org.kie.kogito.process.Process.class.getCanonicalName()), NodeList.nodeList(new ClassOrInterfaceType(null, StringUtils.ucFirst(subProcess.getKey() + "Model"))));
if (context.hasDI()) {
subprocessFieldDeclaration.addVariable(new VariableDeclarator(modelType, fieldName));
context.getDependencyInjectionAnnotator().withInjection(subprocessFieldDeclaration);
} else {
// app.get(org.kie.kogito.process.Processes.class).processById()
MethodCallExpr initSubProcessField = new MethodCallExpr(new MethodCallExpr(new NameExpr(APPLICATION), "get").addArgument(new ClassExpr().setType(Processes.class.getCanonicalName())), "processById").addArgument(new StringLiteralExpr(subProcess.getKey()));
subprocessFieldDeclaration.addVariable(new VariableDeclarator(modelType, fieldName));
constructor.getBody().addStatement(new AssignExpr(new FieldAccessExpr(new ThisExpr(), fieldName), new CastExpr(modelType, initSubProcessField), Operator.ASSIGN));
}
cls.addMember(subprocessFieldDeclaration);
}
}
if (!processMetaData.getTriggers().isEmpty()) {
for (TriggerMetaData trigger : processMetaData.getTriggers()) {
// add message produces as field
if (trigger.getType().equals(TriggerMetaData.TriggerType.ProduceMessage)) {
String producerFieldType = packageName + "." + typeName + "MessageProducer_" + trigger.getOwnerId();
String producerFieldName = "producer_" + trigger.getOwnerId();
FieldDeclaration producerFieldDeclaration = new FieldDeclaration().addVariable(new VariableDeclarator(new ClassOrInterfaceType(null, producerFieldType), producerFieldName));
cls.addMember(producerFieldDeclaration);
if (context.hasDI()) {
context.getDependencyInjectionAnnotator().withInjection(producerFieldDeclaration);
} else {
AssignExpr assignExpr = new AssignExpr(new FieldAccessExpr(new ThisExpr(), producerFieldName), new ObjectCreationExpr().setType(producerFieldType), AssignExpr.Operator.ASSIGN);
cls.getConstructors().forEach(c -> c.getBody().addStatement(assignExpr));
}
}
}
}
cls.getMembers().sort(new BodyDeclarationComparator());
return cls;
}
use of org.kie.kogito.Model in project kogito-runtimes by kiegroup.
the class ProcessGenerationIT method testProcessGeneration.
@ParameterizedTest
@MethodSource("processesProvider")
public void testProcessGeneration(String processFile) throws Exception {
// for some tests this needs to be set to true
System.setProperty("jbpm.enable.multi.con", "true");
ProcessCodegen processCodeGen = ProcessCodegen.ofCollectedResources(newContext(), Collections.singletonList(new CollectedResource(BASE_PATH, new FileSystemResource(new File(BASE_PATH.toString(), processFile)))));
RuleFlowProcess expected = (RuleFlowProcess) processCodeGen.processes().iterator().next();
Application app = generateCodeProcessesOnly(processFile);
AbstractProcess<? extends Model> process = (AbstractProcess<? extends Model>) app.get(Processes.class).processById(expected.getId());
assertThat(process).isNotNull().isSameAs(app.get(Processes.class).processById(expected.getId()));
RuleFlowProcess current = (RuleFlowProcess) process.get();
assertNotNull(current);
assertEquals(expected.getId(), current.getId(), "Id");
assertEquals(expected.getName(), current.getName(), "Name");
assertEquals(expected.getPackageName(), current.getPackageName(), "PackageName");
assertEquals(expected.getVisibility(), current.getVisibility(), "Visibility");
assertEquals(expected.getType(), current.getType(), "Type");
assertEquals(expected.isAutoComplete(), current.isAutoComplete(), "AutoComplete");
assertEquals(expected.isDynamic(), current.isDynamic(), "Dynamic");
if (expected.getVersion() != null) {
assertEquals(expected.getVersion(), current.getVersion());
} else {
assertEquals("1.0", current.getVersion());
}
assertEquals(expected.getImports(), current.getImports(), "Imports");
assertEquals(expected.getFunctionImports(), current.getFunctionImports(), "FunctionImports");
assertMetadata(expected.getMetaData(), current.getMetaData(), IGNORED_PROCESS_META);
assertNodes(expected.getNodes(), current.getNodes());
System.clearProperty("jbpm.enable.multi.con");
}
use of org.kie.kogito.Model in project kogito-runtimes by kiegroup.
the class BusinessRuleTaskIT method testBasicBusinessRuleTaskControlledByUnitOfWork.
@Test
public void testBasicBusinessRuleTaskControlledByUnitOfWork() throws Exception {
Map<AbstractCodegenIT.TYPE, List<String>> resourcesTypeMap = new HashMap<>();
resourcesTypeMap.put(TYPE.PROCESS, Collections.singletonList("ruletask/BusinessRuleTask.bpmn2"));
resourcesTypeMap.put(TYPE.RULES, Collections.singletonList("ruletask/BusinessRuleTask.drl"));
Application app = generateCode(resourcesTypeMap);
assertThat(app).isNotNull();
final List<String> startedProcesses = new ArrayList<>();
// add custom event listener that collects data
app.config().get(ProcessConfig.class).processEventListeners().listeners().add(new DefaultKogitoProcessEventListener() {
@Override
public void beforeProcessStarted(ProcessStartedEvent event) {
startedProcesses.add(((KogitoProcessInstance) event.getProcessInstance()).getStringId());
}
});
UnitOfWork uow = app.unitOfWorkManager().newUnitOfWork();
uow.start();
Process<? extends Model> p = app.get(Processes.class).processById("BusinessRuleTask");
Model m = p.createModel();
m.fromMap(Collections.singletonMap("person", new Person("john", 25)));
ProcessInstance<?> processInstance = p.createInstance(m);
processInstance.start();
assertThat(processInstance.status()).isEqualTo(ProcessInstance.STATE_COMPLETED);
Model result = (Model) processInstance.variables();
assertThat(result.toMap()).hasSize(1).containsKey("person");
assertThat(result.toMap().get("person")).isNotNull().hasFieldOrPropertyWithValue("adult", true);
// since the unit of work has not been finished yet not listeners where invoked
assertThat(startedProcesses).hasSize(0);
uow.end();
// after unit of work has been ended listeners are invoked
assertThat(startedProcesses).hasSize(1);
}
use of org.kie.kogito.Model in project kogito-runtimes by kiegroup.
the class BusinessRuleUnitIT method outputMappingNullCollection.
@Test
@DisplayName("Should throw an exception when a null collection variable is mapped as output of a datasource")
public void outputMappingNullCollection() throws Exception {
Map<AbstractCodegenIT.TYPE, List<String>> resourcesTypeMap = new HashMap<>();
resourcesTypeMap.put(TYPE.PROCESS, Collections.singletonList("ruletask/ExampleP.bpmn"));
resourcesTypeMap.put(TYPE.RULES, Collections.singletonList("ruletask/Example.drl"));
Application app = generateCode(resourcesTypeMap);
Process<? extends Model> process = app.get(Processes.class).processById("ruletask.ExampleP");
HashMap<String, Object> map = new HashMap<>();
map.put("singleString", "hello");
map.put("singlePerson", new Person("Yoko", 86));
map.put("manyPersons", asList(new Person("Paul", 77), new Person("Ringo", 79)));
Model model = process.createModel();
model.fromMap(map);
ProcessInstance<? extends Model> instance = process.createInstance(model);
Model variables = instance.variables();
Map<String, Object> result = variables.toMap();
assertNull(result.get("emptyString"));
assertNull(result.get("emptyPerson"));
assertNull(result.get("emptyList"));
instance.start();
assertThat(instance.status()).isEqualTo(ProcessInstance.STATE_ERROR);
assertThat(instance.error().get().errorMessage()).contains("Null collection variable used as an output variable");
}
use of org.kie.kogito.Model in project kogito-runtimes by kiegroup.
the class BusinessRuleUnitIT method ioMappingAutoGeneratedRuleUnit.
@Test
public void ioMappingAutoGeneratedRuleUnit() throws Exception {
Map<AbstractCodegenIT.TYPE, List<String>> resourcesTypeMap = new HashMap<>();
resourcesTypeMap.put(TYPE.PROCESS, Collections.singletonList("ruletask/ExampleGenerated.bpmn"));
resourcesTypeMap.put(TYPE.RULES, Collections.singletonList("ruletask/Generated.drl"));
Application app = generateCode(resourcesTypeMap);
Process<? extends Model> process = app.get(Processes.class).processById("ruletask.ExampleGenerated");
HashMap<String, Object> map = new HashMap<>();
map.put("singleString", "hello");
map.put("singlePerson", new Person("Yoko", 86));
map.put("manyPersons", asList(new Person("Paul", 77), new Person("Ringo", 79)));
map.put("emptyList", new ArrayList<>());
Model model = process.createModel();
model.fromMap(map);
ProcessInstance<? extends Model> instance = process.createInstance(model);
Model variables = instance.variables();
Map<String, Object> result = variables.toMap();
assertNull(result.get("emptyString"));
assertNull(result.get("emptyPerson"));
instance.start();
result = instance.variables().toMap();
Person yoko = new Person("Yoko", 86);
yoko.setAdult(true);
assertEquals(yoko, result.get("singlePerson"));
}
Aggregations