use of io.automatiko.engine.api.Functions 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();
}
use of io.automatiko.engine.api.Functions in project automatiko-engine by automatiko-io.
the class ProcessGenerator method compilationUnit.
public CompilationUnit compilationUnit() {
CompilationUnit compilationUnit = new CompilationUnit(packageName);
compilationUnit.addImport("io.automatiko.engine.workflow.base.core.datatype.impl.type.ObjectDataType");
compilationUnit.addImport("io.automatiko.engine.workflow.process.executable.core.ExecutableProcessFactory");
compilationUnit.addImport(new ImportDeclaration(BaseFunctions.class.getCanonicalName(), true, true));
if (isServerlessWorkflow()) {
compilationUnit.addImport(new ImportDeclaration(ServerlessFunctions.class.getCanonicalName(), true, true));
}
List<String> functions = context.getBuildContext().classThatImplement(Functions.class.getCanonicalName());
functions.forEach(c -> compilationUnit.addImport(new ImportDeclaration(c, true, true)));
compilationUnit.getTypes().add(classDeclaration(compilationUnit));
return compilationUnit;
}
use of io.automatiko.engine.api.Functions in project automatiko-engine by automatiko-io.
the class ProcessCodegen method generate.
public List<GeneratedFile> generate() {
if (processes.isEmpty()) {
return Collections.emptyList();
}
List<ProcessGenerator> ps = new ArrayList<>();
List<ProcessInstanceGenerator> pis = new ArrayList<>();
List<ProcessExecutableModelGenerator> processExecutableModelGenerators = new ArrayList<>();
// REST resources
List<AbstractResourceGenerator> rgs = new ArrayList<>();
// GraphQL resources
List<AbstractResourceGenerator> grapggs = new ArrayList<>();
// Function resources
List<FunctionGenerator> fgs = new ArrayList<>();
// Function flow resources
List<FunctionFlowGenerator> ffgs = new ArrayList<>();
// message data events
List<MessageDataEventGenerator> mdegs = new ArrayList<>();
// message endpoints/consumers
Set<MessageConsumerGenerator> megs = new LinkedHashSet<>();
// message producers
List<MessageProducerGenerator> mpgs = new ArrayList<>();
// OpenAPI clients
Set<OpenAPIClientGenerator> opgs = new LinkedHashSet<>();
List<String> publicProcesses = new ArrayList<>();
Map<String, ModelMetaData> processIdToModel = new HashMap<>();
Map<String, ModelClassGenerator> processIdToModelGenerator = new HashMap<>();
Map<String, InputModelClassGenerator> processIdToInputModelGenerator = new HashMap<>();
Map<String, OutputModelClassGenerator> processIdToOutputModelGenerator = new HashMap<>();
Map<String, List<UserTaskModelMetaData>> processIdToUserTaskModel = new HashMap<>();
Map<String, ProcessMetaData> processIdToMetadata = new HashMap<>();
String workflowType = Process.WORKFLOW_TYPE;
if (isFunctionFlowProject()) {
workflowType = Process.FUNCTION_FLOW_TYPE;
} else if (isFunctionProject()) {
workflowType = Process.FUNCTION_TYPE;
}
// then we can instantiate the exec model generator
// with the data classes that we have already resolved
ProcessToExecModelGenerator execModelGenerator = new ProcessToExecModelGenerator(contextClassLoader, workflowType);
// first we generate all the data classes from variable declarations
for (Entry<String, WorkflowProcess> entry : processes.entrySet()) {
ModelClassGenerator mcg = new ModelClassGenerator(execModelGenerator, context(), entry.getValue());
processIdToModelGenerator.put(entry.getKey(), mcg);
processIdToModel.put(entry.getKey(), mcg.generate());
InputModelClassGenerator imcg = new InputModelClassGenerator(context(), entry.getValue(), workflowType);
processIdToInputModelGenerator.put(entry.getKey(), imcg);
OutputModelClassGenerator omcg = new OutputModelClassGenerator(context(), entry.getValue(), workflowType);
processIdToOutputModelGenerator.put(entry.getKey(), omcg);
context.addGenerator("ModelClassGenerator", entry.getKey(), mcg);
context.addGenerator("InputModelClassGenerator", entry.getKey(), imcg);
context.addGenerator("OutputModelClassGenerator", entry.getKey(), omcg);
}
// then we generate user task inputs and outputs if any
for (Entry<String, WorkflowProcess> entry : processes.entrySet()) {
UserTasksModelClassGenerator utcg = new UserTasksModelClassGenerator(entry.getValue(), context);
processIdToUserTaskModel.put(entry.getKey(), utcg.generate());
}
List<String> functions = context.getBuildContext().classThatImplement(Functions.class.getCanonicalName());
// collect all process descriptors (exec model)
for (Entry<String, WorkflowProcess> entry : processes.entrySet()) {
ProcessExecutableModelGenerator execModelGen = new ProcessExecutableModelGenerator(entry.getValue(), execModelGenerator);
String packageName = entry.getValue().getPackageName();
String id = entry.getKey();
// add extra meta data to indicate if user task mgmt is available
if (context.getBuildContext().isUserTaskMgmtSupported()) {
entry.getValue().getMetaData().put("UserTaskMgmt", "true");
}
Set<String> classImports = ((io.automatiko.engine.workflow.process.core.WorkflowProcess) entry.getValue()).getImports();
if (classImports != null) {
classImports = new HashSet<>();
((io.automatiko.engine.workflow.process.core.WorkflowProcess) entry.getValue()).setImports(classImports);
}
classImports.add(BaseFunctions.class.getCanonicalName());
classImports.addAll(functions);
try {
ProcessMetaData generate = execModelGen.generate();
processIdToMetadata.put(id, generate);
processExecutableModelGenerators.add(execModelGen);
context.addProcess(id, generate);
} catch (RuntimeException e) {
LOGGER.error(e.getMessage());
throw new ProcessCodegenException(id, packageName, e);
}
}
// generate Process, ProcessInstance classes and the REST resource
for (ProcessExecutableModelGenerator execModelGen : processExecutableModelGenerators) {
String classPrefix = StringUtils.capitalize(execModelGen.extractedProcessId());
WorkflowProcess workFlowProcess = execModelGen.process();
ModelClassGenerator modelClassGenerator = processIdToModelGenerator.get(execModelGen.getProcessId());
ProcessGenerator p = new ProcessGenerator(context, workFlowProcess, execModelGen, classPrefix, modelClassGenerator.className(), applicationCanonicalName, processIdToUserTaskModel.get(execModelGen.getProcessId()), processIdToMetadata).withDependencyInjection(annotator).withPersistence(persistence);
ProcessInstanceGenerator pi = new ProcessInstanceGenerator(workflowType, context(), execModelGen, workFlowProcess.getPackageName(), classPrefix, modelClassGenerator.generate());
ProcessMetaData metaData = processIdToMetadata.get(execModelGen.getProcessId());
if (isFunctionFlowProject()) {
ffgs.add(new FunctionFlowGenerator(context(), workFlowProcess, modelClassGenerator.className(), execModelGen.className(), applicationCanonicalName).withDependencyInjection(annotator).withSignals(metaData.getSignals(), metaData.getSignalNodes()).withTriggers(metaData.getTriggers()));
if (metaData.getTriggers() != null) {
for (TriggerMetaData trigger : metaData.getTriggers()) {
if (trigger.getType().equals(TriggerMetaData.TriggerType.ProduceMessage)) {
MessageDataEventGenerator msgDataEventGenerator = new MessageDataEventGenerator(workFlowProcess, trigger).withDependencyInjection(annotator);
mdegs.add(msgDataEventGenerator);
mpgs.add(new MessageProducerGenerator(workflowType, context(), workFlowProcess, modelClassGenerator.className(), execModelGen.className(), msgDataEventGenerator.className(), trigger).withDependencyInjection(annotator));
}
}
}
} else if (isFunctionProject()) {
fgs.add(new FunctionGenerator(context(), workFlowProcess, modelClassGenerator.className(), execModelGen.className(), applicationCanonicalName).withDependencyInjection(annotator));
} else if (isServiceProject()) {
if (isPublic(workFlowProcess)) {
// Creating and adding the ResourceGenerator
resourceGeneratorFactory.create(context(), workFlowProcess, modelClassGenerator.className(), execModelGen.className(), applicationCanonicalName).map(r -> r.withDependencyInjection(annotator).withParentProcess(null).withPersistence(persistence).withUserTasks(processIdToUserTaskModel.get(execModelGen.getProcessId())).withPathPrefix("{id}").withSignals(metaData.getSignals()).withTriggers(metaData.isStartable(), metaData.isDynamic()).withSubProcesses(populateSubprocesses(workFlowProcess, processIdToMetadata.get(execModelGen.getProcessId()), processIdToMetadata, processIdToModelGenerator, processExecutableModelGenerators, processIdToUserTaskModel))).ifPresent(rgs::add);
if (context.getBuildContext().isGraphQLSupported()) {
GraphQLResourceGenerator graphqlGenerator = new GraphQLResourceGenerator(context(), workFlowProcess, modelClassGenerator.className(), execModelGen.className(), applicationCanonicalName);
graphqlGenerator.withDependencyInjection(annotator).withParentProcess(null).withPersistence(persistence).withUserTasks(processIdToUserTaskModel.get(execModelGen.getProcessId())).withPathPrefix(CodegenUtils.version(workFlowProcess.getVersion())).withSignals(metaData.getSignals()).withTriggers(metaData.isStartable(), metaData.isDynamic()).withSubProcesses(populateSubprocessesGraphQL(workFlowProcess, processIdToMetadata.get(execModelGen.getProcessId()), processIdToMetadata, processIdToModelGenerator, processExecutableModelGenerators, processIdToUserTaskModel));
grapggs.add(graphqlGenerator);
}
}
if (metaData.getTriggers() != null) {
for (TriggerMetaData trigger : metaData.getTriggers()) {
// generate message consumers for processes with message events
if (isPublic(workFlowProcess) && trigger.getType().equals(TriggerMetaData.TriggerType.ConsumeMessage)) {
MessageDataEventGenerator msgDataEventGenerator = new MessageDataEventGenerator(workFlowProcess, trigger).withDependencyInjection(annotator);
mdegs.add(msgDataEventGenerator);
megs.add(new MessageConsumerGenerator(context(), workFlowProcess, modelClassGenerator.className(), execModelGen.className(), applicationCanonicalName, msgDataEventGenerator.className(), trigger).withDependencyInjection(annotator).withPersistence(persistence));
} else if (trigger.getType().equals(TriggerMetaData.TriggerType.ProduceMessage)) {
MessageDataEventGenerator msgDataEventGenerator = new MessageDataEventGenerator(workFlowProcess, trigger).withDependencyInjection(annotator);
mdegs.add(msgDataEventGenerator);
mpgs.add(new MessageProducerGenerator(workflowType, context(), workFlowProcess, modelClassGenerator.className(), execModelGen.className(), msgDataEventGenerator.className(), trigger).withDependencyInjection(annotator));
}
}
}
}
if (metaData.getOpenAPIs() != null) {
for (OpenAPIMetaData api : metaData.getOpenAPIs()) {
OpenAPIClientGenerator oagenerator = new OpenAPIClientGenerator(context, workFlowProcess, api).withDependencyInjection(annotator);
opgs.add(oagenerator);
}
}
moduleGenerator.addProcess(p);
ps.add(p);
pis.add(pi);
}
for (ModelClassGenerator modelClassGenerator : processIdToModelGenerator.values()) {
ModelMetaData mmd = modelClassGenerator.generate();
storeFile(Type.MODEL, modelClassGenerator.generatedFilePath(), mmd.generate(annotator != null ? new String[] { "io.quarkus.runtime.annotations.RegisterForReflection" } : new String[0]));
}
for (InputModelClassGenerator modelClassGenerator : processIdToInputModelGenerator.values()) {
ModelMetaData mmd = modelClassGenerator.generate();
storeFile(Type.MODEL, modelClassGenerator.generatedFilePath(), mmd.generate(annotator != null ? new String[] { "io.quarkus.runtime.annotations.RegisterForReflection" } : new String[0]));
}
for (OutputModelClassGenerator modelClassGenerator : processIdToOutputModelGenerator.values()) {
ModelMetaData mmd = modelClassGenerator.generate();
storeFile(Type.MODEL, modelClassGenerator.generatedFilePath(), mmd.generate(annotator != null ? new String[] { "io.quarkus.runtime.annotations.RegisterForReflection" } : new String[0]));
}
for (List<UserTaskModelMetaData> utmd : processIdToUserTaskModel.values()) {
for (UserTaskModelMetaData ut : utmd) {
storeFile(Type.MODEL, UserTasksModelClassGenerator.generatedFilePath(ut.getInputModelClassName()), ut.generateInput());
storeFile(Type.MODEL, UserTasksModelClassGenerator.generatedFilePath(ut.getOutputModelClassName()), ut.generateOutput());
}
}
for (AbstractResourceGenerator resourceGenerator : rgs) {
storeFile(Type.REST, resourceGenerator.generatedFilePath(), resourceGenerator.generate());
}
for (AbstractResourceGenerator resourceGenerator : grapggs) {
storeFile(Type.GRAPHQL, resourceGenerator.generatedFilePath(), resourceGenerator.generate());
}
for (FunctionGenerator functionGenerator : fgs) {
storeFile(Type.FUNCTION, functionGenerator.generatedFilePath(), functionGenerator.generate());
}
for (FunctionFlowGenerator functionFlowGenerator : ffgs) {
storeFile(Type.FUNCTION_FLOW, functionFlowGenerator.generatedFilePath(), functionFlowGenerator.generate());
}
for (MessageDataEventGenerator messageDataEventGenerator : mdegs) {
storeFile(Type.CLASS, messageDataEventGenerator.generatedFilePath(), messageDataEventGenerator.generate());
}
for (MessageConsumerGenerator messageConsumerGenerator : megs) {
storeFile(Type.MESSAGE_CONSUMER, messageConsumerGenerator.generatedFilePath(), messageConsumerGenerator.generate());
}
for (MessageProducerGenerator messageProducerGenerator : mpgs) {
storeFile(Type.MESSAGE_PRODUCER, messageProducerGenerator.generatedFilePath(), messageProducerGenerator.generate());
}
for (OpenAPIClientGenerator openApiClientGenerator : opgs) {
openApiClientGenerator.generate();
Map<String, String> contents = openApiClientGenerator.generatedClasses();
for (Entry<String, String> entry : contents.entrySet()) {
storeFile(Type.CLASS, entry.getKey().replace('.', '/') + ".java", entry.getValue());
}
}
for (ProcessGenerator p : ps) {
storeFile(Type.PROCESS, p.generatedFilePath(), p.generate());
p.getAdditionalClasses().forEach(cp -> {
String packageName = cp.getPackageDeclaration().map(pd -> pd.getName().toString()).orElse("");
String clazzName = cp.findFirst(ClassOrInterfaceDeclaration.class).map(cls -> cls.getName().toString()).get();
String path = (packageName + "." + clazzName).replace('.', '/') + ".java";
storeFile(Type.CLASS, path, cp.toString());
});
}
for (ProcessInstanceGenerator pi : pis) {
storeFile(Type.PROCESS_INSTANCE, pi.generatedFilePath(), pi.generate());
}
for (ProcessExecutableModelGenerator processGenerator : processExecutableModelGenerators) {
if (processGenerator.isPublic()) {
publicProcesses.add(processGenerator.extractedProcessId());
}
}
return generatedFiles;
}
use of io.automatiko.engine.api.Functions in project automatiko-engine by automatiko-io.
the class MessageConsumerGenerator method generate.
public String generate() {
String sanitizedName = CodegenUtils.triggerSanitizedName(trigger, process.getVersion());
String connector = CodegenUtils.getConnector(INCOMING_PROP_PREFIX + sanitizedName + ".connector", context, (String) trigger.getContext("connector"));
if (connector != null && !OPERATOR_CONNECTOR.equals(connector)) {
context.setApplicationProperty(INCOMING_PROP_PREFIX + sanitizedName + ".connector", connector);
appendConnectorSpecificProperties(connector);
}
// operator consumer only supports starting message endpoints
if (OPERATOR_CONNECTOR.equals(connector) && !trigger.isStart()) {
return null;
}
CompilationUnit clazz = parse(this.getClass().getResourceAsStream(consumerTemplate(connector)));
clazz.setPackageDeclaration(process.getPackageName());
clazz.addImport(modelfqcn);
// add functions so they can be easily accessed in message consumer 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, dataClazzName));
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("consume") || md.getNameAsString().equals("cleanup") || md.getNameAsString().equals("reconcile")).forEach(md -> {
md.findAll(StringLiteralExpr.class).forEach(str -> str.setString(str.asString().replace("$Trigger$", trigger.getName())));
md.findAll(ClassOrInterfaceType.class).forEach(t -> t.setName(t.getNameAsString().replace("$DataEventType$", messageDataEventClassName)));
md.findAll(ClassOrInterfaceType.class).forEach(t -> t.setName(t.getNameAsString().replace("$DataType$", trigger.getDataType())));
md.setType(md.getTypeAsString().replace("$DataType$", trigger.getDataType()));
});
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())));
});
if (trigger.getModelRef().startsWith("#")) {
template.findAll(MethodCallExpr.class).stream().filter(m -> m.getNameAsString().endsWith("$ModelRef$")).forEach(m -> {
m.getParentNode().ifPresent(p -> p.removeForced());
});
} else {
template.findAll(MethodCallExpr.class).forEach(this::interpolateStrings);
}
if (useInjection()) {
if (!OPERATOR_CONNECTOR.equals(connector)) {
annotator.withApplicationComponent(template);
}
template.findAll(FieldDeclaration.class, fd -> isProcessField(fd)).forEach(fd -> annotator.withNamedInjection(fd, processId + version));
template.findAll(FieldDeclaration.class, fd -> isApplicationField(fd)).forEach(fd -> annotator.withInjection(fd));
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(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("consume")).forEach(md -> {
if (persistence) {
annotator.withBlocking(md);
}
annotator.withIncomingMessage(md, sanitizedName);
if (context.getBuildContext().hasClassAvailable("org.eclipse.microprofile.opentracing.Traced")) {
md.addAnnotation("org.eclipse.microprofile.opentracing.Traced");
}
});
} else {
template.findAll(FieldDeclaration.class, fd -> isProcessField(fd)).forEach(fd -> initializeProcessField(fd, template));
template.findAll(FieldDeclaration.class, fd -> isApplicationField(fd)).forEach(fd -> initializeApplicationField(fd, template));
template.findAll(FieldDeclaration.class, fd -> fd.getVariables().get(0).getNameAsString().equals("converter")).forEach(fd -> {
fd.getVariable(0).setType(fd.getVariable(0).getTypeAsString().replace("$DataType$", trigger.getDataType()));
});
}
BlockStmt filterExpressionBody = new BlockStmt();
if (trigger.getContext("filterExpression") != null) {
filterExpressionBody.addStatement(new ReturnStmt(new NameExpr((String) trigger.getContext("filterExpression"))));
} else {
filterExpressionBody.addStatement(new ReturnStmt(new BooleanLiteralExpr(true)));
}
BlockStmt body = new BlockStmt();
if (trigger.getCorrelation() != null) {
body.addStatement(new ReturnStmt(new StringLiteralExpr(trigger.getCorrelation())));
} else if (trigger.getCorrelationExpression() != null) {
body.addStatement(new ReturnStmt(new NameExpr(trigger.getCorrelationExpression())));
} else {
body.addStatement(new ReturnStmt(new NullLiteralExpr()));
}
boolean cloudEvents = context.getBuildContext().config().messaging().asCloudevents() || Boolean.parseBoolean(context.getApplicationProperty("quarkus.automatiko.messaging.as-cloudevents").orElse("false"));
if (cloudEvents) {
template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("correlationEvent")).forEach(md -> {
md.setBody(body);
md.getParameters().get(0).setType(messageDataEventClassName);
});
template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("acceptedEvent")).forEach(md -> {
md.setBody(filterExpressionBody);
md.getParameters().get(0).setType(messageDataEventClassName);
});
} else {
template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("correlationPayload")).forEach(md -> {
md.setBody(body);
md.getParameters().get(0).setType(trigger.getDataType());
});
template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("acceptedPayload")).forEach(md -> {
md.setBody(filterExpressionBody);
md.getParameters().get(0).setType(trigger.getDataType());
});
}
template.addMember(new MethodDeclaration().setName("canStartInstance").setType(Boolean.class).setModifiers(Keyword.PROTECTED).setBody(new BlockStmt().addStatement(new ReturnStmt(new BooleanLiteralExpr(trigger.isStart())))));
// 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 (OPERATOR_CONNECTOR.equals(connector)) {
// add event filter
String eventFilterClass = (String) trigger.getContext("eventFilter");
if (eventFilterClass != null && !eventFilterClass.isEmpty()) {
AnnotationExpr controllerAnnotation = template.getAnnotationByName("Controller").get();
((NormalAnnotationExpr) controllerAnnotation).addPair("eventFilters", new NameExpr(eventFilterClass + ".class"));
}
}
template.getMembers().sort(new BodyDeclarationComparator());
ImportsOrganizer.organize(clazz);
return clazz.toString().replaceAll("\\$DataType\\$", trigger.getDataType()).replaceAll("\\$DataEventType\\$", messageDataEventClassName).replaceAll("\\$ProcessId\\$", processId + version).replaceAll("\\$GenControllerParam\\$", (String) trigger.getContext("generationAware", "true")).replaceAll("\\$ControllerParam\\$", "{" + Stream.of(namespaces.split(",")).filter(s -> !s.trim().isEmpty()).map(s -> "\"" + s.trim() + "\"").collect(Collectors.joining(",")) + "}");
}
Aggregations