Search in sources :

Example 41 with ProcessInstance

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

the class BusinessRuleTaskTest method testDecision.

@Test
public void testDecision() throws Exception {
    Application app = generateCode(Collections.singletonList("decision/models/dmnprocess.bpmn2"), Collections.emptyList(), Collections.singletonList("decision/models/vacationDaysAlt/vacationDaysAlt.dmn"), Collections.emptyList(), false);
    Process<? extends Model> p = app.processes().processById("DmnProcess_1_0");
    // first run 16, 1 and expected days is 27
    {
        Model m = p.createModel();
        HashMap<String, Object> vars = new HashMap<>();
        vars.put("age", 16);
        vars.put("yearsOfService", 1);
        m.fromMap(vars);
        ProcessInstance<? extends Model> processInstance = p.createInstance(m);
        processInstance.start();
        assertThat(processInstance.status()).isEqualTo(ProcessInstance.STATE_COMPLETED);
        Model result = processInstance.variables();
        assertThat(result.toMap().get("vacationDays")).isNotNull().isEqualTo(BigDecimal.valueOf(27));
    }
    // second run 44, 20 and expected days is 24
    {
        Model m = p.createModel();
        HashMap<String, Object> vars = new HashMap<>();
        vars.put("age", 44);
        vars.put("yearsOfService", 20);
        m.fromMap(vars);
        ProcessInstance<? extends Model> processInstance = p.createInstance(m);
        processInstance.start();
        assertThat(processInstance.status()).isEqualTo(ProcessInstance.STATE_COMPLETED);
        Model result = processInstance.variables();
        assertThat(result.toMap().get("vacationDays")).isNotNull().isEqualTo(BigDecimal.valueOf(24));
    }
    // second run 50, 30 and expected days is 30
    {
        Model m = p.createModel();
        HashMap<String, Object> vars = new HashMap<>();
        vars.put("age", 50);
        vars.put("yearsOfService", 30);
        m.fromMap(vars);
        ProcessInstance<? extends Model> processInstance = p.createInstance(m);
        processInstance.start();
        assertThat(processInstance.status()).isEqualTo(ProcessInstance.STATE_COMPLETED);
        Model result = processInstance.variables();
        assertThat(result.toMap().get("vacationDays")).isNotNull().isEqualTo(BigDecimal.valueOf(30));
    }
}
Also used : HashMap(java.util.HashMap) Model(io.automatiko.engine.api.Model) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) Application(io.automatiko.engine.api.Application) AbstractCodegenTest(io.automatiko.engine.codegen.AbstractCodegenTest) Test(org.junit.jupiter.api.Test)

Example 42 with ProcessInstance

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

the class TimerEventTest method testStartTimerEventTimeCycle.

@Test
public void testStartTimerEventTimeCycle() throws Exception {
    Application app = generateCodeProcessesOnly("timer/StartTimerCycle.bpmn2");
    assertThat(app).isNotNull();
    NodeLeftCountDownProcessEventListener listener = new NodeLeftCountDownProcessEventListener("timer fired", 2);
    ((DefaultProcessEventListenerConfig) app.config().process().processEventListeners()).register(listener);
    Process<? extends Model> p = app.processes().processById("defaultPackage.TimerProcess");
    // activate to schedule timers
    p.activate();
    boolean completed = listener.waitTillCompleted(5000);
    assertThat(completed).isTrue();
    Collection<?> instances = p.instances().values(1, 10);
    assertThat(instances).hasSize(2);
    ProcessInstance<?> processInstance = (ProcessInstance<?>) instances.iterator().next();
    assertThat(processInstance).isNotNull();
    assertThat(processInstance.status()).isEqualTo(ProcessInstance.STATE_ACTIVE);
    // deactivate to cancel timer, so there should be no more timers fired
    p.deactivate();
    // reset the listener to make sure nothing more is triggered
    listener.reset(1);
    completed = listener.waitTillCompleted(3000);
    assertThat(completed).isFalse();
    // same amount of instances should be active as before deactivation
    instances = p.instances().values(1, 10);
    assertThat(instances).hasSize(2);
    // clean up by aborting all instances
    instances.forEach(i -> ((ProcessInstance<?>) i).abort());
    instances = p.instances().values(1, 10);
    assertThat(instances).hasSize(0);
}
Also used : NodeLeftCountDownProcessEventListener(io.automatiko.engine.workflow.compiler.util.NodeLeftCountDownProcessEventListener) DefaultProcessEventListenerConfig(io.automatiko.engine.workflow.DefaultProcessEventListenerConfig) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) Application(io.automatiko.engine.api.Application) AbstractCodegenTest(io.automatiko.engine.codegen.AbstractCodegenTest) Test(org.junit.jupiter.api.Test)

Example 43 with ProcessInstance

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

the class ProcessInstanceMarshaller method exportProcessInstance.

public ExportedProcessInstance<?> exportProcessInstance(ProcessInstance<?> processInstance) {
    io.automatiko.engine.api.runtime.process.ProcessInstance pi = ((AbstractProcessInstance<?>) processInstance).internalGetProcessInstance();
    if (pi == null) {
        return null;
    }
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        Map<String, Object> localEnv = new HashMap<String, Object>(env);
        localEnv.put("_export_", true);
        ProcessMarshallerWriteContext context = new ProcessMarshallerWriteContext(baos, ((io.automatiko.engine.workflow.base.instance.ProcessInstance) pi).getProcessRuntime(), null, localEnv);
        context.setProcessInstanceId(pi.getId());
        context.setState(pi.getState());
        String processType = pi.getProcess().getType();
        context.stream.writeUTF(processType);
        io.automatiko.engine.workflow.marshalling.impl.ProcessInstanceMarshaller marshaller = ProcessMarshallerRegistry.INSTANCE.getMarshaller(processType);
        Object result = marshaller.writeProcessInstance(context, pi);
        AutomatikoMessages.Header.Builder _header = AutomatikoMessages.Header.newBuilder();
        _header.setVersion(AutomatikoMessages.Version.newBuilder().setVersionMajor(1).setVersionMinor(0).setVersionRevision(0).build());
        PersisterHelper.writeStrategiesIndex(context, _header);
        String header = JsonFormat.printer().print(_header);
        context.close();
        // collect all information about timers
        Collection<io.automatiko.engine.workflow.process.instance.NodeInstance> nodes = ((WorkflowProcessInstanceImpl) pi).getNodeInstances(true);
        StringBuilder timers = new StringBuilder("[");
        for (io.automatiko.engine.workflow.process.instance.NodeInstance ni : nodes) {
            String timerId = null;
            if (ni instanceof TimerNodeInstance) {
                timerId = ((TimerNodeInstance) ni).getTimerId();
            } else if (ni instanceof StateBasedNodeInstance) {
                if (((StateBasedNodeInstance) ni).getTimerInstances() != null) {
                    ((StateBasedNodeInstance) ni).getTimerInstances().forEach(timer -> {
                        ZonedDateTime scheduledTime = context.processRuntime.getJobsService().getScheduledTime(timer);
                        timers.append("{\"timerId\":\"").append(timer).append("\",\"scheduledAt\":\"").append(scheduledTime.toString()).append("\",\"nodeInstanceId\":\"").append(ni.getId()).append("\"}");
                    });
                }
            }
            if (timerId != null) {
                ZonedDateTime scheduledTime = context.processRuntime.getJobsService().getScheduledTime(timerId);
                timers.append("{\"timerId\":\"").append(timerId).append("\",\"scheduledAt\":\"").append(scheduledTime.toString()).append("\",\"nodeInstanceId\":\"").append(ni.getId()).append("\"}");
            }
            if (((NodeInstanceImpl) ni).getRetryJobId() != null && !((NodeInstanceImpl) ni).getRetryJobId().isEmpty()) {
                ZonedDateTime scheduledTime = context.processRuntime.getJobsService().getScheduledTime(((NodeInstanceImpl) ni).getRetryJobId());
                timers.append("{\"timerId\":\"").append(((NodeInstanceImpl) ni).getRetryJobId()).append("\",\"scheduledAt\":\"").append(scheduledTime.toString()).append("\",\"nodeInstanceId\":\"").append(ni.getId()).append("\"}");
            }
        }
        timers.append("]");
        return StringExportedProcessInstance.of(header, JsonFormat.printer().print((MessageOrBuilder) result), timers.toString(), null);
    } catch (Exception e) {
        throw new RuntimeException("Error while marshalling process instance", e);
    }
}
Also used : StateBasedNodeInstance(io.automatiko.engine.workflow.process.instance.node.StateBasedNodeInstance) TimerNodeInstance(io.automatiko.engine.workflow.process.instance.node.TimerNodeInstance) AbstractProcessInstance(io.automatiko.engine.workflow.AbstractProcessInstance) Timer(io.automatiko.engine.workflow.base.core.timer.Timer) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ProtobufRuleFlowProcessInstanceMarshaller(io.automatiko.engine.workflow.marshalling.impl.ProtobufRuleFlowProcessInstanceMarshaller) WorkflowProcessInstanceImpl(io.automatiko.engine.workflow.process.instance.impl.WorkflowProcessInstanceImpl) ZonedDateTime(java.time.ZonedDateTime) ObjectInputStream(java.io.ObjectInputStream) ExpirationTime(io.automatiko.engine.api.jobs.ExpirationTime) NodeInstanceImpl(io.automatiko.engine.workflow.process.instance.impl.NodeInstanceImpl) HashMap(java.util.HashMap) MessageOrBuilder(com.google.protobuf.MessageOrBuilder) SerializablePlaceholderResolverStrategy(io.automatiko.engine.workflow.marshalling.impl.strategies.SerializablePlaceholderResolverStrategy) LinkedHashMap(java.util.LinkedHashMap) JobsService(io.automatiko.engine.api.jobs.JobsService) ByteArrayInputStream(java.io.ByteArrayInputStream) Map(java.util.Map) Process(io.automatiko.engine.api.workflow.Process) PersisterHelper(io.automatiko.engine.workflow.marshalling.impl.PersisterHelper) AbstractProcess(io.automatiko.engine.workflow.AbstractProcess) StreamCorruptedException(java.io.StreamCorruptedException) Iterator(java.util.Iterator) Model(io.automatiko.engine.api.Model) AutomatikoMessages(io.automatiko.engine.workflow.marshalling.impl.AutomatikoMessages) Collection(java.util.Collection) ClassObjectMarshallingStrategyAcceptor(io.automatiko.engine.workflow.marshalling.impl.ClassObjectMarshallingStrategyAcceptor) IOException(java.io.IOException) WorkflowProcessInstance(io.automatiko.engine.api.runtime.process.WorkflowProcessInstance) MarshallerReaderContext(io.automatiko.engine.workflow.marshalling.impl.MarshallerReaderContext) ProcessMarshallerRegistry(io.automatiko.engine.workflow.marshalling.impl.ProcessMarshallerRegistry) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) StringExportedProcessInstance(io.automatiko.engine.workflow.StringExportedProcessInstance) List(java.util.List) JsonFormat(com.google.protobuf.util.JsonFormat) ObjectMarshallingStrategy(io.automatiko.engine.api.marshalling.ObjectMarshallingStrategy) ExportedProcessInstance(io.automatiko.engine.api.workflow.ExportedProcessInstance) EnvironmentName(io.automatiko.engine.api.runtime.EnvironmentName) ProcessInstanceJobDescription(io.automatiko.engine.api.jobs.ProcessInstanceJobDescription) AbstractProcessInstance(io.automatiko.engine.workflow.AbstractProcessInstance) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) WorkflowProcessInstanceImpl(io.automatiko.engine.workflow.process.instance.impl.WorkflowProcessInstanceImpl) MessageOrBuilder(com.google.protobuf.MessageOrBuilder) ZonedDateTime(java.time.ZonedDateTime) NodeInstanceImpl(io.automatiko.engine.workflow.process.instance.impl.NodeInstanceImpl) StateBasedNodeInstance(io.automatiko.engine.workflow.process.instance.node.StateBasedNodeInstance) ByteArrayOutputStream(java.io.ByteArrayOutputStream) StreamCorruptedException(java.io.StreamCorruptedException) IOException(java.io.IOException) StateBasedNodeInstance(io.automatiko.engine.workflow.process.instance.node.StateBasedNodeInstance) TimerNodeInstance(io.automatiko.engine.workflow.process.instance.node.TimerNodeInstance) TimerNodeInstance(io.automatiko.engine.workflow.process.instance.node.TimerNodeInstance)

Example 44 with ProcessInstance

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

the class AbstractProcessInstance method archive.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public ArchivedProcessInstance archive(ArchiveBuilder builder) {
    ArchivedProcessInstance archived = builder.instance(id, process.id(), ((MutableProcessInstances) process().instances()).exportInstance(this, false));
    Map<String, Object> variables = processInstance().getVariables();
    for (Entry<String, Object> var : variables.entrySet()) {
        archived.addVariable(builder.variable(var.getKey(), var.getValue()));
    }
    Collection<ProcessInstance<? extends Model>> subInstances = subprocesses(ProcessInstanceReadMode.MUTABLE);
    List<ArchivedProcessInstance> subinstances = new ArrayList<ArchivedProcessInstance>();
    if (!subInstances.isEmpty()) {
        for (ProcessInstance<? extends Model> si : subInstances) {
            ArchivedProcessInstance subArchived = si.archive(builder);
            subinstances.add(subArchived);
        }
    }
    archived.setSubInstances(subinstances);
    return archived;
}
Also used : Model(io.automatiko.engine.api.Model) ArrayList(java.util.ArrayList) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) ArchivedProcessInstance(io.automatiko.engine.api.workflow.ArchivedProcessInstance) WorkflowProcessInstance(io.automatiko.engine.api.runtime.process.WorkflowProcessInstance) ArchivedProcessInstance(io.automatiko.engine.api.workflow.ArchivedProcessInstance)

Example 45 with ProcessInstance

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

the class MapProcessInstances method importInstance.

@Override
public ProcessInstance importInstance(ExportedProcessInstance instance, Process process) {
    ProcessInstance imported = marshaller.importProcessInstance(instance, process);
    if (exists(imported.id())) {
        throw new ProcessInstanceDuplicatedException(imported.id());
    }
    create(imported.id(), imported);
    return imported;
}
Also used : ProcessInstanceDuplicatedException(io.automatiko.engine.api.workflow.ProcessInstanceDuplicatedException) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) ExportedProcessInstance(io.automatiko.engine.api.workflow.ExportedProcessInstance)

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