Search in sources :

Example 6 with TrustedIdentityProvider

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

the class TestJobService method triggerProcessJob.

@SuppressWarnings({ "unchecked", "rawtypes" })
public void triggerProcessJob(String jobId) {
    ProcessJobDescription job = (ProcessJobDescription) jobs.remove(jobId);
    if (job == null) {
        throw new IllegalArgumentException("Job with id " + jobId + " not found");
    }
    int limit = job.expirationTime().repeatLimit();
    try {
        LOGGER.debug("Job {} started", job.id());
        Process process = mappedProcesses.get(job.processId());
        if (process == null) {
            LOGGER.warn("No process found for process id {}", job.processId());
            return;
        }
        IdentityProvider.set(new TrustedIdentityProvider("System<timer>"));
        UnitOfWorkExecutor.executeInUnitOfWork(unitOfWorkManager, () -> {
            ProcessInstance<?> pi = process.createInstance(process.createModel());
            if (pi != null) {
                pi.start(TRIGGER, null, null);
            }
            return null;
        });
        limit--;
        if (limit == 0) {
            jobs.remove(jobId);
        }
        LOGGER.debug("Job {} completed", job.id());
    } finally {
        if (job.expirationTime().next() != null) {
            jobs.remove(jobId);
            scheduleProcessJob(job);
        } else {
            jobs.remove(jobId);
        }
    }
}
Also used : TrustedIdentityProvider(io.automatiko.engine.api.auth.TrustedIdentityProvider) Process(io.automatiko.engine.api.workflow.Process) ProcessJobDescription(io.automatiko.engine.api.jobs.ProcessJobDescription)

Example 7 with TrustedIdentityProvider

use of io.automatiko.engine.api.auth.TrustedIdentityProvider 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 8 with TrustedIdentityProvider

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

the class $Type$MessageConsumer method consume.

public CompletionStage<Void> consume(Message<byte[]> msg) {
    final String trigger = "$Trigger$";
    try {
        IdentityProvider.set(new TrustedIdentityProvider("System<messaging>"));
        if (useCloudEvents.orElse(true)) {
            final $DataEventType$ eventData = json.readValue(msg.getPayload(), $DataEventType$.class);
            final $Type$ model = new $Type$();
            io.automatiko.engine.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
                String correlation = correlationEvent(eventData, msg);
                if (correlation != null) {
                    LOGGER.debug("Correlation ({}) is set, attempting to find if there is matching instance already active", correlation);
                    Optional possiblyFound = process.instances().findById(correlation);
                    if (possiblyFound.isPresent()) {
                        ProcessInstance pInstance = (ProcessInstance) possiblyFound.get();
                        LOGGER.debug("Found process instance {} matching correlation {}, signaling instead of starting new instance", pInstance.id(), correlation);
                        pInstance.send(Sig.of(trigger, eventData.getData()));
                        return null;
                    }
                }
                LOGGER.debug("Received message without reference id and no correlation is set/matched, staring new process instance with trigger '{}'", trigger);
                try {
                    ProcessInstance<$Type$> pi = process.createInstance(correlation, model);
                    pi.start(trigger, null, eventData.getData());
                } catch (ProcessInstanceDuplicatedException e) {
                    ProcessInstance<$Type$> pi = process.instances().findById(correlation).get();
                    pi.send(Sig.of(trigger, eventData.getData()));
                }
                return null;
            });
        } else {
            final $DataType$ eventData = json.readValue(msg.getPayload(), $DataType$.class);
            final $Type$ model = new $Type$();
            io.automatiko.engine.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
                String correlation = correlationPayload(eventData, msg);
                if (correlation != null) {
                    LOGGER.debug("Correlation ({}) is set, attempting to find if there is matching instance already active", correlation);
                    Optional possiblyFound = process.instances().findById(correlation);
                    if (possiblyFound.isPresent()) {
                        ProcessInstance pInstance = (ProcessInstance) possiblyFound.get();
                        LOGGER.debug("Found process instance {} matching correlation {}, signaling instead of starting new instance", pInstance.id(), correlation);
                        pInstance.send(Sig.of(trigger, eventData));
                        return null;
                    }
                }
                LOGGER.debug("Received message without reference id and no correlation is set/matched, staring new process instance with trigger '{}'", trigger);
                try {
                    ProcessInstance<$Type$> pi = process.createInstance(correlation, model);
                    pi.start(trigger, null, eventData);
                } catch (ProcessInstanceDuplicatedException e) {
                    ProcessInstance<$Type$> pi = process.instances().findById(correlation).get();
                    pi.send(Sig.of(trigger, eventData));
                }
                return null;
            });
        }
        return msg.ack();
    } catch (Exception e) {
        LOGGER.error("Error when consuming message for process {}", process.id(), e);
        return msg.nack(e);
    }
}
Also used : ProcessInstanceDuplicatedException(io.automatiko.engine.api.workflow.ProcessInstanceDuplicatedException) Optional(java.util.Optional) TrustedIdentityProvider(io.automatiko.engine.api.auth.TrustedIdentityProvider) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) ProcessInstanceDuplicatedException(io.automatiko.engine.api.workflow.ProcessInstanceDuplicatedException)

Example 9 with TrustedIdentityProvider

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

the class $Type$MessageConsumer method consume.

public CompletionStage<Void> consume(Message<String> msg) {
    metrics.messageReceived(CONNECTOR, MESSAGE, ((io.automatiko.engine.workflow.AbstractProcess<?>) process).process());
    final String trigger = "$Trigger$";
    try {
        IdentityProvider.set(new TrustedIdentityProvider("System<messaging>"));
        final $DataType$ eventData;
        final $Type$ model;
        final String correlation;
        LOGGER.debug("Received message with payload '{}'", msg.getPayload());
        boolean accepted;
        if (useCloudEvents.orElse(false)) {
            $DataEventType$ event;
            String contentType = appProperty(msg, "contentType");
            model = new $Type$();
            if (contentType != null && contentType.startsWith("application/cloudevents+json")) {
                // structured
                event = json.readValue(msg.getPayload(), $DataEventType$.class);
                eventData = event.getData();
            } else {
                // binary
                eventData = convert(msg, $DataType$.class);
                event = new $DataEventType$(appProperty(msg, "ce_specversion"), appProperty(msg, "ce_id"), appProperty(msg, "ce_source"), appProperty(msg, "ce_type"), appProperty(msg, "ce_subject"), appProperty(msg, "ce_time"), eventData);
                cloudEventsExtensions(msg, event);
            }
            correlation = correlationEvent(event, msg);
            accepted = acceptedEvent(event, msg);
        } else {
            eventData = convert(msg, $DataType$.class);
            model = new $Type$();
            correlation = correlationPayload(eventData, msg);
            accepted = acceptedPayload(eventData, msg);
        }
        if (!accepted) {
            metrics.messageRejected(CONNECTOR, MESSAGE, ((io.automatiko.engine.workflow.AbstractProcess<?>) process).process());
            LOGGER.debug("Message has been rejected by filter expression");
            return msg.ack();
        }
        io.automatiko.engine.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
            if (correlation != null) {
                LOGGER.debug("Correlation ({}) is set, attempting to find if there is matching instance already active", correlation);
                Collection possiblyFound = process.instances().findByIdOrTag(io.automatiko.engine.api.workflow.ProcessInstanceReadMode.MUTABLE, correlation);
                if (!possiblyFound.isEmpty()) {
                    metrics.messageConsumed(CONNECTOR, MESSAGE, ((io.automatiko.engine.workflow.AbstractProcess<?>) process).process());
                    possiblyFound.forEach(pi -> {
                        ProcessInstance pInstance = (ProcessInstance) pi;
                        LOGGER.debug("Found process instance {} matching correlation {}, signaling instead of starting new instance", pInstance.id(), correlation);
                        pInstance.send(Sig.of(canStartInstance() ? trigger : "Message-" + trigger, eventData));
                    });
                    return null;
                }
            }
            if (canStartInstance()) {
                LOGGER.debug("Received message without reference id and no correlation is set/matched, staring new process instance with trigger '{}'", trigger);
                metrics.messageConsumed(CONNECTOR, MESSAGE, ((io.automatiko.engine.workflow.AbstractProcess<?>) process).process());
                try {
                    ProcessInstance<$Type$> pi = process.createInstance(correlation, model);
                    pi.start(trigger, null, eventData);
                } catch (ProcessInstanceDuplicatedException e) {
                    ProcessInstance<$Type$> pi = process.instances().findById(correlation).get();
                    pi.send(Sig.of(trigger, eventData));
                }
            } else {
                metrics.messageMissed(CONNECTOR, MESSAGE, ((io.automatiko.engine.workflow.AbstractProcess<?>) process).process());
                LOGGER.warn("Received message without reference id and no correlation is set/matched, for trigger not capable of starting new instance '{}'", trigger);
            }
            return null;
        });
        return msg.ack();
    } catch (Exception e) {
        metrics.messageFailed(CONNECTOR, MESSAGE, ((io.automatiko.engine.workflow.AbstractProcess<?>) process).process());
        LOGGER.error("Error when consuming message for process {}", process.id(), e);
        return msg.nack(e);
    }
}
Also used : ProcessInstanceDuplicatedException(io.automatiko.engine.api.workflow.ProcessInstanceDuplicatedException) ProcessInstanceDuplicatedException(io.automatiko.engine.api.workflow.ProcessInstanceDuplicatedException) TrustedIdentityProvider(io.automatiko.engine.api.auth.TrustedIdentityProvider) Collection(java.util.Collection) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance)

Example 10 with TrustedIdentityProvider

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

the class $Type$MessageConsumer method consume.

public CompletionStage<Void> consume(Message<?> msg) {
    metrics.messageReceived(CONNECTOR, MESSAGE, ((io.automatiko.engine.workflow.AbstractProcess<?>) process).process());
    final String trigger = "$Trigger$";
    try {
        io.smallrye.reactive.messaging.kafka.KafkaRecord<?, ?> record = (io.smallrye.reactive.messaging.kafka.KafkaRecord<?, ?>) msg;
        final $DataType$ eventData;
        final $Type$ model;
        final String correlation;
        LOGGER.debug("Received message with key '{}' and payload '{}'", record.getKey(), msg.getPayload());
        boolean accepted;
        if (useCloudEvents.orElse(false)) {
            $DataEventType$ event;
            String contentType = header(record, "content-type");
            model = new $Type$();
            if (contentType != null && contentType.startsWith("application/cloudevents+json")) {
                // structured
                event = json.readValue(record.getPayload().toString(), $DataEventType$.class);
                eventData = event.getData();
            } else {
                // binary
                eventData = convert(record, $DataType$.class);
                event = new $DataEventType$(header(record, "ce_specversion"), header(record, "ce_id"), header(record, "ce_source"), header(record, "ce_type"), header(record, "ce_subject"), header(record, "ce_time"), eventData);
                cloudEventsExtensions(msg, event);
            }
            correlation = correlation(event, msg);
            accepted = acceptedEvent(event, msg);
        } else {
            eventData = convert(msg, $DataType$.class);
            model = new $Type$();
            correlation = correlation(eventData, msg);
            accepted = acceptedPayload(eventData, msg);
        }
        if (!accepted) {
            metrics.messageRejected(CONNECTOR, MESSAGE, ((io.automatiko.engine.workflow.AbstractProcess<?>) process).process());
            LOGGER.debug("Message has been rejected by filter expression");
            return msg.ack();
        }
        IdentityProvider.set(new TrustedIdentityProvider("System<messaging>"));
        io.automatiko.engine.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
            if (correlation != null) {
                LOGGER.debug("Correlation ({}) is set, attempting to find if there is matching instance already active", correlation);
                Collection possiblyFound = process.instances().findByIdOrTag(io.automatiko.engine.api.workflow.ProcessInstanceReadMode.MUTABLE, correlation);
                if (!possiblyFound.isEmpty()) {
                    metrics.messageConsumed(CONNECTOR, MESSAGE, ((io.automatiko.engine.workflow.AbstractProcess<?>) process).process());
                    possiblyFound.forEach(pi -> {
                        ProcessInstance pInstance = (ProcessInstance) pi;
                        LOGGER.debug("Found process instance {} matching correlation {}, signaling instead of starting new instance", pInstance.id(), correlation);
                        pInstance.send(Sig.of(canStartInstance() ? trigger : "Message-" + trigger, eventData));
                    });
                    return null;
                }
            }
            if (canStartInstance()) {
                LOGGER.debug("Received message without reference id and no correlation is set/matched, staring new process instance with trigger '{}'", trigger);
                metrics.messageConsumed(CONNECTOR, MESSAGE, ((io.automatiko.engine.workflow.AbstractProcess<?>) process).process());
                try {
                    ProcessInstance<$Type$> pi = process.createInstance(correlation, model);
                    pi.start(trigger, null, eventData);
                } catch (ProcessInstanceDuplicatedException e) {
                    ProcessInstance<$Type$> pi = process.instances().findById(correlation).get();
                    pi.send(Sig.of(trigger, eventData));
                }
            } else {
                metrics.messageMissed(CONNECTOR, MESSAGE, ((io.automatiko.engine.workflow.AbstractProcess<?>) process).process());
                LOGGER.warn("Received message without reference id and no correlation is set/matched, for trigger not capable of starting new instance '{}'", trigger);
            }
            return null;
        });
        return msg.ack();
    } catch (Exception e) {
        metrics.messageFailed(CONNECTOR, MESSAGE, ((io.automatiko.engine.workflow.AbstractProcess<?>) process).process());
        LOGGER.error("Error when consuming message for process {}", process.id(), e);
        return msg.nack(e);
    }
}
Also used : ProcessInstanceDuplicatedException(io.automatiko.engine.api.workflow.ProcessInstanceDuplicatedException) ProcessInstanceDuplicatedException(io.automatiko.engine.api.workflow.ProcessInstanceDuplicatedException) TrustedIdentityProvider(io.automatiko.engine.api.auth.TrustedIdentityProvider) Collection(java.util.Collection) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance)

Aggregations

TrustedIdentityProvider (io.automatiko.engine.api.auth.TrustedIdentityProvider)11 ProcessInstance (io.automatiko.engine.api.workflow.ProcessInstance)7 Optional (java.util.Optional)5 ProcessInstanceDuplicatedException (io.automatiko.engine.api.workflow.ProcessInstanceDuplicatedException)3 Model (io.automatiko.engine.api.Model)2 AbstractProcessInstance (io.automatiko.engine.workflow.AbstractProcessInstance)2 Collection (java.util.Collection)2 Application (io.automatiko.engine.api.Application)1 AccessDeniedException (io.automatiko.engine.api.auth.AccessDeniedException)1 IdentityProvider (io.automatiko.engine.api.auth.IdentityProvider)1 ProcessInstanceJobDescription (io.automatiko.engine.api.jobs.ProcessInstanceJobDescription)1 ProcessJobDescription (io.automatiko.engine.api.jobs.ProcessJobDescription)1 EventListener (io.automatiko.engine.api.runtime.process.EventListener)1 Process (io.automatiko.engine.api.workflow.Process)1 AbstractCodegenTest (io.automatiko.engine.codegen.AbstractCodegenTest)1 StaticIdentityProvider (io.automatiko.engine.services.identity.StaticIdentityProvider)1 InternalProcessRuntime (io.automatiko.engine.workflow.base.instance.InternalProcessRuntime)1 NodeInstance (io.automatiko.engine.workflow.process.instance.NodeInstance)1 WorkflowProcessInstanceImpl (io.automatiko.engine.workflow.process.instance.impl.WorkflowProcessInstanceImpl)1 CompositeNodeInstance (io.automatiko.engine.workflow.process.instance.node.CompositeNodeInstance)1