use of com.github.javaparser.ast.expr.LambdaExpr in project kogito-runtimes by kiegroup.
the class LambdaSubProcessNodeVisitor method bind.
private BlockStmt bind(VariableScope variableScope, SubProcessNode subProcessNode, ModelMetaData subProcessModel) {
BlockStmt actionBody = new BlockStmt();
actionBody.addStatement(subProcessModel.newInstance("model"));
// process the inputs of the task
ClassOrInterfaceType nodeInstanceType = new ClassOrInterfaceType(null, NodeInstanceImpl.class.getCanonicalName());
ClassOrInterfaceType objectType = new ClassOrInterfaceType(null, Object.class.getCanonicalName());
ClassOrInterfaceType stringType = new ClassOrInterfaceType(null, String.class.getCanonicalName());
ClassOrInterfaceType type = new ClassOrInterfaceType(null, Map.class.getCanonicalName()).setTypeArguments(nodeList(stringType, objectType));
VariableDeclarationExpr expr = new VariableDeclarationExpr(type, "inputs");
BlockStmt lambdaBody = new BlockStmt();
MethodCallExpr getVariableExpr = new MethodCallExpr(new NameExpr(KCONTEXT_VAR), "getVariable").addArgument(new NameExpr("name"));
Expression getNodeInstance = new CastExpr(nodeInstanceType, new MethodCallExpr(new NameExpr(KCONTEXT_VAR), "getNodeInstance"));
lambdaBody.addStatement(new ReturnStmt(getVariableExpr));
Parameter varName = new Parameter(stringType, "name");
LambdaExpr sourceResolverExpr = new LambdaExpr(nodeList(varName), lambdaBody);
MethodCallExpr processInputsExpr = new MethodCallExpr(null, "org.jbpm.workflow.core.impl.NodeIoHelper.processInputs", nodeList(getNodeInstance, sourceResolverExpr));
AssignExpr inputs = new AssignExpr(expr, processInputsExpr, AssignExpr.Operator.ASSIGN);
actionBody.addStatement(inputs);
// do the actual assignments
for (DataDefinition inputDefinition : subProcessNode.getIoSpecification().getDataInput().values()) {
// remove multiinstance data. It does not belong to this model it is just for calculations with
// data associations
String collectionInput = (String) subProcessNode.getMetaData().get("MICollectionInput");
if (collectionInput != null && collectionInput.equals(inputDefinition.getLabel())) {
continue;
}
DataDefinition multiInstance = subProcessNode.getMultiInstanceSpecification().getInputDataItem();
if (multiInstance != null && multiInstance.getLabel().equals(inputDefinition.getLabel())) {
continue;
}
Expression getValueExpr = new MethodCallExpr(new NameExpr("inputs"), "get", nodeList(new StringLiteralExpr(inputDefinition.getLabel())));
actionBody.addStatement(subProcessModel.callSetter("model", inputDefinition.getLabel(), getValueExpr));
}
actionBody.addStatement(new ReturnStmt(new NameExpr("model")));
return actionBody;
}
use of com.github.javaparser.ast.expr.LambdaExpr in project kogito-runtimes by kiegroup.
the class LambdaSubProcessNodeVisitor method unbind.
private BlockStmt unbind(VariableScope variableScope, SubProcessNode subProcessNode) {
BlockStmt actionBody = new BlockStmt();
// process the outputs of the task
ClassOrInterfaceType nodeInstanceType = new ClassOrInterfaceType(null, NodeInstanceImpl.class.getCanonicalName());
ClassOrInterfaceType objectType = new ClassOrInterfaceType(null, Object.class.getCanonicalName());
ClassOrInterfaceType stringType = new ClassOrInterfaceType(null, String.class.getCanonicalName());
ClassOrInterfaceType type = new ClassOrInterfaceType(null, Map.class.getCanonicalName()).setTypeArguments(nodeList(stringType, objectType));
ClassOrInterfaceType hashMapType = new ClassOrInterfaceType(null, HashMap.class.getCanonicalName()).setTypeArguments(nodeList(stringType, objectType));
// we get the outputs from model
VariableDeclarationExpr expr = new VariableDeclarationExpr(type, "outputs");
actionBody.addStatement(new AssignExpr(expr, new ObjectCreationExpr(null, hashMapType, nodeList()), AssignExpr.Operator.ASSIGN));
// do the actual assignments
for (DataDefinition outputDefinition : subProcessNode.getIoSpecification().getDataOutput().values()) {
// remove multiinstance data. It does not belong to this model it is just for calculations with
// data associations
String collectionOutput = (String) subProcessNode.getMetaData().get("MICollectionOutput");
if (collectionOutput != null && collectionOutput.equals(outputDefinition.getLabel())) {
continue;
}
DataDefinition multiInstance = subProcessNode.getMultiInstanceSpecification().getOutputDataItem();
if (multiInstance != null && multiInstance.getLabel().equals(outputDefinition.getLabel())) {
continue;
}
Expression getValueExpr = new MethodCallExpr(new NameExpr("model"), "get" + ucFirst(outputDefinition.getLabel()));
Expression setValueExpr = new MethodCallExpr(new NameExpr("outputs"), "put", nodeList(new StringLiteralExpr(outputDefinition.getLabel()), getValueExpr));
actionBody.addStatement(setValueExpr);
}
// source resolver
BlockStmt lambdaSourceBody = new BlockStmt();
Expression getSourceVariableExpr = new MethodCallExpr(new NameExpr("outputs"), "get", nodeList(new NameExpr("name")));
lambdaSourceBody.addStatement(new ReturnStmt(getSourceVariableExpr));
LambdaExpr sourceResolverExpr = new LambdaExpr(nodeList(new Parameter(stringType, "name")), lambdaSourceBody);
// target resolver
BlockStmt lambdaTargetBody = new BlockStmt();
Expression getTargetVariableExpr = new MethodCallExpr(new NameExpr(KCONTEXT_VAR), "getVariable").addArgument(new NameExpr("name"));
lambdaTargetBody.addStatement(new ReturnStmt(getTargetVariableExpr));
LambdaExpr targetResolverExpr = new LambdaExpr(nodeList(new Parameter(stringType, "name")), lambdaTargetBody);
Expression getNodeInstance = new CastExpr(nodeInstanceType, new MethodCallExpr(new NameExpr(KCONTEXT_VAR), "getNodeInstance"));
MethodCallExpr processOutputsExpr = new MethodCallExpr(null, "org.jbpm.workflow.core.impl.NodeIoHelper.processOutputs", nodeList(getNodeInstance, sourceResolverExpr, targetResolverExpr));
actionBody.addStatement(processOutputsExpr);
return actionBody;
}
use of com.github.javaparser.ast.expr.LambdaExpr in project kogito-runtimes by kiegroup.
the class EndNodeVisitor method visitNode.
@Override
public void visitNode(String factoryField, EndNode node, BlockStmt body, VariableScope variableScope, ProcessMetaData metadata) {
body.addStatement(getAssignedFactoryMethod(factoryField, EndNodeFactory.class, getNodeId(node), getNodeKey(), new LongLiteralExpr(node.getId()))).addStatement(getNameMethod(node, "End")).addStatement(getFactoryMethod(getNodeId(node), METHOD_TERMINATE, new BooleanLiteralExpr(node.isTerminate())));
// if there is trigger defined on end event create TriggerMetaData for it
Optional<ProcessInstanceCompensationAction> compensationAction = getAction(node, ProcessInstanceCompensationAction.class);
Optional<ExpressionSupplier> supplier = getAction(node, ExpressionSupplier.class);
if (compensationAction.isPresent()) {
String compensateNode = CompensationScope.IMPLICIT_COMPENSATION_PREFIX + metadata.getProcessId();
if (compensationAction.get().getActivityRef() != null) {
compensateNode = compensationAction.get().getActivityRef();
}
LambdaExpr lambda = buildCompensationLambdaExpr(compensateNode);
body.addStatement(getFactoryMethod(getNodeId(node), ActionNodeFactory.METHOD_ACTION, lambda));
} else if (supplier.isPresent()) {
body.addStatement(getFactoryMethod(getNodeId(node), ActionNodeFactory.METHOD_ACTION, supplier.get().get(node, metadata)));
} else if (node.getMetaData(TRIGGER_REF) != null) {
body.addStatement(getFactoryMethod(getNodeId(node), METHOD_ACTION, buildProducerAction(node, metadata)));
} else if (node.getMetaData(REF) != null && EVENT_TYPE_SIGNAL.equals(node.getMetaData(EVENT_TYPE))) {
body.addStatement(getFactoryMethod(getNodeId(node), METHOD_ACTION, buildAction((String) node.getMetaData(REF), (String) node.getMetaData(VARIABLE), (String) node.getMetaData(MAPPING_VARIABLE_INPUT), (String) node.getMetaData(CUSTOM_SCOPE))));
}
addNodeMappings(node, body, getNodeId(node));
visitMetaData(node.getMetaData(), body, getNodeId(node));
body.addStatement(getDoneMethod(getNodeId(node)));
}
use of com.github.javaparser.ast.expr.LambdaExpr in project kogito-runtimes by kiegroup.
the class DescriptorRestOperationHandler method addOpenApiParameters.
private <T extends RuleFlowNodeContainerFactory<T, ?>> WorkItemNodeFactory<T> addOpenApiParameters(WorkItemNodeFactory<T> node, Workflow workflow, FunctionDefinition function) {
URI uri = operationId.getUri();
String serviceName = operationId.getPackageName();
try {
// although OpenAPIParser has built in support to load uri, it messes up when using contextclassloader, so using our retrieval apis to get the content
SwaggerParseResult result = new OpenAPIParser().readContents(new String(readAllBytes(buildLoader(uri, parserContext.getContext().getClassLoader(), workflow, function.getAuthRef()))), null, null);
OpenAPI openAPI = result.getOpenAPI();
if (openAPI == null) {
throw new IllegalArgumentException("Problem parsing uri " + uri);
}
logger.debug("OpenAPI parser messages {}", result.getMessages());
OpenAPIDescriptor openAPIDescriptor = OpenAPIDescriptorFactory.of(openAPI, operationId.getOperation());
addSecurity(node, openAPIDescriptor, serviceName);
return node.workParameter(RestWorkItemHandler.URL, runtimeOpenApi(serviceName, "base_path", String.class, OpenAPIDescriptorFactory.getDefaultURL(openAPI, "http://localhost:8080"), (key, clazz, defaultValue) -> new ConfigSuppliedWorkItemSupplier<>(key, clazz, defaultValue, calculatedKey -> concatPaths(calculatedKey, openAPIDescriptor.getPath()), new LambdaExpr(new Parameter(new UnknownType(), "calculatedKey"), new MethodCallExpr(ConversionUtils.class.getCanonicalName() + ".concatPaths").addArgument(new NameExpr("calculatedKey")).addArgument(new StringLiteralExpr(openAPIDescriptor.getPath())))))).workParameter(RestWorkItemHandler.METHOD, openAPIDescriptor.getMethod()).workParameter(RestWorkItemHandler.PARAMS_DECORATOR, new CollectionParamsDecoratorSupplier(openAPIDescriptor.getHeaderParams(), openAPIDescriptor.getQueryParams()));
} catch (IOException e) {
throw new IllegalArgumentException("Problem retrieving uri " + uri);
}
}
use of com.github.javaparser.ast.expr.LambdaExpr in project automatiko-engine by automatiko-io.
the class ProcessVisitor method visitProcess.
public void visitProcess(WorkflowProcess process, MethodDeclaration processMethod, ProcessMetaData metadata, String workflowType) {
BlockStmt body = new BlockStmt();
String expiresAfter = (String) process.getMetaData().get("expiresAfter");
if (expiresAfter != null) {
if (!DateTimeUtils.isPeriod(expiresAfter)) {
throw new IllegalArgumentException("ExpiresAfter custom attribute is not a valid ISO period format - '" + expiresAfter + "'");
}
DateTimeUtils.parseDuration(expiresAfter);
}
ClassOrInterfaceType processFactoryType = new ClassOrInterfaceType(null, ExecutableProcessFactory.class.getSimpleName());
boolean serverless = ProcessToExecModelGenerator.isServerlessWorkflow(process);
// create local variable factory and assign new fluent process to it
VariableDeclarationExpr factoryField = new VariableDeclarationExpr(processFactoryType, FACTORY_FIELD_NAME);
MethodCallExpr assignFactoryMethod = new MethodCallExpr(new NameExpr(processFactoryType.getName().asString()), "createProcess");
assignFactoryMethod.addArgument(new StringLiteralExpr(process.getId())).addArgument(new StringLiteralExpr(workflowType)).addArgument(new BooleanLiteralExpr(serverless));
body.addStatement(new AssignExpr(factoryField, assignFactoryMethod, AssignExpr.Operator.ASSIGN));
// item definitions
Set<String> visitedVariables = new HashSet<>();
VariableScope variableScope = (VariableScope) ((io.automatiko.engine.workflow.base.core.Process) process).getDefaultContext(VariableScope.VARIABLE_SCOPE);
visitVariableScope(variableScope, body, visitedVariables);
visitSubVariableScopes(process.getNodes(), body, visitedVariables);
Collection<TagDefinition> tagDefinitions = ((io.automatiko.engine.workflow.process.core.WorkflowProcess) process).getTagDefinitions();
if (tagDefinitions != null) {
for (TagDefinition tag : tagDefinitions) {
if (tag instanceof FunctionTagDefinition) {
String expression = tag.getExpression();
Matcher matcher = PatternConstants.PARAMETER_MATCHER.matcher(expression);
if (matcher.find()) {
expression = matcher.group(1);
}
BlockStmt actionBody = new BlockStmt();
if (serverless) {
MethodCallExpr evaluate = new MethodCallExpr(null, "expressionAsString").addArgument(new NameExpr("context")).addArgument(new NameExpr("exp"));
actionBody.addStatement(new ReturnStmt(evaluate));
} else {
List<Variable> variables = variableScope.getVariables();
variables.stream().filter(v -> tag.getExpression().contains(v.getName())).map(ActionNodeVisitor::makeAssignment).forEach(actionBody::addStatement);
actionBody.addStatement(new ReturnStmt(new NameExpr(expression)));
}
LambdaExpr lambda = new LambdaExpr(NodeList.nodeList(new Parameter(new UnknownType(), "exp"), new Parameter(new UnknownType(), "context")), actionBody);
body.addStatement(getFactoryMethod(FACTORY_FIELD_NAME, "tag", new StringLiteralExpr(tag.getId()), new StringLiteralExpr().setString(tag.getExpression()), lambda));
} else {
body.addStatement(getFactoryMethod(FACTORY_FIELD_NAME, "tag", new StringLiteralExpr(tag.getId()), new StringLiteralExpr(tag.getExpression()), new NullLiteralExpr()));
}
}
if (((io.automatiko.engine.workflow.process.core.WorkflowProcess) process).getImports() != null && !((io.automatiko.engine.workflow.process.core.WorkflowProcess) process).getImports().isEmpty()) {
NodeList<Expression> items = NodeList.nodeList(((io.automatiko.engine.workflow.process.core.WorkflowProcess) process).getImports().stream().map(s -> new StringLiteralExpr(s)).collect(Collectors.toList()));
body.addStatement(getFactoryMethod(FACTORY_FIELD_NAME, "imports", items.toArray(Expression[]::new)));
}
}
metadata.setDynamic(((io.automatiko.engine.workflow.process.core.WorkflowProcess) process).isDynamic());
// the process itself
body.addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_NAME, new StringLiteralExpr(process.getName()))).addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_PACKAGE_NAME, new StringLiteralExpr(process.getPackageName()))).addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_DYNAMIC, new BooleanLiteralExpr(metadata.isDynamic()))).addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_VERSION, new StringLiteralExpr(getOrDefault(process.getVersion(), DEFAULT_VERSION)))).addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_VISIBILITY, new StringLiteralExpr(getOrDefault(process.getVisibility(), WorkflowProcess.PUBLIC_VISIBILITY))));
visitMetaData(process.getMetaData(), body, FACTORY_FIELD_NAME);
visitHeader(process, body);
List<Node> processNodes = new ArrayList<>();
for (io.automatiko.engine.api.definition.process.Node procNode : process.getNodes()) {
processNodes.add((io.automatiko.engine.workflow.process.core.Node) procNode);
}
visitNodes(process, processNodes, body, variableScope, metadata);
visitConnections(process.getNodes(), body);
String timeout = (String) process.getMetaData().get("timeout");
if (timeout != null) {
String extraNodeIds = (String) process.getMetaData().get("timeoutNodes");
if (extraNodeIds != null) {
List<Expression> arguments = new ArrayList<>();
arguments.add(new IntegerLiteralExpr(process.getNodes().length));
arguments.add(new StringLiteralExpr(timeout));
arguments.addAll(Stream.of(extraNodeIds.split(",")).map(s -> new LongLiteralExpr(s)).collect(Collectors.toList()));
body.addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_EXEC_TIMEOUT, arguments.toArray(Expression[]::new)));
} else {
body.addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_EXEC_TIMEOUT, new IntegerLiteralExpr(process.getNodes().length), new StringLiteralExpr(timeout)));
}
}
body.addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_VALIDATE));
MethodCallExpr getProcessMethod = new MethodCallExpr(new NameExpr(FACTORY_FIELD_NAME), "getProcess");
body.addStatement(new ReturnStmt(getProcessMethod));
processMethod.setBody(body);
}
Aggregations