Search in sources :

Example 1 with Policy

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

the class BaseHumanTaskLifeCycle method transitionTo.

@Override
public Map<String, Object> transitionTo(WorkItem workItem, WorkItemManager manager, Transition<Map<String, Object>> transition) {
    logger.debug("Transition method invoked for work item {} to transition to {}, currently in phase {} and status {}", workItem.getId(), transition.phase(), workItem.getPhaseId(), workItem.getPhaseStatus());
    HumanTaskWorkItemImpl humanTaskWorkItem = (HumanTaskWorkItemImpl) workItem;
    LifeCyclePhase targetPhase = phases.get(transition.phase());
    if (targetPhase == null) {
        logger.debug("Target life cycle phase '{}' does not exist in {}", transition.phase(), this.getClass().getSimpleName());
        throw new InvalidLifeCyclePhaseException(transition.phase());
    }
    LifeCyclePhase currentPhase = phases.get(humanTaskWorkItem.getPhaseId());
    if (!targetPhase.canTransition(currentPhase)) {
        logger.debug("Target life cycle phase '{}' cannot transition from current state '{}'", targetPhase.id(), currentPhase.id());
        throw new InvalidTransitionException("Cannot transition from " + humanTaskWorkItem.getPhaseId() + " to " + targetPhase.id());
    }
    if (!targetPhase.id().equals(Active.ID) && !targetPhase.id().equals(Abort.ID) && !humanTaskWorkItem.enforce(transition.policies().toArray(new Policy[transition.policies().size()]))) {
        throw new NotAuthorizedException("User is not authorized to access task instance with id " + humanTaskWorkItem.getId());
    }
    humanTaskWorkItem.setPhaseId(targetPhase.id());
    humanTaskWorkItem.setPhaseStatus(targetPhase.status());
    targetPhase.apply(humanTaskWorkItem, transition);
    if (transition.data() != null) {
        logger.debug("Updating data for work item {}", targetPhase.id(), humanTaskWorkItem.getId());
        humanTaskWorkItem.getResults().putAll(transition.data());
    }
    logger.debug("Transition for work item {} to {} done, currently in phase {} and status {}", workItem.getId(), transition.phase(), workItem.getPhaseId(), workItem.getPhaseStatus());
    if (targetPhase.isCompleting()) {
        logger.debug("Target life cycle phase '{}' is completing, completing work item {}", targetPhase.id(), humanTaskWorkItem.getId());
        // since target life cycle phase is terminating completing work item
        ((DefaultWorkItemManager) manager).internalCompleteWorkItem(humanTaskWorkItem);
    } else if (targetPhase.isTerminating()) {
        logger.debug("Target life cycle phase '{}' is terminating, aborting work item {}", targetPhase.id(), humanTaskWorkItem.getId());
        ((DefaultWorkItemManager) manager).internalAbortWorkItem(humanTaskWorkItem);
    }
    return data(humanTaskWorkItem);
}
Also used : InvalidTransitionException(io.automatiko.engine.api.workflow.workitem.InvalidTransitionException) Policy(io.automatiko.engine.api.workflow.workitem.Policy) DefaultWorkItemManager(io.automatiko.engine.workflow.base.instance.impl.workitem.DefaultWorkItemManager) InvalidLifeCyclePhaseException(io.automatiko.engine.api.workflow.workitem.InvalidLifeCyclePhaseException) NotAuthorizedException(io.automatiko.engine.api.workflow.workitem.NotAuthorizedException) LifeCyclePhase(io.automatiko.engine.api.workflow.workitem.LifeCyclePhase)

Example 2 with Policy

use of io.automatiko.engine.api.workflow.workitem.Policy 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)

Aggregations

Policy (io.automatiko.engine.api.workflow.workitem.Policy)2 Application (io.automatiko.engine.api.Application)1 IdentityProvider (io.automatiko.engine.api.auth.IdentityProvider)1 IdentitySupplier (io.automatiko.engine.api.auth.IdentitySupplier)1 SecurityPolicy (io.automatiko.engine.api.auth.SecurityPolicy)1 WorkItemNotFoundException (io.automatiko.engine.api.runtime.process.WorkItemNotFoundException)1 InstanceMetadata (io.automatiko.engine.api.workflow.InstanceMetadata)1 Process (io.automatiko.engine.api.workflow.Process)1 ProcessImageNotFoundException (io.automatiko.engine.api.workflow.ProcessImageNotFoundException)1 ProcessInstance (io.automatiko.engine.api.workflow.ProcessInstance)1 ProcessInstanceExecutionException (io.automatiko.engine.api.workflow.ProcessInstanceExecutionException)1 ProcessInstanceNotFoundException (io.automatiko.engine.api.workflow.ProcessInstanceNotFoundException)1 Tag (io.automatiko.engine.api.workflow.Tag)1 WorkItem (io.automatiko.engine.api.workflow.WorkItem)1 InvalidLifeCyclePhaseException (io.automatiko.engine.api.workflow.workitem.InvalidLifeCyclePhaseException)1 InvalidTransitionException (io.automatiko.engine.api.workflow.workitem.InvalidTransitionException)1 LifeCyclePhase (io.automatiko.engine.api.workflow.workitem.LifeCyclePhase)1 NotAuthorizedException (io.automatiko.engine.api.workflow.workitem.NotAuthorizedException)1 HttpAuthSupport (io.automatiko.engine.service.auth.HttpAuthSupport)1 AbstractProcessInstance (io.automatiko.engine.workflow.AbstractProcessInstance)1