Search in sources :

Example 1 with BodyDeclarationComparator

use of io.automatiko.engine.codegen.BodyDeclarationComparator in project automatiko-engine by automatiko-io.

the class FunctionFlowGenerator method generate.

public String generate() {
    CompilationUnit clazz = parse(this.getClass().getResourceAsStream("/class-templates/FunctionFlowTemplate.java"));
    clazz.setPackageDeclaration(process.getPackageName());
    clazz.addImport(modelfqcn);
    ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).orElseThrow(() -> new IllegalStateException("Cannot find the class in FunctionFlowTemplate"));
    template.setName(functionClazzName);
    List<String> discoveredFunctions = new ArrayList<>();
    // first to initiate the function flow
    template.findFirst(MethodDeclaration.class, md -> md.getNameAsString().equals("startTemplate")).ifPresent(md -> {
        md.setName(processId.toLowerCase() + version);
        md.getBody().get().findFirst(StringLiteralExpr.class, s -> s.getValue().equals("$TypePrefix$")).ifPresent(s -> s.setValue(process.getPackageName() + "." + processId + fversion));
        if (useInjection()) {
            String trigger = functionTrigger(process);
            String filter = functionFilter(process);
            if (filter != null) {
                Matcher matcher = PARAMETER_MATCHER.matcher(filter);
                while (matcher.find()) {
                    String paramName = matcher.group(1);
                    Optional<String> value = context.getApplicationProperty(paramName);
                    if (value.isPresent()) {
                        filter = filter.replaceAll("\\{" + paramName + "\\}", value.get());
                    } else {
                        throw new IllegalArgumentException("Missing argument declared in as function filter with name '" + paramName + "'. Define it in application.properties file");
                    }
                }
            }
            annotator.withCloudEventMapping(md, trigger, filter);
        }
    });
    MethodDeclaration callTemplate = template.findFirst(MethodDeclaration.class, md -> md.getNameAsString().equals("callTemplate")).get();
    discoveredFunctions.add(definedFunctionTrigger(process));
    // for each "execution" node add new function
    for (Node node : process.getNodesRecursively()) {
        if (isExecutionNode(node)) {
            discoveredFunctions.add(definedFunctionTrigger(node));
            MethodDeclaration flowStepFunction = callTemplate.clone();
            if (useInjection()) {
                String trigger = functionTrigger(node);
                String filter = functionFilter(node);
                if (filter != null) {
                    Matcher matcher = PARAMETER_MATCHER.matcher(filter);
                    while (matcher.find()) {
                        String paramName = matcher.group(1);
                        Optional<String> value = context.getApplicationProperty(paramName);
                        if (value.isPresent() && !value.get().isEmpty()) {
                            filter = filter.replaceAll("\\{" + paramName + "\\}", value.get());
                        } else {
                            throw new IllegalArgumentException("Missing argument declared in as function filter with name '" + paramName + "'. Define it in application.properties file");
                        }
                    }
                }
                annotator.withCloudEventMapping(flowStepFunction, trigger, filter);
            }
            flowStepFunction.getBody().get().findFirst(StringLiteralExpr.class, s -> s.getValue().equals("$StartFromNode$")).ifPresent(s -> s.setValue((String) node.getMetaData().get("UniqueId")));
            flowStepFunction.getBody().get().findFirst(StringLiteralExpr.class, s -> s.getValue().equals("$TypePrefix$")).ifPresent(s -> s.setValue(process.getPackageName() + "." + processId + fversion + "."));
            flowStepFunction.getBody().get().findFirst(StringLiteralExpr.class, s -> s.getValue().equals("$ThisNode$")).ifPresent(s -> s.setValue(node.getName()));
            flowStepFunction.setName(sanitizeIdentifier(node.getName() + version).toLowerCase());
            template.addMember(flowStepFunction);
        } else if (node instanceof EndNode || node instanceof FaultNode) {
            discoveredFunctions.add(definedFunctionTrigger(node));
        }
    }
    // remove the template method
    callTemplate.removeForced();
    // process signals
    MethodDeclaration signalTemplate = template.findFirst(MethodDeclaration.class, md -> md.getNameAsString().equals("signalTemplate")).get();
    Optional.ofNullable(signals).ifPresent(signalsMap -> {
        AtomicInteger index = new AtomicInteger(0);
        signalsMap.entrySet().stream().filter(e -> Objects.nonNull(e.getKey())).forEach(entry -> {
            String signalName = entry.getKey();
            String signalType = entry.getValue();
            MethodDeclaration flowSignalFunction = produceSignalFunction("", signalName, signalType, signalTemplate, index, signalNodes.get(signalName));
            template.addMember(flowSignalFunction);
        });
    });
    if (triggers != null && !triggers.isEmpty()) {
        AtomicInteger index = new AtomicInteger(0);
        for (TriggerMetaData trigger : triggers) {
            if (trigger.getType().equals(TriggerMetaData.TriggerType.ConsumeMessage)) {
                String signalName = trigger.getName();
                String signalType = trigger.getDataType();
                MethodDeclaration flowSignalFunction = produceSignalFunction("Message-", signalName, signalType, signalTemplate, index, (Node) trigger.getContext("_node_"));
                VariableDeclarationExpr correlationVar = flowSignalFunction.findFirst(VariableDeclarationExpr.class, vd -> vd.getVariable(0).getNameAsString().equals("correlation")).get();
                if (trigger.getCorrelation() != null) {
                    correlationVar.getVariable(0).setInitializer(new StringLiteralExpr(trigger.getCorrelation()));
                } else if (trigger.getCorrelationExpression() != null) {
                    correlationVar.getVariable(0).setInitializer(new NameExpr(trigger.getCorrelationExpression()));
                }
                template.addMember(flowSignalFunction);
            }
        }
    }
    // remove the template method
    signalTemplate.removeForced();
    Map<String, String> typeInterpolations = new HashMap<>();
    typeInterpolations.put("$Clazz$", functionClazzName);
    typeInterpolations.put("$Type$", dataClazzName);
    template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, typeInterpolations));
    if (useInjection()) {
        template.findAll(FieldDeclaration.class, CodegenUtils::isProcessField).forEach(fd -> annotator.withNamedInjection(fd, processId + version));
        template.findAll(FieldDeclaration.class, CodegenUtils::isApplicationField).forEach(fd -> annotator.withInjection(fd));
        template.findAll(FieldDeclaration.class, CodegenUtils::isIdentitySupplierField).forEach(fd -> annotator.withInjection(fd));
        template.findAll(FieldDeclaration.class, CodegenUtils::isEventSourceField).forEach(fd -> annotator.withInjection(fd));
        template.findAll(MethodDeclaration.class, md -> md.isPublic()).forEach(md -> annotator.withFunction(md));
    }
    NodeList<Expression> items = NodeList.nodeList(discoveredFunctions.stream().map(s -> new StringLiteralExpr(s)).collect(Collectors.toList()));
    template.addAnnotation(new NormalAnnotationExpr(new Name(Generated.class.getCanonicalName()), NodeList.nodeList(new MemberValuePair("value", new ArrayInitializerExpr(items)), new MemberValuePair("reference", new StringLiteralExpr(context.getApplicationProperty("quarkus.google.cloud.project-id").orElse("missing"))), new MemberValuePair("name", new StringLiteralExpr(StringUtils.capitalize(ProcessToExecModelGenerator.extractProcessId(processId, version)))), new MemberValuePair("hidden", new BooleanLiteralExpr(false)))));
    template.getMembers().sort(new BodyDeclarationComparator());
    ImportsOrganizer.organize(clazz);
    return clazz.toString();
}
Also used : SubProcessNode(io.automatiko.engine.workflow.process.core.node.SubProcessNode) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) ProcessToExecModelGenerator(io.automatiko.engine.workflow.compiler.canonical.ProcessToExecModelGenerator) RuleSetNode(io.automatiko.engine.workflow.process.core.node.RuleSetNode) StaticJavaParser.parse(com.github.javaparser.StaticJavaParser.parse) Name(com.github.javaparser.ast.expr.Name) GeneratorContext(io.automatiko.engine.codegen.GeneratorContext) HashMap(java.util.HashMap) Node(io.automatiko.engine.api.definition.process.Node) ArrayList(java.util.ArrayList) Matcher(java.util.regex.Matcher) CodegenUtils.interpolateTypes(io.automatiko.engine.codegen.CodegenUtils.interpolateTypes) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) BoundaryEventNode(io.automatiko.engine.workflow.process.core.node.BoundaryEventNode) StringUtils(io.automatiko.engine.services.utils.StringUtils) Expression(com.github.javaparser.ast.expr.Expression) CompilationUnit(com.github.javaparser.ast.CompilationUnit) TriggerMetaData(io.automatiko.engine.workflow.compiler.canonical.TriggerMetaData) DependencyInjectionAnnotator(io.automatiko.engine.codegen.di.DependencyInjectionAnnotator) CodegenUtils(io.automatiko.engine.codegen.CodegenUtils) NodeList(com.github.javaparser.ast.NodeList) BooleanLiteralExpr(com.github.javaparser.ast.expr.BooleanLiteralExpr) WorkflowProcess(io.automatiko.engine.api.definition.process.WorkflowProcess) ActionNode(io.automatiko.engine.workflow.process.core.node.ActionNode) BodyDeclarationComparator(io.automatiko.engine.codegen.BodyDeclarationComparator) FaultNode(io.automatiko.engine.workflow.process.core.node.FaultNode) NameExpr(com.github.javaparser.ast.expr.NameExpr) Collectors(java.util.stream.Collectors) NormalAnnotationExpr(com.github.javaparser.ast.expr.NormalAnnotationExpr) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) VariableDeclarationExpr(com.github.javaparser.ast.expr.VariableDeclarationExpr) Objects(java.util.Objects) List(java.util.List) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) MemberValuePair(com.github.javaparser.ast.expr.MemberValuePair) WorkItemNode(io.automatiko.engine.workflow.process.core.node.WorkItemNode) Optional(java.util.Optional) StartNode(io.automatiko.engine.workflow.process.core.node.StartNode) Pattern(java.util.regex.Pattern) ArrayInitializerExpr(com.github.javaparser.ast.expr.ArrayInitializerExpr) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) Generated(io.automatiko.engine.api.codegen.Generated) ImportsOrganizer(io.automatiko.engine.codegen.ImportsOrganizer) EndNode(io.automatiko.engine.workflow.process.core.node.EndNode) EventNode(io.automatiko.engine.workflow.process.core.node.EventNode) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) Matcher(java.util.regex.Matcher) HashMap(java.util.HashMap) SubProcessNode(io.automatiko.engine.workflow.process.core.node.SubProcessNode) RuleSetNode(io.automatiko.engine.workflow.process.core.node.RuleSetNode) Node(io.automatiko.engine.api.definition.process.Node) BoundaryEventNode(io.automatiko.engine.workflow.process.core.node.BoundaryEventNode) ActionNode(io.automatiko.engine.workflow.process.core.node.ActionNode) FaultNode(io.automatiko.engine.workflow.process.core.node.FaultNode) WorkItemNode(io.automatiko.engine.workflow.process.core.node.WorkItemNode) StartNode(io.automatiko.engine.workflow.process.core.node.StartNode) EndNode(io.automatiko.engine.workflow.process.core.node.EndNode) EventNode(io.automatiko.engine.workflow.process.core.node.EventNode) ArrayList(java.util.ArrayList) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) NameExpr(com.github.javaparser.ast.expr.NameExpr) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) Name(com.github.javaparser.ast.expr.Name) MemberValuePair(com.github.javaparser.ast.expr.MemberValuePair) ArrayInitializerExpr(com.github.javaparser.ast.expr.ArrayInitializerExpr) BooleanLiteralExpr(com.github.javaparser.ast.expr.BooleanLiteralExpr) BodyDeclarationComparator(io.automatiko.engine.codegen.BodyDeclarationComparator) NormalAnnotationExpr(com.github.javaparser.ast.expr.NormalAnnotationExpr) CompilationUnit(com.github.javaparser.ast.CompilationUnit) VariableDeclarationExpr(com.github.javaparser.ast.expr.VariableDeclarationExpr) Generated(io.automatiko.engine.api.codegen.Generated) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) TriggerMetaData(io.automatiko.engine.workflow.compiler.canonical.TriggerMetaData) FaultNode(io.automatiko.engine.workflow.process.core.node.FaultNode) EndNode(io.automatiko.engine.workflow.process.core.node.EndNode) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Expression(com.github.javaparser.ast.expr.Expression)

Example 2 with BodyDeclarationComparator

use of io.automatiko.engine.codegen.BodyDeclarationComparator in project automatiko-engine by automatiko-io.

the class FunctionGenerator method generate.

public String generate() {
    CompilationUnit clazz = parse(this.getClass().getResourceAsStream("/class-templates/FunctionTemplate.java"));
    clazz.setPackageDeclaration(process.getPackageName());
    clazz.addImport(modelfqcn);
    ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).orElseThrow(() -> new IllegalStateException("Cannot find the class in FunctionTemplate"));
    template.setName(functionClazzName);
    Map<String, String> typeInterpolations = new HashMap<>();
    typeInterpolations.put("$Clazz$", functionClazzName);
    typeInterpolations.put("$Type$", dataClazzName);
    template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, typeInterpolations));
    if (useInjection()) {
        template.findAll(FieldDeclaration.class, CodegenUtils::isProcessField).forEach(fd -> annotator.withNamedInjection(fd, processId + version));
        template.findAll(FieldDeclaration.class, CodegenUtils::isApplicationField).forEach(fd -> annotator.withInjection(fd));
        template.findAll(FieldDeclaration.class, CodegenUtils::isIdentitySupplierField).forEach(fd -> annotator.withInjection(fd));
        template.findFirst(MethodDeclaration.class, md -> md.isPublic()).ifPresent(md -> {
            annotator.withFunction(md);
            md.setName(processId);
        });
    }
    template.getMembers().sort(new BodyDeclarationComparator());
    ImportsOrganizer.organize(clazz);
    return clazz.toString();
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) ProcessToExecModelGenerator(io.automatiko.engine.workflow.compiler.canonical.ProcessToExecModelGenerator) StaticJavaParser.parse(com.github.javaparser.StaticJavaParser.parse) WorkflowProcess(io.automatiko.engine.api.definition.process.WorkflowProcess) BodyDeclarationComparator(io.automatiko.engine.codegen.BodyDeclarationComparator) GeneratorContext(io.automatiko.engine.codegen.GeneratorContext) HashMap(java.util.HashMap) CodegenUtils.interpolateTypes(io.automatiko.engine.codegen.CodegenUtils.interpolateTypes) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) Map(java.util.Map) StringUtils(io.automatiko.engine.services.utils.StringUtils) CompilationUnit(com.github.javaparser.ast.CompilationUnit) DependencyInjectionAnnotator(io.automatiko.engine.codegen.di.DependencyInjectionAnnotator) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) ImportsOrganizer(io.automatiko.engine.codegen.ImportsOrganizer) CodegenUtils(io.automatiko.engine.codegen.CodegenUtils) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) HashMap(java.util.HashMap) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) BodyDeclarationComparator(io.automatiko.engine.codegen.BodyDeclarationComparator) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration)

Example 3 with BodyDeclarationComparator

use of io.automatiko.engine.codegen.BodyDeclarationComparator in project automatiko-engine by automatiko-io.

the class MessageDataEventGenerator method generate.

public String generate() {
    CompilationUnit clazz = parse(this.getClass().getResourceAsStream("/class-templates/MessageDataEventTemplate.java"));
    clazz.setPackageDeclaration(process.getPackageName());
    ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).orElseThrow(() -> new IllegalStateException("Cannot find the class in MessageDataEventTemplate"));
    template.setName(resourceClazzName);
    template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, trigger.getDataType()));
    template.findAll(ConstructorDeclaration.class).stream().forEach(cd -> cd.setName(resourceClazzName));
    template.getMembers().sort(new BodyDeclarationComparator());
    return clazz.toString();
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) BodyDeclarationComparator(io.automatiko.engine.codegen.BodyDeclarationComparator) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType)

Example 4 with BodyDeclarationComparator

use of io.automatiko.engine.codegen.BodyDeclarationComparator 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 5 with BodyDeclarationComparator

use of io.automatiko.engine.codegen.BodyDeclarationComparator in project automatiko-engine by automatiko-io.

the class PersistenceGenerator method mongodbBasedPersistence.

protected void mongodbBasedPersistence(List<GeneratedFile> generatedFiles) {
    ClassOrInterfaceDeclaration persistenceProviderClazz = new ClassOrInterfaceDeclaration().setName("ProcessInstancesFactoryImpl").setModifiers(Modifier.Keyword.PUBLIC).addExtendedType("io.automatiko.engine.addons.persistence.AbstractProcessInstancesFactory");
    CompilationUnit compilationUnit = new CompilationUnit("io.automatiko.engine.addons.persistence.impl");
    compilationUnit.getTypes().add(persistenceProviderClazz);
    persistenceProviderClazz.addConstructor(Keyword.PUBLIC);
    ConstructorDeclaration constructor = persistenceProviderClazz.addConstructor(Keyword.PUBLIC).addParameter("com.mongodb.client.MongoClient", "mongoClient").addParameter("io.automatiko.engine.api.config.MongodbPersistenceConfig", "config");
    BlockStmt body = new BlockStmt();
    ExplicitConstructorInvocationStmt superExp = new ExplicitConstructorInvocationStmt(false, null, NodeList.nodeList(new NameExpr("mongoClient"), new NameExpr("config")));
    body.addStatement(superExp);
    constructor.setBody(body);
    if (useInjection()) {
        annotator.withApplicationComponent(persistenceProviderClazz);
        annotator.withInjection(constructor);
        addCodecComponents(persistenceProviderClazz);
    }
    String packageName = compilationUnit.getPackageDeclaration().map(pd -> pd.getName().toString()).orElse("");
    String clazzName = packageName + "." + persistenceProviderClazz.findFirst(ClassOrInterfaceDeclaration.class).map(c -> c.getName().toString()).get();
    generatedFiles.add(new GeneratedFile(GeneratedFile.Type.CLASS, clazzName.replace('.', '/') + ".java", compilationUnit.toString().getBytes(StandardCharsets.UTF_8)));
    persistenceProviderClazz.getMembers().sort(new BodyDeclarationComparator());
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) ApplicationSection(io.automatiko.engine.codegen.ApplicationSection) ArrayList(java.util.ArrayList) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) CompilationUnit(com.github.javaparser.ast.CompilationUnit) Keyword(com.github.javaparser.ast.Modifier.Keyword) DependencyInjectionAnnotator(io.automatiko.engine.codegen.di.DependencyInjectionAnnotator) ConfigGenerator(io.automatiko.engine.codegen.ConfigGenerator) NodeList(com.github.javaparser.ast.NodeList) SimpleName(com.github.javaparser.ast.expr.SimpleName) GeneratedFile(io.automatiko.engine.codegen.GeneratedFile) Collection(java.util.Collection) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) StoredDataCodec(io.automatiko.engine.api.workflow.encrypt.StoredDataCodec) BodyDeclarationComparator(io.automatiko.engine.codegen.BodyDeclarationComparator) NameExpr(com.github.javaparser.ast.expr.NameExpr) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) ExplicitConstructorInvocationStmt(com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt) Modifier(com.github.javaparser.ast.Modifier) List(java.util.List) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) AbstractGenerator(io.automatiko.engine.codegen.AbstractGenerator) Optional(java.util.Optional) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) NameExpr(com.github.javaparser.ast.expr.NameExpr) BodyDeclarationComparator(io.automatiko.engine.codegen.BodyDeclarationComparator) ExplicitConstructorInvocationStmt(com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt) GeneratedFile(io.automatiko.engine.codegen.GeneratedFile)

Aggregations

ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)14 ClassOrInterfaceType (com.github.javaparser.ast.type.ClassOrInterfaceType)14 BodyDeclarationComparator (io.automatiko.engine.codegen.BodyDeclarationComparator)14 FieldDeclaration (com.github.javaparser.ast.body.FieldDeclaration)12 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)12 CompilationUnit (com.github.javaparser.ast.CompilationUnit)11 NameExpr (com.github.javaparser.ast.expr.NameExpr)11 StringLiteralExpr (com.github.javaparser.ast.expr.StringLiteralExpr)11 VariableDeclarator (com.github.javaparser.ast.body.VariableDeclarator)10 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)10 BlockStmt (com.github.javaparser.ast.stmt.BlockStmt)10 DependencyInjectionAnnotator (io.automatiko.engine.codegen.di.DependencyInjectionAnnotator)10 ReturnStmt (com.github.javaparser.ast.stmt.ReturnStmt)9 ConstructorDeclaration (com.github.javaparser.ast.body.ConstructorDeclaration)8 Keyword (com.github.javaparser.ast.Modifier.Keyword)7 NodeList (com.github.javaparser.ast.NodeList)7 SimpleName (com.github.javaparser.ast.expr.SimpleName)7 List (java.util.List)7 Optional (java.util.Optional)7 StaticJavaParser.parse (com.github.javaparser.StaticJavaParser.parse)5