Search in sources :

Example 16 with ProcessInstance

use of io.automatiko.engine.api.workflow.ProcessInstance in project automatiko-engine by automatiko-io.

the class DefaultWorkItemExecutionManager method success.

@SuppressWarnings("unchecked")
protected void success(String processId, String name, WorkItem workItem, WorkItemManager manager, Object value) {
    LOGGER.debug("Executing success callback after work item execution");
    Process<?> process = processData.get(processId);
    if (process == null) {
        LOGGER.error("Unable to find process with id {}, completion of service invocation aborted", processId);
        return;
    }
    IdentityProvider.set(new TrustedIdentityProvider("System<async>"));
    UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
        String id = StringUtils.isEmpty(workItem.getParentProcessInstanceId()) ? workItem.getProcessInstanceId() : workItem.getParentProcessInstanceId() + ":" + workItem.getProcessInstanceId();
        Optional<ProcessInstance<?>> instance = (Optional<ProcessInstance<?>>) process.instances().findById(id);
        if (instance.isPresent()) {
            instance.get().completeWorkItem(workItem.getId(), name == null ? null : Collections.singletonMap(name, value));
        }
        return null;
    });
}
Also used : Optional(java.util.Optional) TrustedIdentityProvider(io.automatiko.engine.api.auth.TrustedIdentityProvider) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance)

Example 17 with ProcessInstance

use of io.automatiko.engine.api.workflow.ProcessInstance in project automatiko-engine by automatiko-io.

the class AbstractProcessInstance method populateChildProcesses.

@SuppressWarnings("unchecked")
protected void populateChildProcesses(Process<?> process, Collection<ProcessInstance<? extends Model>> collection, ProcessInstanceReadMode mode) {
    WorkflowProcessInstanceImpl instance = (WorkflowProcessInstanceImpl) processInstance();
    List<String> children = instance.getChildren().get(process.id());
    if (children != null && !children.isEmpty()) {
        for (String id : children) {
            process.instances().findById(id, mode).ifPresent(pi -> collection.add((ProcessInstance<? extends Model>) pi));
        }
    }
}
Also used : WorkflowProcessInstanceImpl(io.automatiko.engine.workflow.process.instance.impl.WorkflowProcessInstanceImpl) Model(io.automatiko.engine.api.Model) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) ArchivedProcessInstance(io.automatiko.engine.api.workflow.ArchivedProcessInstance) WorkflowProcessInstance(io.automatiko.engine.api.runtime.process.WorkflowProcessInstance)

Example 18 with ProcessInstance

use of io.automatiko.engine.api.workflow.ProcessInstance in project automatiko-engine by automatiko-io.

the class MapProcessInstances method findById.

@Override
public Optional<ProcessInstance> findById(String id, int status, ProcessInstanceReadMode mode) {
    String resolvedId = resolveId(id);
    ProcessInstance instance = instances.get(resolvedId);
    if (instance != null) {
        instance.process().accessPolicy().canReadInstance(IdentityProvider.get(), instance);
        if (instance.status() == status) {
            return Optional.ofNullable(instance);
        }
    }
    if (resolvedId.contains(":")) {
        if (instances.containsKey(resolvedId.split(":")[1])) {
            ProcessInstance pi = instances.get(resolvedId.split(":")[1]);
            if (pi.status() == status) {
                return Optional.of(pi);
            }
        }
    }
    return Optional.empty();
}
Also used : ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) ExportedProcessInstance(io.automatiko.engine.api.workflow.ExportedProcessInstance)

Example 19 with ProcessInstance

use of io.automatiko.engine.api.workflow.ProcessInstance in project automatiko-engine by automatiko-io.

the class $Type$Resource method create_$name$.

@APIResponses(value = { @APIResponse(responseCode = "400", description = "In case request given does not meet expectations", content = @Content(mediaType = "application/json")), @APIResponse(responseCode = "500", description = "In case of processing errors", content = @Content(mediaType = "application/json")), @APIResponse(responseCode = "409", description = "In case an instance already exists with given business key", content = @Content(mediaType = "application/json")), @APIResponse(responseCode = "403", description = "In case an instance cannot be created due to access policy by the caller", content = @Content(mediaType = "application/json")), @APIResponse(responseCode = "200", description = "Successfully created instance", content = @Content(mediaType = "application/json", schema = @Schema(implementation = $Type$Output.class))), @APIResponse(responseCode = "202", description = "Successfully accepted request to create instance (applies only to async execution mode)", content = @Content(mediaType = "application/json", schema = @Schema(implementation = $Type$Output.class))) })
@Operation(summary = "Creates new instance of $name$")
@POST()
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response create_$name$(@Context HttpHeaders httpHeaders, @QueryParam("businessKey") @Parameter(description = "Alternative id to be assigned to the instance", required = false) String businessKey, @Parameter(description = "User identifier as alternative autroization info", required = false, hidden = true) @QueryParam("user") final String user, @Parameter(description = "Groups as alternative autroization info", required = false, hidden = true) @QueryParam("group") final List<String> groups, @Parameter(description = "Indicates if instance metadata should be included", required = false) @QueryParam("metadata") @DefaultValue("false") final boolean metadata, @Parameter(description = "The input model for $name$ instance") $Type$Input resource) {
    if (resource == null) {
        resource = new $Type$Input();
    }
    final $Type$Input value = resource;
    String execMode = httpHeaders.getHeaderString("X-ATK-Mode");
    if ("async".equalsIgnoreCase(execMode)) {
        String callbackUrl = httpHeaders.getHeaderString("X-ATK-Callback");
        String startFromNode = httpHeaders.getHeaderString("X-ATK-StartFromNode");
        ProcessInstance<$Type$> pi = process.createInstance(businessKey, mapInput(value, new $Type$()));
        ((AbstractProcessInstance<$Type$>) pi).unlock(true);
        $Type$Output output = mapOutput(new $Type$Output(), pi.variables(), businessKey, pi.metadata());
        Map<String, String> headers = httpHeaders.getRequestHeaders().entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> e.getValue().get(0)));
        IdentityProvider identity = identitySupplier.buildIdentityProvider(user, groups);
        IdentityProvider.set(null);
        CompletableFuture.runAsync(() -> {
            IdentityProvider.set(identity);
            io.automatiko.engine.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
                if (startFromNode != null) {
                    pi.startFrom(startFromNode);
                } else {
                    pi.start();
                }
                tracing(pi);
                $Type$Output result = getModel(pi, metadata);
                io.automatiko.engine.workflow.http.HttpCallbacks.get().post(callbackUrl, result, httpAuth.produce(headers), pi.status());
                return null;
            });
        });
        ResponseBuilder builder = Response.accepted().entity(output);
        return builder.build();
    } else {
        identitySupplier.buildIdentityProvider(user, groups);
        return io.automatiko.engine.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
            ProcessInstance<$Type$> pi = process.createInstance(businessKey, mapInput(value, new $Type$()));
            String startFromNode = httpHeaders.getHeaderString("X-ATK-StartFromNode");
            if (startFromNode != null) {
                pi.startFrom(startFromNode);
            } else {
                pi.start();
            }
            tracing(pi);
            ResponseBuilder builder = Response.ok().entity(getModel(pi, metadata));
            return builder.build();
        });
    }
}
Also used : Produces(javax.ws.rs.Produces) SecurityPolicy(io.automatiko.engine.api.auth.SecurityPolicy) Path(javax.ws.rs.Path) WorkItemNotFoundException(io.automatiko.engine.api.runtime.process.WorkItemNotFoundException) TagInstance(io.automatiko.engine.workflow.base.instance.TagInstance) ProcessInstanceExecutionException(io.automatiko.engine.api.workflow.ProcessInstanceExecutionException) MediaType(javax.ws.rs.core.MediaType) Application(io.automatiko.engine.api.Application) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) ProcessImageNotFoundException(io.automatiko.engine.api.workflow.ProcessImageNotFoundException) SchemaType(org.eclipse.microprofile.openapi.annotations.enums.SchemaType) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) DELETE(javax.ws.rs.DELETE) Context(javax.ws.rs.core.Context) Collection(java.util.Collection) Tag(io.automatiko.engine.api.workflow.Tag) IdentityProvider(io.automatiko.engine.api.auth.IdentityProvider) StreamingOutput(javax.ws.rs.core.StreamingOutput) Operation(org.eclipse.microprofile.openapi.annotations.Operation) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) Policy(io.automatiko.engine.api.workflow.workitem.Policy) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) Sig(io.automatiko.engine.workflow.Sig) Parameter(org.eclipse.microprofile.openapi.annotations.parameters.Parameter) Entry(java.util.Map.Entry) WebApplicationException(javax.ws.rs.WebApplicationException) UriInfo(javax.ws.rs.core.UriInfo) ProcessInstanceNotFoundException(io.automatiko.engine.api.workflow.ProcessInstanceNotFoundException) WorkItem(io.automatiko.engine.api.workflow.WorkItem) PathParam(javax.ws.rs.PathParam) AbstractProcessInstance(io.automatiko.engine.workflow.AbstractProcessInstance) GET(javax.ws.rs.GET) CompletableFuture(java.util.concurrent.CompletableFuture) IdentitySupplier(io.automatiko.engine.api.auth.IdentitySupplier) InstanceMetadata(io.automatiko.engine.api.workflow.InstanceMetadata) Process(io.automatiko.engine.api.workflow.Process) Content(org.eclipse.microprofile.openapi.annotations.media.Content) Status(javax.ws.rs.core.Response.Status) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) OutputStream(java.io.OutputStream) POST(javax.ws.rs.POST) Schema(org.eclipse.microprofile.openapi.annotations.media.Schema) IOException(java.io.IOException) HttpAuthSupport(io.automatiko.engine.service.auth.HttpAuthSupport) APIResponses(org.eclipse.microprofile.openapi.annotations.responses.APIResponses) Collections(java.util.Collections) AbstractProcessInstance(io.automatiko.engine.workflow.AbstractProcessInstance) IdentityProvider(io.automatiko.engine.api.auth.IdentityProvider) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) APIResponses(org.eclipse.microprofile.openapi.annotations.responses.APIResponses) Operation(org.eclipse.microprofile.openapi.annotations.Operation)

Example 20 with ProcessInstance

use of io.automatiko.engine.api.workflow.ProcessInstance in project automatiko-engine by automatiko-io.

the class $Type$Resource method signal.

@APIResponses(value = { @APIResponse(responseCode = "500", description = "In case of processing errors", content = @Content(mediaType = "application/json")), @APIResponse(responseCode = "404", description = "In case of instance with given id was not found", content = @Content(mediaType = "application/json")), @APIResponse(responseCode = "200", description = "Successfully aborted instance of $taskName$ task with given id", content = @Content(mediaType = "application/json", schema = @Schema(implementation = $Type$Output.class))) })
@Operation(summary = "Signals '$signalName$' on instance with given id")
@POST
@Path("$prefix$/$name$/{id_$name$}/$signalPath$")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response signal(@Context HttpHeaders httpHeaders, @PathParam("id") String id, @PathParam("id_$name$") String id_$name$, @Parameter(description = "User identifier as alternative autroization info", required = false, hidden = true) @QueryParam("user") final String user, @Parameter(description = "Groups as alternative autroization info", required = false, hidden = true) @QueryParam("group") final List<String> groups, @Parameter(description = "Indicates if instance metadata should be included", required = false) @QueryParam("metadata") @DefaultValue("false") final boolean metadata, final $signalType$ data) {
    String execMode = httpHeaders.getHeaderString("X-ATK-Mode");
    if ("async".equalsIgnoreCase(execMode)) {
        String callbackUrl = httpHeaders.getHeaderString("X-ATK-Callback");
        Map<String, String> headers = httpHeaders.getRequestHeaders().entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> e.getValue().get(0)));
        IdentityProvider identity = identitySupplier.buildIdentityProvider(user, groups);
        IdentityProvider.set(null);
        CompletableFuture.runAsync(() -> {
            IdentityProvider.set(identity);
            io.automatiko.engine.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
                ProcessInstance<$Type$> pi = subprocess_$name$.instances().findById($parentprocessid$ + ":" + id_$name$).orElseThrow(() -> new ProcessInstanceNotFoundException(id));
                tracing(pi);
                pi.send(Sig.of("$signalName$", data));
                io.automatiko.engine.workflow.http.HttpCallbacks.get().post(callbackUrl, getSubModel_$name$(pi, metadata), httpAuth.produce(headers), pi.status());
                return null;
            });
        });
        ResponseBuilder builder = Response.accepted().entity(Collections.singletonMap("id", id));
        return builder.build();
    } else {
        identitySupplier.buildIdentityProvider(user, groups);
        return io.automatiko.engine.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
            ProcessInstance<$Type$> pi = subprocess_$name$.instances().findById($parentprocessid$ + ":" + id_$name$).orElseThrow(() -> new ProcessInstanceNotFoundException(id));
            tracing(pi);
            pi.send(Sig.of("$signalName$", data));
            ResponseBuilder builder = Response.ok().entity(getSubModel_$name$(pi, metadata));
            return builder.build();
        });
    }
}
Also used : List(java.util.List) Sig(io.automatiko.engine.workflow.Sig) Entry(java.util.Map.Entry) IdentityProvider(io.automatiko.engine.api.auth.IdentityProvider) CompletableFuture(java.util.concurrent.CompletableFuture) Process(io.automatiko.engine.api.workflow.Process) WorkItemNotFoundException(io.automatiko.engine.api.runtime.process.WorkItemNotFoundException) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) Collections(java.util.Collections) Collectors(java.util.stream.Collectors) IdentityProvider(io.automatiko.engine.api.auth.IdentityProvider)

Aggregations

ProcessInstance (io.automatiko.engine.api.workflow.ProcessInstance)63 Model (io.automatiko.engine.api.Model)29 Application (io.automatiko.engine.api.Application)26 HashMap (java.util.HashMap)23 Test (org.junit.jupiter.api.Test)23 AbstractProcessInstance (io.automatiko.engine.workflow.AbstractProcessInstance)22 AbstractCodegenTest (io.automatiko.engine.codegen.AbstractCodegenTest)21 ExportedProcessInstance (io.automatiko.engine.api.workflow.ExportedProcessInstance)16 List (java.util.List)15 WorkItem (io.automatiko.engine.api.workflow.WorkItem)14 Process (io.automatiko.engine.api.workflow.Process)13 Optional (java.util.Optional)13 Map (java.util.Map)12 IdentityProvider (io.automatiko.engine.api.auth.IdentityProvider)10 Collections (java.util.Collections)10 ProcessInstanceDuplicatedException (io.automatiko.engine.api.workflow.ProcessInstanceDuplicatedException)9 ArrayList (java.util.ArrayList)9 Collection (java.util.Collection)9 Collectors (java.util.stream.Collectors)9 WorkflowProcessInstance (io.automatiko.engine.api.runtime.process.WorkflowProcessInstance)8