Search in sources :

Example 6 with IdentityProvider

use of io.automatiko.engine.api.auth.IdentityProvider 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)

Example 7 with IdentityProvider

use of io.automatiko.engine.api.auth.IdentityProvider in project automatiko-engine by automatiko-io.

the class WorkflowThreadContextProvider method currentContext.

@Override
public ThreadContextSnapshot currentContext(Map<String, String> props) {
    UnitOfWork capturedUnitOfWork = DefaultUnitOfWorkManager.getUnitOfWork();
    IdentityProvider capturedIdentity = IdentityProvider.isSet() ? IdentityProvider.get() : null;
    return () -> {
        UnitOfWork currentUnitOfWork = DefaultUnitOfWorkManager.getUnitOfWork();
        IdentityProvider currentIdentity = IdentityProvider.isSet() ? IdentityProvider.get() : null;
        if (currentUnitOfWork != capturedUnitOfWork) {
            DefaultUnitOfWorkManager.setUnitOfWork(capturedUnitOfWork);
        }
        if (currentIdentity != capturedIdentity) {
            IdentityProvider.set(capturedIdentity);
        }
        return () -> {
            DefaultUnitOfWorkManager.setUnitOfWork(currentUnitOfWork);
            IdentityProvider.set(currentIdentity);
        };
    };
}
Also used : UnitOfWork(io.automatiko.engine.api.uow.UnitOfWork) IdentityProvider(io.automatiko.engine.api.auth.IdentityProvider)

Example 8 with IdentityProvider

use of io.automatiko.engine.api.auth.IdentityProvider in project automatiko-engine by automatiko-io.

the class WorkflowProcessInstanceImpl method setState.

@Override
public void setState(final int state, String outcome) {
    // TODO move most of this to ProcessInstanceImpl
    if (state == ProcessInstance.STATE_COMPLETED || state == ProcessInstance.STATE_ABORTED) {
        this.endDate = new Date();
        if (this.slaCompliance == SLA_PENDING) {
            if (System.currentTimeMillis() > slaDueDate.getTime()) {
                // completion of the process instance is after expected SLA due date, mark it
                // accordingly
                this.slaCompliance = SLA_VIOLATED;
            } else {
                this.slaCompliance = state == ProcessInstance.STATE_COMPLETED ? SLA_MET : SLA_ABORTED;
            }
        }
        InternalProcessRuntime processRuntime = getProcessRuntime();
        processRuntime.getProcessEventSupport().fireBeforeProcessCompleted(this, processRuntime);
        // JBPM-8094 - set state after event
        super.setState(state, outcome);
        // deactivate all node instances of this process instance
        while (!nodeInstances.isEmpty()) {
            NodeInstance nodeInstance = nodeInstances.get(0);
            nodeInstance.cancel();
        }
        if (this.slaTimerId != null && !slaTimerId.trim().isEmpty()) {
            processRuntime.getJobsService().cancelJob(this.slaTimerId);
            logger.debug("SLA Timer {} has been canceled", this.slaTimerId);
        }
        removeEventListeners();
        processRuntime.getProcessInstanceManager().removeProcessInstance(this);
        processRuntime.getProcessEventSupport().fireAfterProcessCompleted(this, processRuntime);
        if (isSignalCompletion()) {
            IdentityProvider identity = IdentityProvider.get();
            try {
                // make sure that identity is switched to trusted one as whoever executed this instance
                // might not have access to parent process instance
                IdentityProvider.set(new TrustedIdentityProvider("system"));
                List<EventListener> listeners = eventListeners.get("processInstanceCompleted:" + getId());
                if (listeners != null) {
                    for (EventListener listener : listeners) {
                        listener.signalEvent("processInstanceCompleted:" + getId(), this);
                    }
                }
                processRuntime.getSignalManager().signalEvent("processInstanceCompleted:" + getId(), this);
            } finally {
                IdentityProvider.set(identity);
            }
        }
    } else {
        super.setState(state, outcome);
    }
}
Also used : TrustedIdentityProvider(io.automatiko.engine.api.auth.TrustedIdentityProvider) InternalProcessRuntime(io.automatiko.engine.workflow.base.instance.InternalProcessRuntime) IdentityProvider(io.automatiko.engine.api.auth.IdentityProvider) TrustedIdentityProvider(io.automatiko.engine.api.auth.TrustedIdentityProvider) EventListener(io.automatiko.engine.api.runtime.process.EventListener) EventSubProcessNodeInstance(io.automatiko.engine.workflow.process.instance.node.EventSubProcessNodeInstance) NodeInstance(io.automatiko.engine.workflow.process.instance.NodeInstance) FaultNodeInstance(io.automatiko.engine.workflow.process.instance.node.FaultNodeInstance) CompositeNodeInstance(io.automatiko.engine.workflow.process.instance.node.CompositeNodeInstance) StateBasedNodeInstance(io.automatiko.engine.workflow.process.instance.node.StateBasedNodeInstance) StartNodeInstance(io.automatiko.engine.workflow.process.instance.node.StartNodeInstance) EndNodeInstance(io.automatiko.engine.workflow.process.instance.node.EndNodeInstance) EventNodeInstance(io.automatiko.engine.workflow.process.instance.node.EventNodeInstance) Date(java.util.Date)

Example 9 with IdentityProvider

use of io.automatiko.engine.api.auth.IdentityProvider in project automatiko-engine by automatiko-io.

the class $Type$Resource method completeTask.

@APIResponses(value = { @APIResponse(responseCode = "500", description = "In case of processing errors", content = @Content(mediaType = "application/json")), @APIResponse(responseCode = "404", description = "In case of task instance with given id was not found", content = @Content(mediaType = "application/json")), @APIResponse(responseCode = "200", description = "Successfully completed instance of $taskName$ task with given id", content = @Content(mediaType = "application/json", schema = @Schema(implementation = $Type$Output.class))) })
@Operation(summary = "Completes $taskName$ task instance with given id")
@POST()
@Path("$prefix$/$name$/{id_$name$}/$taskName$/{workItemId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response completeTask(@Context HttpHeaders httpHeaders, @PathParam("id") String id, @PathParam("id_$name$") String id_$name$, @PathParam("workItemId") final String workItemId, @QueryParam("phase") @DefaultValue("complete") final String phase, @QueryParam("user") final String user, @QueryParam("group") final List<String> groups, @QueryParam("metadata") @DefaultValue("false") final boolean metadata, final $TaskOutput$ model) {
    try {
        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(), () -> {
                    String combinedId;
                    if (id_$name$.contains(":")) {
                        combinedId = id_$name$;
                    } else {
                        combinedId = $parentprocessid$ + ":" + id_$name$;
                    }
                    ProcessInstance<$Type$> pi = subprocess_$name$.instances().findById(combinedId).orElseThrow(() -> new ProcessInstanceNotFoundException(id));
                    tracing(pi);
                    io.automatiko.engine.workflow.base.instance.impl.humantask.HumanTaskTransition transition = new io.automatiko.engine.workflow.base.instance.impl.humantask.HumanTaskTransition(phase, model.toMap(), io.automatiko.engine.api.auth.IdentityProvider.get());
                    pi.transitionWorkItem(workItemId, transition);
                    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(), () -> {
                String combinedId;
                if (id_$name$.contains(":")) {
                    combinedId = id_$name$;
                } else {
                    combinedId = $parentprocessid$ + ":" + id_$name$;
                }
                ProcessInstance<$Type$> pi = subprocess_$name$.instances().findById(combinedId).orElseThrow(() -> new ProcessInstanceNotFoundException(id));
                tracing(pi);
                io.automatiko.engine.workflow.base.instance.impl.humantask.HumanTaskTransition transition = new io.automatiko.engine.workflow.base.instance.impl.humantask.HumanTaskTransition(phase, model.toMap(), io.automatiko.engine.api.auth.IdentityProvider.get());
                pi.transitionWorkItem(workItemId, transition);
                ResponseBuilder builder = Response.ok().entity(getSubModel_$name$(pi, metadata));
                return builder.build();
            });
        }
    } catch (WorkItemNotFoundException e) {
        return null;
    } finally {
        IdentityProvider.set(null);
    }
}
Also used : List(java.util.List) Sig(io.automatiko.engine.workflow.Sig) ProcessInstanceReadMode(io.automatiko.engine.api.workflow.ProcessInstanceReadMode) Entry(java.util.Map.Entry) IdentityProvider(io.automatiko.engine.api.auth.IdentityProvider) CompletableFuture(java.util.concurrent.CompletableFuture) WorkItemNotFoundException(io.automatiko.engine.api.runtime.process.WorkItemNotFoundException) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) Collections(java.util.Collections) Collectors(java.util.stream.Collectors) WorkItem(io.automatiko.engine.api.workflow.WorkItem) IdentityProvider(io.automatiko.engine.api.auth.IdentityProvider) WorkItemNotFoundException(io.automatiko.engine.api.runtime.process.WorkItemNotFoundException)

Example 10 with IdentityProvider

use of io.automatiko.engine.api.auth.IdentityProvider 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 task instance with given id was not found", content = @Content(mediaType = "application/json")), @APIResponse(responseCode = "200", description = "Successfully created new instance of $taskName$ task", content = @Content(mediaType = "application/json", schema = @Schema(implementation = $Type$Output.class))) })
@Operation(summary = "Adds new $taskName$ task instance")
@POST
@Path("$prefix$/$name$/{id_$name$}/$taskName$")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public javax.ws.rs.core.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) {
    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(), () -> {
                String combinedId;
                if (id_$name$.contains(":")) {
                    combinedId = id_$name$;
                } else {
                    combinedId = $parentprocessid$ + ":" + id_$name$;
                }
                ProcessInstance<$Type$> pi = subprocess_$name$.instances().findById(combinedId).orElseThrow(() -> new ProcessInstanceNotFoundException(id));
                tracing(pi);
                pi.send(Sig.of("$taskNodeName$", java.util.Collections.emptyMap()));
                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(), () -> {
            String combinedId;
            if (id_$name$.contains(":")) {
                combinedId = id_$name$;
            } else {
                combinedId = $parentprocessid$ + ":" + id_$name$;
            }
            ProcessInstance<$Type$> pi = subprocess_$name$.instances().findById(combinedId).orElseThrow(() -> new ProcessInstanceNotFoundException(id));
            tracing(pi);
            pi.send(Sig.of("$taskNodeName$", java.util.Collections.emptyMap()));
            java.util.Optional<WorkItem> task = pi.workItems().stream().filter(wi -> wi.getName().equals("$taskName$")).findFirst();
            if (task.isPresent()) {
                return javax.ws.rs.core.Response.ok(getSubModel_$name$(pi, metadata)).header("Link", "</" + id + "/$taskName$/" + task.get().getId() + ">; rel='instance'").build();
            }
            return javax.ws.rs.core.Response.status(javax.ws.rs.core.Response.Status.NOT_FOUND).build();
        });
    }
}
Also used : List(java.util.List) Sig(io.automatiko.engine.workflow.Sig) ProcessInstanceReadMode(io.automatiko.engine.api.workflow.ProcessInstanceReadMode) Entry(java.util.Map.Entry) IdentityProvider(io.automatiko.engine.api.auth.IdentityProvider) CompletableFuture(java.util.concurrent.CompletableFuture) WorkItemNotFoundException(io.automatiko.engine.api.runtime.process.WorkItemNotFoundException) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) Collections(java.util.Collections) Collectors(java.util.stream.Collectors) WorkItem(io.automatiko.engine.api.workflow.WorkItem) IdentityProvider(io.automatiko.engine.api.auth.IdentityProvider) WorkItem(io.automatiko.engine.api.workflow.WorkItem)

Aggregations

IdentityProvider (io.automatiko.engine.api.auth.IdentityProvider)15 ProcessInstance (io.automatiko.engine.api.workflow.ProcessInstance)8 List (java.util.List)8 WorkItemNotFoundException (io.automatiko.engine.api.runtime.process.WorkItemNotFoundException)7 WorkItem (io.automatiko.engine.api.workflow.WorkItem)7 Sig (io.automatiko.engine.workflow.Sig)6 Collections (java.util.Collections)6 Entry (java.util.Map.Entry)6 CompletableFuture (java.util.concurrent.CompletableFuture)6 Collectors (java.util.stream.Collectors)6 SecurityPolicy (io.automatiko.engine.api.auth.SecurityPolicy)4 Application (io.automatiko.engine.api.Application)3 HumanTaskWorkItem (io.automatiko.engine.api.runtime.process.HumanTaskWorkItem)3 Process (io.automatiko.engine.api.workflow.Process)3 ProcessInstanceReadMode (io.automatiko.engine.api.workflow.ProcessInstanceReadMode)3 GET (javax.ws.rs.GET)3 Path (javax.ws.rs.Path)3 InstanceMetadata (io.automatiko.engine.api.workflow.InstanceMetadata)2 ProcessImageNotFoundException (io.automatiko.engine.api.workflow.ProcessImageNotFoundException)2 ProcessInstanceExecutionException (io.automatiko.engine.api.workflow.ProcessInstanceExecutionException)2