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);
}
}
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);
}
}
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());
}
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();
});
}
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");
}
Aggregations