Search in sources :

Example 21 with Model

use of io.automatiko.engine.api.Model in project automatiko-engine by automatiko-io.

the class MongodbProcessInstances method update.

@Override
public void update(String id, ProcessInstance instance) {
    String resolvedId = resolveId(id, instance);
    try {
        if (isActive(instance)) {
            byte[] data = codec.encode(marshaller.marhsallProcessInstance(instance));
            if (data == null) {
                return;
            }
            Model entity = (Model) instance.variables();
            String variablesJson = marshallingStrategy.mapper().writeValueAsString(entity);
            Document variables = Document.parse(variablesJson);
            removeTransientVariables(variables, instance);
            Collection<String> tags = new LinkedHashSet<>(instance.tags().values());
            tags.add(resolvedId);
            if (instance.businessKey() != null) {
                tags.add(instance.businessKey());
            }
            Document item = new Document(INSTANCE_ID_FIELD, resolvedId).append(CONTENT_FIELD, data).append(STATUS_FIELD, instance.status()).append(TAGS_FIELD, tags).append(VERSION_FIELD, ((AbstractProcessInstance<?>) instance).getVersionTracker()).append(VARIABLES_FIELD, variables).append(START_DATE_FIELD, instance.startDate());
            if (instance.endDate() != null) {
                item.append(END_DATE_FIELD, instance.endDate());
                if (instance.expiresAtDate() != null) {
                    item.append(EXPIRED_AT_FIELD, instance.expiresAtDate());
                }
            }
            try {
                Document replaced = collection().findOneAndReplace(and(eq(INSTANCE_ID_FIELD, resolvedId), eq(VERSION_FIELD, ((AbstractProcessInstance<?>) instance).getVersionTracker())), item);
                if (replaced == null) {
                    if (transactionLog.contains(process.id(), instance.id())) {
                        collection().insertOne(item);
                    } else {
                        throw new ConflictingVersionException("Process instance with id '" + instance.id() + "' has older version than the stored one");
                    }
                }
                Supplier<AuditEntry> entry = () -> BaseAuditEntry.persitenceWrite(instance).add("message", "Workflow instance updated in the MongoDB based data store");
                auditor.publish(entry);
            } finally {
                cachedInstances.remove(resolvedId);
                cachedInstances.remove(id);
                disconnect(instance);
            }
        } else if (isPending(instance)) {
            if (cachedInstances.putIfAbsent(resolvedId, instance) != null) {
                throw new ProcessInstanceDuplicatedException(id);
            }
        } else {
            cachedInstances.remove(resolvedId);
            cachedInstances.remove(id);
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ConflictingVersionException(io.automatiko.engine.api.workflow.ConflictingVersionException) ProcessInstanceDuplicatedException(io.automatiko.engine.api.workflow.ProcessInstanceDuplicatedException) AuditEntry(io.automatiko.engine.api.audit.AuditEntry) BaseAuditEntry(io.automatiko.engine.workflow.audit.BaseAuditEntry) Model(io.automatiko.engine.api.Model) UncheckedIOException(java.io.UncheckedIOException) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument)

Example 22 with Model

use of io.automatiko.engine.api.Model in project automatiko-engine by automatiko-io.

the class MongodbProcessInstances method unmarshallInstance.

protected ProcessInstance unmarshallInstance(ProcessInstanceReadMode mode, Document entity) {
    try {
        ProcessInstance pi;
        if (mode == MUTABLE) {
            WorkflowProcessInstance wpi = marshaller.unmarshallWorkflowProcessInstance(codec.decode(entity.get(CONTENT_FIELD, Binary.class).getData()), process);
            String variablesJson = entity.get(VARIABLES_FIELD, Document.class).toJson();
            Model model = process.createModel();
            Map<String, Object> loaded = marshallingStrategy.mapper().readValue(variablesJson, model.getClass()).toMap();
            model.fromMap(loaded);
            loaded.forEach((k, v) -> {
                if (v != null) {
                    v.toString();
                    VariableScopeInstance variableScopeInstance = (VariableScopeInstance) ((ProcessInstanceImpl) wpi).getContextInstance(VariableScope.VARIABLE_SCOPE);
                    variableScopeInstance.internalSetVariable(k, v);
                }
            });
            pi = ((AbstractProcess) process).createInstance(wpi, model, entity.getLong(VERSION_FIELD));
        } else {
            WorkflowProcessInstance wpi = marshaller.unmarshallWorkflowProcessInstance(codec.decode(entity.get(CONTENT_FIELD, Binary.class).getData()), process);
            String variablesJson = entity.get(VARIABLES_FIELD, Document.class).toJson();
            Model model = process.createModel();
            Map<String, Object> loaded = marshallingStrategy.mapper().readValue(variablesJson, model.getClass()).toMap();
            model.fromMap(loaded);
            loaded.forEach((k, v) -> {
                if (v != null) {
                    v.toString();
                    VariableScopeInstance variableScopeInstance = (VariableScopeInstance) ((ProcessInstanceImpl) wpi).getContextInstance(VariableScope.VARIABLE_SCOPE);
                    variableScopeInstance.internalSetVariable(k, v);
                }
            });
            pi = ((AbstractProcess) process).createReadOnlyInstance(wpi, model);
        }
        return pi;
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
Also used : VariableScopeInstance(io.automatiko.engine.workflow.base.instance.context.variable.VariableScopeInstance) Model(io.automatiko.engine.api.Model) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) ExportedProcessInstance(io.automatiko.engine.api.workflow.ExportedProcessInstance) AbstractProcessInstance(io.automatiko.engine.workflow.AbstractProcessInstance) WorkflowProcessInstance(io.automatiko.engine.api.runtime.process.WorkflowProcessInstance) UncheckedIOException(java.io.UncheckedIOException) Binary(org.bson.types.Binary) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) WorkflowProcessInstance(io.automatiko.engine.api.runtime.process.WorkflowProcessInstance)

Example 23 with Model

use of io.automatiko.engine.api.Model in project automatiko-engine by automatiko-io.

the class PredictionAwareHumanTaskLifeCycleTest method testUserTaskWithoutPredictionService.

@Test
public void testUserTaskWithoutPredictionService() {
    BpmnProcess process = (BpmnProcess) BpmnProcess.from(config, new ClassPathResource("BPMN2-UserTask.bpmn2")).get(0);
    process.configure();
    ProcessInstance<BpmnVariables> processInstance = process.createInstance(BpmnVariables.create(Collections.singletonMap("test", "test")));
    processInstance.start();
    assertEquals(STATE_ACTIVE, processInstance.status());
    WorkItem workItem = processInstance.workItems(securityPolicy).get(0);
    assertNotNull(workItem);
    assertEquals("john", workItem.getParameters().get("ActorId"));
    processInstance.completeWorkItem(workItem.getId(), Collections.singletonMap("output", "given value"), securityPolicy);
    assertEquals(STATE_COMPLETED, processInstance.status());
    Model result = (Model) processInstance.variables();
    assertEquals(2, result.toMap().size());
    assertEquals("given value", result.toMap().get("s"));
    assertEquals(1, trainedTasks.size());
}
Also used : BpmnProcess(io.automatiko.engine.workflow.bpmn2.BpmnProcess) Model(io.automatiko.engine.api.Model) WorkItem(io.automatiko.engine.api.workflow.WorkItem) ClassPathResource(io.automatiko.engine.services.io.ClassPathResource) BpmnVariables(io.automatiko.engine.workflow.bpmn2.BpmnVariables) Test(org.junit.jupiter.api.Test)

Example 24 with Model

use of io.automatiko.engine.api.Model in project automatiko-engine by automatiko-io.

the class Controller method reconcile.

@Override
public synchronized UpdateControl<$DataType$> reconcile($DataType$ resource, Context context) {
    if (!acceptedPayload(resource)) {
        LOGGER.debug("Event has been rejected by the filter expression");
        return UpdateControl.noUpdate();
    }
    String trigger = "$Trigger$";
    IdentityProvider.set(new TrustedIdentityProvider("System<messaging>"));
    final $Type$ model = new $Type$();
    return io.automatiko.engine.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
        try {
            String correlation = resource.getMetadata().getName();
            if (correlation != null) {
                LOGGER.debug("Correlation ({}) is set, attempting to find if there is matching instance already active", correlation);
                Optional<? extends ProcessInstance> possiblyFound = (Optional<? extends ProcessInstance>) 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("Message-updated", resource));
                    $DataType$ updated = ($DataType$) ((Model) pInstance.variables()).toMap().get("resource");
                    if (updated == null || Boolean.TRUE.equals(((WorkflowProcessInstanceImpl) ((AbstractProcessInstance<?>) pInstance).processInstance()).getVariable("skipResourceUpdate"))) {
                        LOGGER.debug("Signalled and returned updated {} no need to updated custom resource", updated);
                        return UpdateControl.noUpdate();
                    }
                    LOGGER.debug("Signalled and returned updated {} that requires update of the custom resource", updated);
                    return UpdateControl.updateResourceAndStatus(updated);
                }
            }
            if (canStartInstance()) {
                LOGGER.debug("Received message without reference id and no correlation is set/matched, staring new process instance with trigger '{}'", trigger);
                ProcessInstance<?> pi = process.createInstance(correlation, model);
                pi.start(trigger, null, resource);
                $DataType$ updated = ($DataType$) ((Model) pi.variables()).toMap().get("resource");
                if (updated == null || Boolean.TRUE.equals(((WorkflowProcessInstanceImpl) ((AbstractProcessInstance<?>) pi).processInstance()).getVariable("skipResourceUpdate"))) {
                    LOGGER.debug("New instance started and not need to update custom resource");
                    return UpdateControl.noUpdate();
                }
                LOGGER.debug("New instance started and with the need to update custom resource");
                return UpdateControl.updateResourceAndStatus(updated);
            } else {
                LOGGER.warn("Received message without reference id and no correlation is set/matched, for trigger not capable of starting new instance '{}'", trigger);
            }
        } catch (Throwable t) {
            LOGGER.error("Encountered problems while creating/updating instance", t);
        }
        return UpdateControl.noUpdate();
    });
}
Also used : Optional(java.util.Optional) TrustedIdentityProvider(io.automatiko.engine.api.auth.TrustedIdentityProvider) Model(io.automatiko.engine.api.Model) WorkflowProcessInstanceImpl(io.automatiko.engine.workflow.process.instance.impl.WorkflowProcessInstanceImpl) AbstractProcessInstance(io.automatiko.engine.workflow.AbstractProcessInstance) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance)

Example 25 with Model

use of io.automatiko.engine.api.Model in project automatiko-engine by automatiko-io.

the class MessageStartEventTest method testMessageStartAndEndEventProcess.

@Test
public void testMessageStartAndEndEventProcess() throws Exception {
    Application app = generateCodeProcessesOnly("messagestartevent/MessageStartAndEndEvent.bpmn2");
    assertThat(app).isNotNull();
    Process<? extends Model> p = app.processes().processById("MessageStartEvent");
    Model m = p.createModel();
    Map<String, Object> parameters = new HashMap<>();
    m.fromMap(parameters);
    ProcessInstance<?> processInstance = p.createInstance(m);
    processInstance.start("customers", null, "CUS-00998877");
    assertThat(processInstance.status()).isEqualTo(ProcessInstance.STATE_COMPLETED);
    Model result = (Model) processInstance.variables();
    assertThat(result.toMap()).hasSize(1).containsKeys("customerId");
    assertThat(result.toMap().get("customerId")).isNotNull().isEqualTo("CUS-00998877");
}
Also used : HashMap(java.util.HashMap) Model(io.automatiko.engine.api.Model) Application(io.automatiko.engine.api.Application) AbstractCodegenTest(io.automatiko.engine.codegen.AbstractCodegenTest) Test(org.junit.jupiter.api.Test)

Aggregations

Model (io.automatiko.engine.api.Model)167 Application (io.automatiko.engine.api.Application)148 Test (org.junit.jupiter.api.Test)143 AbstractCodegenTest (io.automatiko.engine.codegen.AbstractCodegenTest)138 HashMap (java.util.HashMap)127 WorkItem (io.automatiko.engine.api.workflow.WorkItem)44 ProcessInstance (io.automatiko.engine.api.workflow.ProcessInstance)27 DefaultProcessEventListenerConfig (io.automatiko.engine.workflow.DefaultProcessEventListenerConfig)23 NodeLeftCountDownProcessEventListener (io.automatiko.engine.workflow.compiler.util.NodeLeftCountDownProcessEventListener)23 ArrayList (java.util.ArrayList)17 HumanTaskTransition (io.automatiko.engine.workflow.base.instance.impl.humantask.HumanTaskTransition)13 JsonNode (com.fasterxml.jackson.databind.JsonNode)11 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)11 Person (io.automatiko.engine.codegen.data.Person)10 StaticIdentityProvider (io.automatiko.engine.services.identity.StaticIdentityProvider)10 List (java.util.List)10 UnitOfWork (io.automatiko.engine.api.uow.UnitOfWork)9 Map (java.util.Map)9 DataEvent (io.automatiko.engine.api.event.DataEvent)8 ProcessInstanceDataEvent (io.automatiko.engine.services.event.ProcessInstanceDataEvent)8