Search in sources :

Example 1 with ProcessMetaData

use of org.jbpm.compiler.canonical.ProcessMetaData 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;
}
Also used : StaticJavaParser.parseClassOrInterfaceType(com.github.javaparser.StaticJavaParser.parseClassOrInterfaceType) ClassExpr(com.github.javaparser.ast.expr.ClassExpr) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) TriggerMetaData(org.jbpm.compiler.canonical.TriggerMetaData) AbstractProcess(org.kie.kogito.process.impl.AbstractProcess) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) MemoryFileSystem(org.drools.compiler.compiler.io.memory.MemoryFileSystem) Parameter(com.github.javaparser.ast.body.Parameter) BodyDeclarationComparator(org.kie.kogito.codegen.core.BodyDeclarationComparator) CastExpr(com.github.javaparser.ast.expr.CastExpr) ThisExpr(com.github.javaparser.ast.expr.ThisExpr) ArrayList(java.util.ArrayList) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) Map(java.util.Map) SuperExpr(com.github.javaparser.ast.expr.SuperExpr) CompilationUnit(com.github.javaparser.ast.CompilationUnit) NoSuchElementException(java.util.NoSuchElementException) WorkflowProcessInstance(org.kie.api.runtime.process.WorkflowProcessInstance) Keyword(com.github.javaparser.ast.Modifier.Keyword) NodeList(com.github.javaparser.ast.NodeList) SimpleName(com.github.javaparser.ast.expr.SimpleName) KogitoBuildContext(org.kie.kogito.codegen.api.context.KogitoBuildContext) Process(org.kie.api.definition.process.Process) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) AssignExpr(com.github.javaparser.ast.expr.AssignExpr) NameExpr(com.github.javaparser.ast.expr.NameExpr) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) StandardCharsets(java.nio.charset.StandardCharsets) ProcessMetaData(org.jbpm.compiler.canonical.ProcessMetaData) Modifier(com.github.javaparser.ast.Modifier) SourceVersion(javax.lang.model.SourceVersion) List(java.util.List) Model(org.kie.kogito.Model) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) Entry(java.util.Map.Entry) Operator(com.github.javaparser.ast.expr.AssignExpr.Operator) Optional(java.util.Optional) KogitoWorkflowProcess(org.kie.kogito.internal.process.runtime.KogitoWorkflowProcess) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) Processes(org.kie.kogito.process.Processes) FieldAccessExpr(com.github.javaparser.ast.expr.FieldAccessExpr) ProcessInstancesFactory(org.kie.kogito.process.ProcessInstancesFactory) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) StringUtils(org.drools.core.util.StringUtils) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) SimpleName(com.github.javaparser.ast.expr.SimpleName) NameExpr(com.github.javaparser.ast.expr.NameExpr) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) StaticJavaParser.parseClassOrInterfaceType(com.github.javaparser.StaticJavaParser.parseClassOrInterfaceType) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) AssignExpr(com.github.javaparser.ast.expr.AssignExpr) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) CastExpr(com.github.javaparser.ast.expr.CastExpr) BodyDeclarationComparator(org.kie.kogito.codegen.core.BodyDeclarationComparator) FieldAccessExpr(com.github.javaparser.ast.expr.FieldAccessExpr) ThisExpr(com.github.javaparser.ast.expr.ThisExpr) CompilationUnit(com.github.javaparser.ast.CompilationUnit) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) TriggerMetaData(org.jbpm.compiler.canonical.TriggerMetaData) ProcessInstancesFactory(org.kie.kogito.process.ProcessInstancesFactory) ProcessMetaData(org.jbpm.compiler.canonical.ProcessMetaData) Parameter(com.github.javaparser.ast.body.Parameter) ClassExpr(com.github.javaparser.ast.expr.ClassExpr) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) NoSuchElementException(java.util.NoSuchElementException) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 2 with ProcessMetaData

use of org.jbpm.compiler.canonical.ProcessMetaData in project kogito-runtimes by kiegroup.

the class ActivityGenerationModelTest method testWorkItemProcessWithVariableMapping.

@Test
public void testWorkItemProcessWithVariableMapping() throws Exception {
    BpmnProcess process = BpmnProcess.from(new ClassPathResource("BPMN2-ServiceProcess.bpmn2")).get(0);
    ProcessMetaData metaData = ProcessToExecModelGenerator.INSTANCE.generate((WorkflowProcess) process.get());
    String content = metaData.getGeneratedClassModel().toString();
    assertThat(content).isNotNull();
    log(content);
    Map<String, String> classData = new HashMap<>();
    classData.put("org.drools.bpmn2.ServiceProcessProcess", content);
    TestWorkItemHandler workItemHandler = new TestWorkItemHandler();
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("s", "john");
    Map<String, BpmnProcess> processes = createProcesses(classData, Collections.singletonMap("org.jbpm.bpmn2.objects.HelloService_hello_2_Handler", workItemHandler));
    ProcessInstance<BpmnVariables> processInstance = processes.get("ServiceProcess").createInstance(BpmnVariables.create(params));
    processInstance.start();
    assertEquals(STATE_ACTIVE, processInstance.status());
    KogitoWorkItem workItem = workItemHandler.getWorkItem();
    assertNotNull(workItem);
    assertEquals("john", workItem.getParameter("Parameter"));
    processInstance.completeWorkItem(workItem.getStringId(), Collections.singletonMap("Result", "john doe"));
    assertEquals(STATE_COMPLETED, processInstance.status());
}
Also used : TestWorkItemHandler(org.jbpm.bpmn2.objects.TestWorkItemHandler) BpmnProcess(org.kie.kogito.process.bpmn2.BpmnProcess) HashMap(java.util.HashMap) KogitoWorkItem(org.kie.kogito.internal.process.runtime.KogitoWorkItem) ClassPathResource(org.drools.core.io.impl.ClassPathResource) ProcessMetaData(org.jbpm.compiler.canonical.ProcessMetaData) BpmnVariables(org.kie.kogito.process.bpmn2.BpmnVariables) Test(org.junit.jupiter.api.Test)

Example 3 with ProcessMetaData

use of org.jbpm.compiler.canonical.ProcessMetaData in project kogito-runtimes by kiegroup.

the class ActivityGenerationModelTest method testParallelGateway.

@Test
public void testParallelGateway() throws Exception {
    BpmnProcess process = BpmnProcess.from(new ClassPathResource("BPMN2-ParallelSplit.bpmn2")).get(0);
    ProcessMetaData metaData = ProcessToExecModelGenerator.INSTANCE.generate((WorkflowProcess) process.get());
    String content = metaData.getGeneratedClassModel().toString();
    assertThat(content).isNotNull();
    log(content);
    Map<String, String> classData = new HashMap<>();
    classData.put("org.drools.bpmn2.TestProcess", content);
    Map<String, BpmnProcess> processes = createProcesses(classData, Collections.emptyMap());
    Map<String, Object> params = new HashMap<String, Object>();
    ProcessInstance<BpmnVariables> processInstance = processes.get("com.sample.test").createInstance(BpmnVariables.create(params));
    processInstance.start();
    assertEquals(STATE_COMPLETED, processInstance.status());
}
Also used : BpmnProcess(org.kie.kogito.process.bpmn2.BpmnProcess) HashMap(java.util.HashMap) ProcessMetaData(org.jbpm.compiler.canonical.ProcessMetaData) ClassPathResource(org.drools.core.io.impl.ClassPathResource) BpmnVariables(org.kie.kogito.process.bpmn2.BpmnVariables) Test(org.junit.jupiter.api.Test)

Example 4 with ProcessMetaData

use of org.jbpm.compiler.canonical.ProcessMetaData in project kogito-runtimes by kiegroup.

the class ActivityGenerationModelTest method testCallActivityProcess.

@Test
public void testCallActivityProcess() throws Exception {
    BpmnProcess process = BpmnProcess.from(new ClassPathResource("PrefixesProcessIdCallActivity.bpmn2")).get(0);
    ProcessMetaData metaData = ProcessToExecModelGenerator.INSTANCE.generate((WorkflowProcess) process.get());
    String content = metaData.getGeneratedClassModel().toString();
    assertThat(content).isNotNull();
    log(content);
    assertThat(metaData.getSubProcesses()).hasSize(1).containsKey("SubProcess").containsValue("test.SubProcess");
}
Also used : BpmnProcess(org.kie.kogito.process.bpmn2.BpmnProcess) ProcessMetaData(org.jbpm.compiler.canonical.ProcessMetaData) ClassPathResource(org.drools.core.io.impl.ClassPathResource) Test(org.junit.jupiter.api.Test)

Example 5 with ProcessMetaData

use of org.jbpm.compiler.canonical.ProcessMetaData in project kogito-runtimes by kiegroup.

the class ActivityGenerationModelTest method testScriptMultilineExprProcess.

@Test
public void testScriptMultilineExprProcess() throws Exception {
    BpmnProcess process = BpmnProcess.from(new ClassPathResource("BPMN2-CallActivitySubProcess.bpmn2")).get(0);
    ProcessMetaData metaData = ProcessToExecModelGenerator.INSTANCE.generate((WorkflowProcess) process.get());
    String content = metaData.getGeneratedClassModel().toString();
    assertThat(content).isNotNull();
    log(content);
    Map<String, String> classData = new HashMap<>();
    classData.put("org.drools.bpmn2.SubProcessProcess", content);
    Map<String, BpmnProcess> processes = createProcesses(classData, Collections.emptyMap());
    ProcessInstance<BpmnVariables> processInstance = processes.get("SubProcess").createInstance();
    processInstance.start();
    assertEquals(STATE_COMPLETED, processInstance.status());
}
Also used : BpmnProcess(org.kie.kogito.process.bpmn2.BpmnProcess) HashMap(java.util.HashMap) ProcessMetaData(org.jbpm.compiler.canonical.ProcessMetaData) ClassPathResource(org.drools.core.io.impl.ClassPathResource) BpmnVariables(org.kie.kogito.process.bpmn2.BpmnVariables) Test(org.junit.jupiter.api.Test)

Aggregations

ProcessMetaData (org.jbpm.compiler.canonical.ProcessMetaData)18 ClassPathResource (org.drools.core.io.impl.ClassPathResource)16 Test (org.junit.jupiter.api.Test)16 BpmnProcess (org.kie.kogito.process.bpmn2.BpmnProcess)16 HashMap (java.util.HashMap)13 BpmnVariables (org.kie.kogito.process.bpmn2.BpmnVariables)13 TestWorkItemHandler (org.jbpm.bpmn2.objects.TestWorkItemHandler)5 KogitoWorkItem (org.kie.kogito.internal.process.runtime.KogitoWorkItem)4 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Map (java.util.Map)2 ProcessToExecModelGenerator (org.jbpm.compiler.canonical.ProcessToExecModelGenerator)2 SystemOutWorkItemHandler (org.jbpm.process.instance.impl.demo.SystemOutWorkItemHandler)2 StaticIdentityProvider (org.kie.kogito.services.identity.StaticIdentityProvider)2 StaticJavaParser.parseClassOrInterfaceType (com.github.javaparser.StaticJavaParser.parseClassOrInterfaceType)1 CompilationUnit (com.github.javaparser.ast.CompilationUnit)1 Modifier (com.github.javaparser.ast.Modifier)1 Keyword (com.github.javaparser.ast.Modifier.Keyword)1 NodeList (com.github.javaparser.ast.NodeList)1