Search in sources :

Example 1 with Process

use of io.automatiko.engine.api.definition.process.Process in project automatiko-engine by automatiko-io.

the class MessageProducerGenerator method generate.

public String generate() {
    String sanitizedName = CodegenUtils.triggerSanitizedName(trigger, process.getVersion());
    String connector = CodegenUtils.getConnector(OUTGOING_PROP_PREFIX + sanitizedName + ".connector", context, (String) trigger.getContext("connector"));
    if (connector != null) {
        context.setApplicationProperty(OUTGOING_PROP_PREFIX + sanitizedName + ".connector", connector);
        appendConnectorSpecificProperties(connector);
    }
    CompilationUnit clazz = parse(this.getClass().getResourceAsStream(producerTemplate(connector)));
    clazz.setPackageDeclaration(process.getPackageName());
    // add functions so they can be easily accessed in message producer classes
    clazz.addImport(new ImportDeclaration(BaseFunctions.class.getCanonicalName(), true, true));
    context.getBuildContext().classThatImplement(Functions.class.getCanonicalName()).forEach(c -> clazz.addImport(new ImportDeclaration(c, true, true)));
    ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).get();
    template.setName(resourceClazzName);
    template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, trigger.getDataType()));
    template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateEventTypes(cls, messageDataEventClassName));
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("produce")).forEach(md -> {
        md.getParameters().stream().filter(p -> p.getNameAsString().equals(EVENT_DATA_VAR)).forEach(p -> p.setType(trigger.getDataType()));
        if (context.getBuildContext().hasClassAvailable("org.eclipse.microprofile.opentracing.Traced")) {
            md.addAnnotation("org.eclipse.microprofile.opentracing.Traced");
        }
    });
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("configure")).forEach(md -> md.addAnnotation("javax.annotation.PostConstruct"));
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("marshall")).forEach(md -> {
        md.getParameters().stream().filter(p -> p.getNameAsString().equals(EVENT_DATA_VAR)).forEach(p -> p.setType(trigger.getDataType()));
        md.findAll(ClassOrInterfaceType.class).forEach(t -> t.setName(t.getNameAsString().replace("$DataEventType$", messageDataEventClassName)));
    });
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("convert")).forEach(md -> {
        md.setType(md.getTypeAsString().replace("$DataType$", trigger.getDataType()));
        md.findAll(CastExpr.class).forEach(c -> c.setType(c.getTypeAsString().replace("$DataType$", trigger.getDataType())));
        md.findAll(ClassOrInterfaceType.class).forEach(t -> t.setName(t.getNameAsString().replace("$DataType$", trigger.getDataType())));
    });
    // used by MQTT to get topic name based on expression
    String topicExpression = (String) trigger.getContext("topicExpression");
    if (topicExpression != null) {
        template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("topic")).forEach(md -> {
            BlockStmt body = new BlockStmt();
            ClassOrInterfaceType stringType = new ClassOrInterfaceType(null, String.class.getCanonicalName());
            if (topicExpression.contains("id")) {
                VariableDeclarationExpr idField = new VariableDeclarationExpr(stringType, "id");
                body.addStatement(new AssignExpr(idField, new MethodCallExpr(new NameExpr("pi"), "getId"), AssignExpr.Operator.ASSIGN));
            }
            if (topicExpression.contains("businessKey")) {
                VariableDeclarationExpr businessKeyField = new VariableDeclarationExpr(stringType, "businessKey");
                body.addStatement(new AssignExpr(businessKeyField, new MethodCallExpr(new NameExpr("pi"), "getCorrelationKey"), AssignExpr.Operator.ASSIGN));
            }
            VariableScope variableScope = (VariableScope) ((io.automatiko.engine.workflow.process.core.WorkflowProcess) process).getDefaultContext(VariableScope.VARIABLE_SCOPE);
            for (Variable var : variableScope.getVariables()) {
                if (topicExpression.contains(var.getSanitizedName())) {
                    ClassOrInterfaceType varType = new ClassOrInterfaceType(null, var.getType().getStringType());
                    VariableDeclarationExpr v = new VariableDeclarationExpr(varType, var.getSanitizedName());
                    body.addStatement(new AssignExpr(v, new CastExpr(varType, new MethodCallExpr(new MethodCallExpr(new NameExpr("pi"), "getVariables"), "get").addArgument(new StringLiteralExpr(var.getName()))), AssignExpr.Operator.ASSIGN));
                }
            }
            body.addStatement(new ReturnStmt(new NameExpr(topicExpression)));
            md.setBody(body);
        });
    }
    // used by AMQP to get address name based on expression
    String addressExpression = (String) trigger.getContext("addressExpression");
    if (addressExpression != null) {
        template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("address")).forEach(md -> {
            BlockStmt body = new BlockStmt();
            ClassOrInterfaceType stringType = new ClassOrInterfaceType(null, String.class.getCanonicalName());
            if (addressExpression.contains("id")) {
                VariableDeclarationExpr idField = new VariableDeclarationExpr(stringType, "id");
                body.addStatement(new AssignExpr(idField, new MethodCallExpr(new NameExpr("pi"), "getId"), AssignExpr.Operator.ASSIGN));
            }
            if (addressExpression.contains("businessKey")) {
                VariableDeclarationExpr businessKeyField = new VariableDeclarationExpr(stringType, "businessKey");
                body.addStatement(new AssignExpr(businessKeyField, new MethodCallExpr(new NameExpr("pi"), "getCorrelationKey"), AssignExpr.Operator.ASSIGN));
            }
            VariableScope variableScope = (VariableScope) ((io.automatiko.engine.workflow.process.core.WorkflowProcess) process).getDefaultContext(VariableScope.VARIABLE_SCOPE);
            for (Variable var : variableScope.getVariables()) {
                if (addressExpression.contains(var.getSanitizedName())) {
                    ClassOrInterfaceType varType = new ClassOrInterfaceType(null, var.getType().getStringType());
                    VariableDeclarationExpr v = new VariableDeclarationExpr(varType, var.getSanitizedName());
                    body.addStatement(new AssignExpr(v, new CastExpr(varType, new MethodCallExpr(new MethodCallExpr(new NameExpr("pi"), "getVariables"), "get").addArgument(new StringLiteralExpr(var.getName()))), AssignExpr.Operator.ASSIGN));
                }
            }
            body.addStatement(new ReturnStmt(new NameExpr(addressExpression)));
            md.setBody(body);
        });
    }
    // used by FunctionFlow to set subject (used by reply to)
    String subjectExpression = (String) trigger.getContext("subjectExpression");
    if (subjectExpression != null) {
        template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("subject")).forEach(md -> {
            BlockStmt body = new BlockStmt();
            ClassOrInterfaceType stringType = new ClassOrInterfaceType(null, String.class.getCanonicalName());
            if (subjectExpression.contains("id")) {
                VariableDeclarationExpr idField = new VariableDeclarationExpr(stringType, "id");
                body.addStatement(new AssignExpr(idField, new MethodCallExpr(new NameExpr("pi"), "getId"), AssignExpr.Operator.ASSIGN));
            }
            if (subjectExpression.contains("businessKey")) {
                VariableDeclarationExpr businessKeyField = new VariableDeclarationExpr(stringType, "businessKey");
                body.addStatement(new AssignExpr(businessKeyField, new MethodCallExpr(new NameExpr("pi"), "getCorrelationKey"), AssignExpr.Operator.ASSIGN));
            }
            if (subjectExpression.contains("referenceId")) {
                VariableDeclarationExpr idField = new VariableDeclarationExpr(stringType, "referenceId");
                body.addStatement(new AssignExpr(idField, new MethodCallExpr(new NameExpr("pi"), "getReferenceId"), AssignExpr.Operator.ASSIGN));
            }
            VariableScope variableScope = (VariableScope) ((io.automatiko.engine.workflow.process.core.WorkflowProcess) process).getDefaultContext(VariableScope.VARIABLE_SCOPE);
            for (Variable var : variableScope.getVariables()) {
                if (subjectExpression.contains(var.getSanitizedName())) {
                    ClassOrInterfaceType varType = new ClassOrInterfaceType(null, var.getType().getStringType());
                    VariableDeclarationExpr v = new VariableDeclarationExpr(varType, var.getSanitizedName());
                    body.addStatement(new AssignExpr(v, new CastExpr(varType, new MethodCallExpr(new MethodCallExpr(new NameExpr("pi"), "getVariables"), "get").addArgument(new StringLiteralExpr(var.getName()))), AssignExpr.Operator.ASSIGN));
                }
            }
            body.addStatement(new ReturnStmt(new NameExpr(subjectExpression)));
            md.setBody(body);
        });
    }
    // Camal or HTTP headers
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("headers")).forEach(md -> {
        StringBuilder allHeaderValues = new StringBuilder();
        for (Entry<String, Object> entry : trigger.getContext().entrySet()) {
            if (entry.getKey().startsWith("Camel") || entry.getKey().startsWith("HTTP")) {
                allHeaderValues.append(entry.getValue().toString()).append(" ");
            }
        }
        String allHeaderValuesStr = allHeaderValues.toString();
        BlockStmt body = new BlockStmt();
        ClassOrInterfaceType stringType = new ClassOrInterfaceType(null, String.class.getCanonicalName());
        if (allHeaderValuesStr.contains("id")) {
            VariableDeclarationExpr idField = new VariableDeclarationExpr(stringType, "id");
            body.addStatement(new AssignExpr(idField, new MethodCallExpr(new NameExpr("pi"), "getId"), AssignExpr.Operator.ASSIGN));
        }
        if (allHeaderValuesStr.contains("businessKey")) {
            VariableDeclarationExpr businessKeyField = new VariableDeclarationExpr(stringType, "businessKey");
            body.addStatement(new AssignExpr(businessKeyField, new MethodCallExpr(new NameExpr("pi"), "getCorrelationKey"), AssignExpr.Operator.ASSIGN));
        }
        VariableScope variableScope = (VariableScope) ((io.automatiko.engine.workflow.process.core.WorkflowProcess) process).getDefaultContext(VariableScope.VARIABLE_SCOPE);
        for (Variable var : variableScope.getVariables()) {
            if (allHeaderValuesStr.contains(var.getSanitizedName())) {
                ClassOrInterfaceType varType = new ClassOrInterfaceType(null, var.getType().getStringType());
                VariableDeclarationExpr v = new VariableDeclarationExpr(varType, var.getSanitizedName());
                body.addStatement(new AssignExpr(v, new CastExpr(varType, new MethodCallExpr(new MethodCallExpr(new NameExpr("pi"), "getVariables"), "get").addArgument(new StringLiteralExpr(var.getName()))), AssignExpr.Operator.ASSIGN));
            }
        }
        for (Entry<String, Object> entry : trigger.getContext().entrySet()) {
            if (entry.getKey().startsWith("Camel")) {
                body.addStatement(new MethodCallExpr(new NameExpr("metadata"), "putHeader").addArgument(new StringLiteralExpr(entry.getKey())).addArgument(new NameExpr(entry.getValue().toString())));
            } else if (entry.getKey().startsWith("HTTP")) {
                body.addStatement(new MethodCallExpr(new NameExpr("builder"), "addHeader").addArgument(new StringLiteralExpr(entry.getKey().replaceFirst("HTTP", ""))).addArgument(new NameExpr(entry.getValue().toString())));
            }
        }
        if (!md.getTypeAsString().equalsIgnoreCase("void")) {
            body.addStatement(new ReturnStmt(new NameExpr("metadata")));
        }
        md.setBody(body);
    });
    // JMS properties
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("properties")).forEach(md -> {
        StringBuilder allHeaderValues = new StringBuilder();
        for (Entry<String, Object> entry : trigger.getContext().entrySet()) {
            if (entry.getKey().startsWith("JMS")) {
                allHeaderValues.append(entry.getValue().toString()).append(" ");
            }
        }
        String allHeaderValuesStr = allHeaderValues.toString();
        BlockStmt body = new BlockStmt();
        ClassOrInterfaceType stringType = new ClassOrInterfaceType(null, String.class.getCanonicalName());
        if (allHeaderValuesStr.contains("id")) {
            VariableDeclarationExpr idField = new VariableDeclarationExpr(stringType, "id");
            body.addStatement(new AssignExpr(idField, new MethodCallExpr(new NameExpr("pi"), "getId"), AssignExpr.Operator.ASSIGN));
        }
        if (allHeaderValuesStr.contains("businessKey")) {
            VariableDeclarationExpr businessKeyField = new VariableDeclarationExpr(stringType, "businessKey");
            body.addStatement(new AssignExpr(businessKeyField, new MethodCallExpr(new NameExpr("pi"), "getCorrelationKey"), AssignExpr.Operator.ASSIGN));
        }
        VariableScope variableScope = (VariableScope) ((io.automatiko.engine.workflow.process.core.WorkflowProcess) process).getDefaultContext(VariableScope.VARIABLE_SCOPE);
        for (Variable var : variableScope.getVariables()) {
            if (allHeaderValuesStr.contains(var.getSanitizedName())) {
                ClassOrInterfaceType varType = new ClassOrInterfaceType(null, var.getType().getStringType());
                VariableDeclarationExpr v = new VariableDeclarationExpr(varType, var.getSanitizedName());
                body.addStatement(new AssignExpr(v, new CastExpr(varType, new MethodCallExpr(new MethodCallExpr(new NameExpr("pi"), "getVariables"), "get").addArgument(new StringLiteralExpr(var.getName()))), AssignExpr.Operator.ASSIGN));
            }
        }
        for (Entry<String, Object> entry : trigger.getContext().entrySet()) {
            if (entry.getKey().startsWith("JMS")) {
                body.addStatement(new MethodCallExpr(new NameExpr("builder"), "with").addArgument(new StringLiteralExpr(entry.getKey().replaceFirst("JMS", ""))).addArgument(new NameExpr(entry.getValue().toString())));
            }
        }
        body.addStatement(new ReturnStmt(new NameExpr("builder")));
        md.setBody(body);
    });
    template.findAll(MethodDeclaration.class).forEach(md -> {
        md.findAll(StringLiteralExpr.class).forEach(str -> str.setString(str.asString().replace("$Trigger$", trigger.getName())));
    });
    template.findAll(MethodDeclaration.class).forEach(md -> {
        md.findAll(StringLiteralExpr.class).forEach(str -> str.setString(str.asString().replace("$TriggerType$", (String) trigger.getContext(Metadata.TRIGGER_TYPE_ATTR, trigger.getName()))));
    });
    if (useInjection()) {
        annotator.withApplicationComponent(template);
        template.findAll(FieldDeclaration.class, fd -> fd.getVariable(0).getNameAsString().equals("emitter")).forEach(emitterField -> {
            annotator.withInjection(emitterField);
            annotator.withOutgoingMessage(emitterField, sanitizedName);
        });
        template.findAll(FieldDeclaration.class, fd -> fd.getVariables().get(0).getNameAsString().equals("converter")).forEach(fd -> {
            annotator.withInjection(fd);
            fd.getVariable(0).setType(fd.getVariable(0).getTypeAsString().replace("$DataType$", trigger.getDataType()));
        });
        template.findAll(FieldDeclaration.class, fd -> fd.getVariable(0).getNameAsString().equals("useCloudEvents")).forEach(fd -> annotator.withConfigInjection(fd, "quarkus.automatiko.messaging.as-cloudevents"));
        template.findAll(FieldDeclaration.class, fd -> fd.getVariable(0).getNameAsString().equals("useCloudEventsBinary")).forEach(fd -> annotator.withConfigInjection(fd, "quarkus.automatiko.messaging.as-cloudevents-binary"));
    }
    // add connector and message name as static fields of the class
    FieldDeclaration connectorField = new FieldDeclaration().setStatic(true).setFinal(true).addVariable(new VariableDeclarator(new ClassOrInterfaceType(null, "String"), "CONNECTOR", new StringLiteralExpr(connector)));
    template.addMember(connectorField);
    FieldDeclaration messageNameField = new FieldDeclaration().setStatic(true).setFinal(true).addVariable(new VariableDeclarator(new ClassOrInterfaceType(null, "String"), "MESSAGE", new StringLiteralExpr(trigger.getName())));
    template.addMember(messageNameField);
    if (workflowType.equals(Process.FUNCTION_FLOW_TYPE)) {
        String destination = (String) trigger.getContext("functionType", sanitizedName);
        String sourcePrefix = process.getPackageName() + "." + processId + "." + sanitizedName;
        template.findAll(StringLiteralExpr.class).forEach(vv -> {
            String s = vv.getValue();
            String interpolated = s.replace("$destination$", destination);
            interpolated = interpolated.replace("$sourcePrefix$", sourcePrefix);
            vv.setString(interpolated);
        });
    }
    template.getMembers().sort(new BodyDeclarationComparator());
    ImportsOrganizer.organize(clazz);
    return clazz.toString();
}
Also used : ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) StaticJavaParser.parse(com.github.javaparser.StaticJavaParser.parse) Metadata(io.automatiko.engine.workflow.process.executable.core.Metadata) CAMEL_CONNECTOR(io.automatiko.engine.codegen.CodeGenConstants.CAMEL_CONNECTOR) GeneratorContext(io.automatiko.engine.codegen.GeneratorContext) CastExpr(com.github.javaparser.ast.expr.CastExpr) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration) AMQP_CONNECTOR(io.automatiko.engine.codegen.CodeGenConstants.AMQP_CONNECTOR) MQTT_CONNECTOR(io.automatiko.engine.codegen.CodeGenConstants.MQTT_CONNECTOR) CodegenUtils.interpolateTypes(io.automatiko.engine.codegen.CodegenUtils.interpolateTypes) StringUtils(io.automatiko.engine.services.utils.StringUtils) CompilationUnit(com.github.javaparser.ast.CompilationUnit) TriggerMetaData(io.automatiko.engine.workflow.compiler.canonical.TriggerMetaData) HTTP_CONNECTOR(io.automatiko.engine.codegen.CodeGenConstants.HTTP_CONNECTOR) KAFKA_CONNECTOR(io.automatiko.engine.codegen.CodeGenConstants.KAFKA_CONNECTOR) DependencyInjectionAnnotator(io.automatiko.engine.codegen.di.DependencyInjectionAnnotator) FUNCTION_FLOW_CONNECTOR(io.automatiko.engine.codegen.CodeGenConstants.FUNCTION_FLOW_CONNECTOR) Process(io.automatiko.engine.api.definition.process.Process) OUTGOING_PROP_PREFIX(io.automatiko.engine.codegen.CodeGenConstants.OUTGOING_PROP_PREFIX) CodegenUtils(io.automatiko.engine.codegen.CodegenUtils) BaseFunctions(io.automatiko.engine.services.execution.BaseFunctions) JMS_CONNECTOR(io.automatiko.engine.codegen.CodeGenConstants.JMS_CONNECTOR) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) WorkflowProcess(io.automatiko.engine.api.definition.process.WorkflowProcess) AssignExpr(com.github.javaparser.ast.expr.AssignExpr) BodyDeclarationComparator(io.automatiko.engine.codegen.BodyDeclarationComparator) CodegenUtils.interpolateEventTypes(io.automatiko.engine.codegen.CodegenUtils.interpolateEventTypes) NameExpr(com.github.javaparser.ast.expr.NameExpr) VariableScope(io.automatiko.engine.workflow.base.core.context.variable.VariableScope) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) VariableDeclarationExpr(com.github.javaparser.ast.expr.VariableDeclarationExpr) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) Entry(java.util.Map.Entry) Functions(io.automatiko.engine.api.Functions) Variable(io.automatiko.engine.workflow.base.core.context.variable.Variable) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) ImportsOrganizer(io.automatiko.engine.codegen.ImportsOrganizer) Variable(io.automatiko.engine.workflow.base.core.context.variable.Variable) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) NameExpr(com.github.javaparser.ast.expr.NameExpr) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) AssignExpr(com.github.javaparser.ast.expr.AssignExpr) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) CastExpr(com.github.javaparser.ast.expr.CastExpr) BodyDeclarationComparator(io.automatiko.engine.codegen.BodyDeclarationComparator) CompilationUnit(com.github.javaparser.ast.CompilationUnit) VariableDeclarationExpr(com.github.javaparser.ast.expr.VariableDeclarationExpr) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) VariableScope(io.automatiko.engine.workflow.base.core.context.variable.VariableScope) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 2 with Process

use of io.automatiko.engine.api.definition.process.Process in project automatiko-engine by automatiko-io.

the class AbstractProtobufProcessInstanceMarshaller method readProcessInstance.

// Input methods
public ProcessInstance readProcessInstance(MarshallerReaderContext context) throws IOException {
    AutomatikoMessages.ProcessInstance _instance = (io.automatiko.engine.workflow.marshalling.impl.AutomatikoMessages.ProcessInstance) context.parameterObject;
    if (_instance == null) {
        // try to parse from the stream
        ExtensionRegistry registry = PersisterHelper.buildRegistry(context, null);
        Header _header;
        try {
            _header = PersisterHelper.readFromStreamWithHeaderPreloaded(context, registry);
        } catch (ClassNotFoundException e) {
            // Java 5 does not accept [new IOException(String, Throwable)]
            IOException ioe = new IOException("Error deserializing process instance.");
            ioe.initCause(e);
            throw ioe;
        }
        _instance = AutomatikoMessages.ProcessInstance.parseFrom(_header.getPayload(), registry);
    }
    WorkflowProcessInstanceImpl processInstance = createProcessInstance();
    processInstance.setId(_instance.getId());
    String processId = _instance.getProcessId();
    processInstance.setProcessId(processId);
    String processXml = _instance.getProcessXml();
    Process process = null;
    if (processXml != null && processXml.trim().length() > 0) {
        processInstance.setProcessXml(processXml);
        process = processInstance.getProcess();
    } else {
        process = context.processes.get(processId);
        if (process == null) {
            throw new RuntimeException("Could not find process " + processId + " when restoring process instance " + processInstance.getId());
        }
        processInstance.setProcess(process);
    }
    processInstance.setDescription(_instance.getDescription());
    processInstance.internalSetState(_instance.getState());
    processInstance.setParentProcessInstanceId(_instance.getParentProcessInstanceId());
    processInstance.setRootProcessInstanceId(_instance.getRootProcessInstanceId());
    processInstance.setRootProcessId(_instance.getRootProcessId());
    processInstance.setSignalCompletion(_instance.getSignalCompletion());
    processInstance.setInitiator(_instance.getInitiator());
    processInstance.setCorrelationKey(_instance.getCorrelationKey());
    processInstance.setStartDate(new Date(_instance.getStartDate()));
    processInstance.internalSetSlaCompliance(_instance.getSlaCompliance());
    if (_instance.getSlaDueDate() > 0) {
        processInstance.internalSetSlaDueDate(new Date(_instance.getSlaDueDate()));
    }
    processInstance.internalSetSlaTimerId(_instance.getSlaTimerId());
    processInstance.setProcessRuntime(context.getProcessRuntime());
    List<ExecutionsErrorInfo> errors = new ArrayList<>();
    for (io.automatiko.engine.workflow.marshalling.impl.AutomatikoMessages.ProcessInstance.Error error : _instance.getErrorsList()) {
        errors.add(new ExecutionsErrorInfo(error.getErrorNodeId(), error.getErrorId(), error.getErrorMessage(), error.getErrorDetails()));
    }
    processInstance.internalSetExecutionErrors(errors);
    processInstance.setReferenceId(_instance.getReferenceId());
    processInstance.internalSetReferenceFromRoot(_instance.getReferenceFromRoot());
    for (String completedNodeId : _instance.getCompletedNodeIdsList()) {
        processInstance.addCompletedNodeId(completedNodeId);
    }
    if (_instance.getChildrenCount() > 0) {
        _instance.getChildrenList().forEach(child -> processInstance.addChildren(child.getProcessId(), child.getIdsList()));
    }
    if (_instance.getTagsCount() > 0) {
        _instance.getTagsList().forEach(tag -> processInstance.internalAddTag(tag.getId(), tag.getValue()));
    }
    if (_instance.getSwimlaneContextCount() > 0) {
        Context swimlaneContext = ((io.automatiko.engine.workflow.base.core.Process) process).getDefaultContext(SwimlaneContext.SWIMLANE_SCOPE);
        SwimlaneContextInstance swimlaneContextInstance = (SwimlaneContextInstance) processInstance.getContextInstance(swimlaneContext);
        for (AutomatikoMessages.ProcessInstance.SwimlaneContextInstance _swimlane : _instance.getSwimlaneContextList()) {
            swimlaneContextInstance.setActorId(_swimlane.getSwimlane(), _swimlane.getActorId());
        }
    }
    for (AutomatikoMessages.ProcessInstance.NodeInstance _node : _instance.getNodeInstanceList()) {
        context.parameterObject = _node;
        readNodeInstance(context, processInstance, processInstance);
    }
    if (processInstance.getState() == ProcessInstance.STATE_ACTIVE || processInstance.getState() == ProcessInstance.STATE_ERROR) {
        for (AutomatikoMessages.ProcessInstance.ExclusiveGroupInstance _excl : _instance.getExclusiveGroupList()) {
            ExclusiveGroupInstance exclusiveGroupInstance = new ExclusiveGroupInstance();
            processInstance.addContextInstance(ExclusiveGroup.EXCLUSIVE_GROUP, exclusiveGroupInstance);
            for (String nodeInstanceId : _excl.getGroupNodeInstanceIdList()) {
                NodeInstance nodeInstance = ((io.automatiko.engine.workflow.process.instance.NodeInstanceContainer) processInstance).getNodeInstance(nodeInstanceId, true);
                if (nodeInstance == null) {
                    throw new IllegalArgumentException("Could not find node instance when deserializing exclusive group instance: " + nodeInstanceId);
                }
                exclusiveGroupInstance.addNodeInstance(nodeInstance);
            }
        }
    }
    readVariableScope(context, process, processInstance, _instance);
    if (_instance.getIterationLevelsCount() > 0) {
        for (AutomatikoMessages.IterationLevel _level : _instance.getIterationLevelsList()) {
            processInstance.getIterationLevels().put(_level.getId(), _level.getLevel());
        }
    }
    return processInstance;
}
Also used : ExecutionsErrorInfo(io.automatiko.engine.api.workflow.ExecutionsErrorInfo) NodeInstanceContainer(io.automatiko.engine.api.runtime.process.NodeInstanceContainer) WorkflowProcessInstanceImpl(io.automatiko.engine.workflow.process.instance.impl.WorkflowProcessInstanceImpl) ArrayList(java.util.ArrayList) Process(io.automatiko.engine.api.definition.process.Process) ExtensionRegistry(com.google.protobuf.ExtensionRegistry) Context(io.automatiko.engine.workflow.base.core.Context) SwimlaneContext(io.automatiko.engine.workflow.base.core.context.swimlane.SwimlaneContext) ExclusiveGroupInstance(io.automatiko.engine.workflow.base.instance.context.exclusive.ExclusiveGroupInstance) SwimlaneContextInstance(io.automatiko.engine.workflow.base.instance.context.swimlane.SwimlaneContextInstance) IOException(java.io.IOException) Date(java.util.Date) Header(io.automatiko.engine.workflow.marshalling.impl.AutomatikoMessages.Header) ProcessInstance(io.automatiko.engine.api.runtime.process.ProcessInstance) WorkflowProcessInstance(io.automatiko.engine.api.runtime.process.WorkflowProcessInstance) CompositeContextNodeInstance(io.automatiko.engine.workflow.process.instance.node.CompositeContextNodeInstance) StateNodeInstance(io.automatiko.engine.workflow.process.instance.node.StateNodeInstance) ForEachNodeInstance(io.automatiko.engine.workflow.process.instance.node.ForEachNodeInstance) EventSubProcessNodeInstance(io.automatiko.engine.workflow.process.instance.node.EventSubProcessNodeInstance) TimerNodeInstance(io.automatiko.engine.workflow.process.instance.node.TimerNodeInstance) MilestoneNodeInstance(io.automatiko.engine.workflow.process.instance.node.MilestoneNodeInstance) HumanTaskNodeInstance(io.automatiko.engine.workflow.process.instance.node.HumanTaskNodeInstance) SubProcessNodeInstance(io.automatiko.engine.workflow.process.instance.node.SubProcessNodeInstance) WorkItemNodeInstance(io.automatiko.engine.workflow.process.instance.node.WorkItemNodeInstance) DynamicNodeInstance(io.automatiko.engine.workflow.process.instance.node.DynamicNodeInstance) LambdaSubProcessNodeInstance(io.automatiko.engine.workflow.process.instance.node.LambdaSubProcessNodeInstance) NodeInstance(io.automatiko.engine.api.runtime.process.NodeInstance) RuleSetNodeInstance(io.automatiko.engine.workflow.process.instance.node.RuleSetNodeInstance) EventNodeInstance(io.automatiko.engine.workflow.process.instance.node.EventNodeInstance)

Example 3 with Process

use of io.automatiko.engine.api.definition.process.Process in project automatiko-engine by automatiko-io.

the class LightProcessRuntime method initStartTimers.

public void initStartTimers() {
    Collection<Process> processes = runtimeContext.getProcesses();
    for (Process process : processes) {
        ExecutableProcess p = (ExecutableProcess) process;
        List<StartNode> startNodes = p.getTimerStart();
        if (startNodes != null && !startNodes.isEmpty()) {
            for (StartNode startNode : startNodes) {
                if (startNode != null && startNode.getTimer() != null) {
                    jobService.scheduleProcessJob(ProcessJobDescription.of(createTimerInstance(startNode.getTimer()), p.getId(), p.getVersion()));
                }
            }
        }
    }
}
Also used : StartNode(io.automatiko.engine.workflow.process.core.node.StartNode) Process(io.automatiko.engine.api.definition.process.Process) ExecutableProcess(io.automatiko.engine.workflow.process.executable.core.ExecutableProcess) ExecutableProcess(io.automatiko.engine.workflow.process.executable.core.ExecutableProcess)

Example 4 with Process

use of io.automatiko.engine.api.definition.process.Process in project automatiko-engine by automatiko-io.

the class LightProcessRuntimeContext method setupParameters.

@Override
public void setupParameters(ProcessInstance processInstance, Map<String, Object> parameters, VariableInitializer variableInitializer) {
    Map<String, Object> variables = new HashMap<>();
    Process process = processInstance.getProcess();
    VariableScope variableScope = (VariableScope) ((ContextContainer) process).getDefaultContext(VariableScope.VARIABLE_SCOPE);
    VariableScopeInstance variableScopeInstance = (VariableScopeInstance) processInstance.getContextInstance(VariableScope.VARIABLE_SCOPE);
    // set input parameters
    if (parameters != null) {
        if (variableScope != null) {
            for (Map.Entry<String, Object> entry : parameters.entrySet()) {
                variableScope.validateVariable(process.getName(), entry.getKey(), entry.getValue());
                variables.put(entry.getKey(), entry.getValue());
            }
        } else {
            throw new IllegalArgumentException("This process does not support parameters!");
        }
    }
    for (Variable var : variableScope.getVariables()) {
        if ((var.hasTag(Variable.AUTO_INITIALIZED_TAG) || var.getMetaData(Variable.DEFAULT_VALUE) != null) && variables.get(var.getName()) == null) {
            Object value = variableInitializer.initialize(process, var, variables);
            variableScope.validateVariable(process.getName(), var.getName(), value);
            variableScopeInstance.setVariable(var.getName(), value);
        }
        if (var.hasTag(Variable.INITIATOR_TAG) && variables.get(var.getName()) != null) {
            processInstance.setInitiator(variables.get(var.getName()).toString());
        }
    }
}
Also used : Variable(io.automatiko.engine.workflow.base.core.context.variable.Variable) VariableScopeInstance(io.automatiko.engine.workflow.base.instance.context.variable.VariableScopeInstance) HashMap(java.util.HashMap) Process(io.automatiko.engine.api.definition.process.Process) HashMap(java.util.HashMap) Map(java.util.Map) VariableScope(io.automatiko.engine.workflow.base.core.context.variable.VariableScope)

Example 5 with Process

use of io.automatiko.engine.api.definition.process.Process in project automatiko-engine by automatiko-io.

the class ServerlessWorkflowParser method addErrorHandlingToState.

protected void addErrorHandlingToState(Workflow workflow, State state, ServerlessWorkflowFactory factory, AtomicLong ids, WorkflowProcess process, CompositeContextNode subprocess) {
    if (state.getOnErrors() != null) {
        for (io.serverlessworkflow.api.error.Error error : state.getOnErrors()) {
            List<ErrorDefinition> defs = new ArrayList<>();
            if (error.getErrorRef() != null) {
                workflow.getErrors().getErrorDefs().stream().filter(err -> err.getName().equals(error.getErrorRef())).forEach(err -> defs.add(err));
            } else {
                workflow.getErrors().getErrorDefs().stream().filter(err -> error.getErrorRefs().contains(err.getName())).forEach(err -> defs.add(err));
            }
            BoundaryEventNode errorNode = factory.errorBoundaryEventNode(ids.getAndIncrement(), defs, null, process, subprocess, workflow);
            if (error.getEnd() != null) {
                EndNode onErrorEnd = factory.endNode(ids.getAndIncrement(), state.getName() + "onErrorEnd", error.getEnd().isTerminate(), process);
                if (error.getEnd().getProduceEvents() != null && !error.getEnd().getProduceEvents().isEmpty()) {
                    produceEvents(error.getEnd().getProduceEvents(), factory, workflow, ids, process, errorNode.getId(), onErrorEnd.getId());
                } else {
                    factory.connect(errorNode.getId(), onErrorEnd.getId(), "connect_" + errorNode.getId() + "_" + onErrorEnd.getId(), process, false);
                }
            } else {
                if (error.getTransition().getNextState() != null) {
                    for (io.automatiko.engine.api.definition.process.Node node : process.getNodes()) {
                        if (node.getName().equals(error.getTransition().getNextState())) {
                            if (error.getTransition().getProduceEvents() != null && !error.getTransition().getProduceEvents().isEmpty()) {
                                produceEvents(error.getTransition().getProduceEvents(), factory, workflow, ids, process, errorNode.getId(), node.getId());
                            } else {
                                factory.connect(errorNode.getId(), node.getId(), "connect_" + errorNode.getId() + "_" + node.getId(), process, false);
                            }
                            break;
                        }
                    }
                }
            }
        }
    }
}
Also used : Arrays(java.util.Arrays) TimerNode(io.automatiko.engine.workflow.process.core.node.TimerNode) Workflow(io.serverlessworkflow.api.Workflow) CompositeContextNode(io.automatiko.engine.workflow.process.core.node.CompositeContextNode) Map(java.util.Map) CompletionType(io.serverlessworkflow.api.states.ParallelState.CompletionType) EventState(io.serverlessworkflow.api.states.EventState) OnEvents(io.serverlessworkflow.api.events.OnEvents) Process(io.automatiko.engine.api.definition.process.Process) InputJqAssignmentAction(io.automatiko.engine.workflow.base.instance.impl.jq.InputJqAssignmentAction) Branch(io.serverlessworkflow.api.branches.Branch) JqReturnValueEvaluator(io.automatiko.engine.workflow.base.instance.impl.jq.JqReturnValueEvaluator) EventCondition(io.serverlessworkflow.api.switchconditions.EventCondition) Invoke(io.serverlessworkflow.api.functions.SubFlowRef.Invoke) InjectState(io.serverlessworkflow.api.states.InjectState) ActionNode(io.automatiko.engine.workflow.process.core.node.ActionNode) ErrorDefinition(io.serverlessworkflow.api.error.ErrorDefinition) Reader(java.io.Reader) UUID(java.util.UUID) ReturnValueConstraintEvaluator(io.automatiko.engine.workflow.base.instance.impl.ReturnValueConstraintEvaluator) ParallelState(io.serverlessworkflow.api.states.ParallelState) StandardCharsets(java.nio.charset.StandardCharsets) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) List(java.util.List) State(io.serverlessworkflow.api.interfaces.State) WorkItemNode(io.automatiko.engine.workflow.process.core.node.WorkItemNode) Optional(java.util.Optional) Join(io.automatiko.engine.workflow.process.core.node.Join) WorkflowUtils(io.serverlessworkflow.utils.WorkflowUtils) DefaultState(io.serverlessworkflow.api.states.DefaultState) SubProcessNode(io.automatiko.engine.workflow.process.core.node.SubProcessNode) DataCondition(io.serverlessworkflow.api.switchconditions.DataCondition) Assignment(io.automatiko.engine.workflow.process.core.node.Assignment) Action(io.serverlessworkflow.api.actions.Action) NodeContainer(io.automatiko.engine.workflow.process.core.NodeContainer) Split(io.automatiko.engine.workflow.process.core.node.Split) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) ProduceEvent(io.serverlessworkflow.api.produce.ProduceEvent) OutputJqAssignmentAction(io.automatiko.engine.workflow.base.instance.impl.jq.OutputJqAssignmentAction) DataAssociation(io.automatiko.engine.workflow.process.core.node.DataAssociation) FunctionDefinition(io.serverlessworkflow.api.functions.FunctionDefinition) OperationState(io.serverlessworkflow.api.states.OperationState) BoundaryEventNode(io.automatiko.engine.workflow.process.core.node.BoundaryEventNode) Type(io.serverlessworkflow.api.states.DefaultState.Type) BiConsumer(java.util.function.BiConsumer) WorkflowProcess(io.automatiko.engine.workflow.process.core.WorkflowProcess) Connection(io.automatiko.engine.api.definition.process.Connection) Node(io.automatiko.engine.workflow.process.core.Node) CallbackState(io.serverlessworkflow.api.states.CallbackState) ExecutableProcess(io.automatiko.engine.workflow.process.executable.core.ExecutableProcess) IOException(java.io.IOException) DateTimeUtils(io.automatiko.engine.workflow.base.core.timer.DateTimeUtils) OnParentComplete(io.serverlessworkflow.api.functions.SubFlowRef.OnParentComplete) EventDefinition(io.serverlessworkflow.api.events.EventDefinition) SleepState(io.serverlessworkflow.api.states.SleepState) RetryDefinition(io.serverlessworkflow.api.retry.RetryDefinition) AtomicLong(java.util.concurrent.atomic.AtomicLong) StartNode(io.automatiko.engine.workflow.process.core.node.StartNode) ActionMode(io.serverlessworkflow.api.states.OperationState.ActionMode) SwitchState(io.serverlessworkflow.api.states.SwitchState) Collections(java.util.Collections) EndNode(io.automatiko.engine.workflow.process.core.node.EndNode) EventNode(io.automatiko.engine.workflow.process.core.node.EventNode) ErrorDefinition(io.serverlessworkflow.api.error.ErrorDefinition) ArrayList(java.util.ArrayList) BoundaryEventNode(io.automatiko.engine.workflow.process.core.node.BoundaryEventNode) EndNode(io.automatiko.engine.workflow.process.core.node.EndNode)

Aggregations

Process (io.automatiko.engine.api.definition.process.Process)28 ArrayList (java.util.ArrayList)15 List (java.util.List)12 ExecutableProcess (io.automatiko.engine.workflow.process.executable.core.ExecutableProcess)11 Map (java.util.Map)10 WorkflowProcess (io.automatiko.engine.api.definition.process.WorkflowProcess)8 IOException (java.io.IOException)8 InternalProcessRuntime (io.automatiko.engine.workflow.base.instance.InternalProcessRuntime)7 WorkflowProcess (io.automatiko.engine.workflow.process.core.WorkflowProcess)7 StartNode (io.automatiko.engine.workflow.process.core.node.StartNode)6 WorkflowProcessInstanceImpl (io.automatiko.engine.workflow.process.instance.impl.WorkflowProcessInstanceImpl)6 UncheckedIOException (java.io.UncheckedIOException)6 HashMap (java.util.HashMap)5 NodeInstance (io.automatiko.engine.api.runtime.process.NodeInstance)4 Variable (io.automatiko.engine.workflow.base.core.context.variable.Variable)4 VariableScope (io.automatiko.engine.workflow.base.core.context.variable.VariableScope)4 ProcessInstance (io.automatiko.engine.workflow.base.instance.ProcessInstance)4 XmlProcessReader (io.automatiko.engine.workflow.compiler.xml.XmlProcessReader)4 Connection (io.automatiko.engine.api.definition.process.Connection)3 Resource (io.automatiko.engine.api.io.Resource)3