use of io.automatiko.engine.workflow.base.core.timer.Timer in project automatiko-engine by automatiko-io.
the class TimerNodeHandler method writeNode.
public void writeNode(Node node, StringBuilder xmlDump, int metaDataType) {
TimerNode timerNode = (TimerNode) node;
writeNode("intermediateCatchEvent", timerNode, xmlDump, metaDataType);
xmlDump.append(">" + EOL);
writeExtensionElements(node, xmlDump);
xmlDump.append(" <timerEventDefinition>" + EOL);
Timer timer = timerNode.getTimer();
if (timer != null && (timer.getDelay() != null || timer.getDate() != null)) {
if (timer.getTimeType() == Timer.TIME_DURATION) {
xmlDump.append(" <timeDuration xsi:type=\"tFormalExpression\">" + XmlDumper.replaceIllegalChars(timer.getDelay()) + "</timeDuration>" + EOL);
} else if (timer.getTimeType() == Timer.TIME_CYCLE) {
if (timer.getPeriod() != null) {
xmlDump.append(" <timeCycle xsi:type=\"tFormalExpression\">" + XmlDumper.replaceIllegalChars(timer.getDelay()) + "###" + XmlDumper.replaceIllegalChars(timer.getPeriod()) + "</timeCycle>" + EOL);
} else {
xmlDump.append(" <timeCycle xsi:type=\"tFormalExpression\">" + XmlDumper.replaceIllegalChars(timer.getDelay()) + "</timeCycle>" + EOL);
}
} else if (timer.getTimeType() == Timer.TIME_DATE) {
xmlDump.append(" <timeDate xsi:type=\"tFormalExpression\">" + XmlDumper.replaceIllegalChars(timer.getDelay()) + "</timeDate>" + EOL);
}
}
xmlDump.append(" </timerEventDefinition>" + EOL);
endNode("intermediateCatchEvent", xmlDump);
}
use of io.automatiko.engine.workflow.base.core.timer.Timer in project automatiko-engine by automatiko-io.
the class StateBasedNodeInstance method extractTimerEventInformation.
public Map<String, String> extractTimerEventInformation() {
if (getTimerInstances() != null) {
for (String id : getTimerInstances()) {
String[] ids = id.split("_");
for (Timer entry : getEventBasedNode().getTimers().keySet()) {
if (entry.getId() == Long.valueOf(ids[1])) {
Map<String, String> properties = new HashMap<>();
properties.put("TimerID", id);
properties.put("Delay", entry.getDelay());
properties.put("Period", entry.getPeriod());
properties.put("Date", entry.getDate());
return properties;
}
}
}
}
return null;
}
use of io.automatiko.engine.workflow.base.core.timer.Timer 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);
}
}
use of io.automatiko.engine.workflow.base.core.timer.Timer in project automatiko-engine by automatiko-io.
the class WorkflowProcessInstanceImpl method getEventDescriptions.
@Override
public Set<EventDescription<?>> getEventDescriptions() {
if (getState() == ProcessInstance.STATE_COMPLETED || getState() == ProcessInstance.STATE_ABORTED) {
return Collections.emptySet();
}
VariableScope variableScope = (VariableScope) ((ContextContainer) getProcess()).getDefaultContext(VariableScope.VARIABLE_SCOPE);
Set<EventDescription<?>> eventDesciptions = new LinkedHashSet<>();
List<EventListener> activeListeners = eventListeners.values().stream().flatMap(List::stream).collect(Collectors.toList());
activeListeners.addAll(externalEventListeners.values().stream().flatMap(List::stream).collect(Collectors.toList()));
activeListeners.forEach(el -> eventDesciptions.addAll(el.getEventDescriptions()));
((io.automatiko.engine.workflow.process.core.WorkflowProcess) getProcess()).getNodesRecursively().stream().filter(n -> n instanceof EventNodeInterface).forEach(n -> {
NamedDataType dataType = null;
if (((EventNodeInterface) n).getVariableName() != null) {
Map<String, Object> dataOutputs = (Map<String, Object>) n.getMetaData().get("DataOutputs");
if (dataOutputs != null) {
for (Entry<String, Object> dOut : dataOutputs.entrySet()) {
dataType = new NamedDataType(dOut.getKey(), dOut.getValue());
}
} else {
Variable eventVar = variableScope.findVariable(((EventNodeInterface) n).getVariableName());
if (eventVar != null) {
dataType = new NamedDataType(eventVar.getName(), eventVar.getType());
}
}
}
if (n instanceof BoundaryEventNode) {
BoundaryEventNode boundaryEventNode = (BoundaryEventNode) n;
StateBasedNodeInstance attachedToNodeInstance = (StateBasedNodeInstance) getNodeInstances(true).stream().filter(ni -> ni.getNode().getMetaData().get(UNIQUE_ID).equals(boundaryEventNode.getAttachedToNodeId())).findFirst().orElse(null);
if (attachedToNodeInstance != null) {
Map<String, String> properties = new HashMap<>();
properties.put("AttachedToID", attachedToNodeInstance.getNodeDefinitionId());
properties.put("AttachedToName", attachedToNodeInstance.getNodeName());
String eventType = EVENT_TYPE_SIGNAL;
String eventName = boundaryEventNode.getType();
Map<String, String> timerProperties = attachedToNodeInstance.extractTimerEventInformation();
if (timerProperties != null) {
properties.putAll(timerProperties);
eventType = "timer";
eventName = "timerTriggered";
}
eventDesciptions.add(new BaseEventDescription(eventName, (String) n.getMetaData().get(UNIQUE_ID), n.getName(), eventType, null, getId(), dataType, properties));
}
} else if (n instanceof EventSubProcessNode) {
EventSubProcessNode eventSubProcessNode = (EventSubProcessNode) n;
boolean isContainerActive = false;
if (eventSubProcessNode.getParentContainer() instanceof WorkflowProcess) {
isContainerActive = true;
} else if (eventSubProcessNode.getParentContainer() instanceof CompositeNode) {
isContainerActive = !getNodeInstances(((CompositeNode) eventSubProcessNode.getParentContainer()).getId()).isEmpty();
}
if (isContainerActive) {
Node startNode = eventSubProcessNode.findStartNode();
Map<Timer, ProcessAction> timers = eventSubProcessNode.getTimers();
if (timers != null && !timers.isEmpty()) {
getNodeInstances(eventSubProcessNode.getId()).forEach(ni -> {
Map<String, String> timerProperties = ((StateBasedNodeInstance) ni).extractTimerEventInformation();
if (timerProperties != null) {
eventDesciptions.add(new BaseEventDescription("timerTriggered", (String) startNode.getMetaData().get("UniqueId"), startNode.getName(), "timer", ni.getId(), getId(), null, timerProperties));
}
});
} else {
for (String eventName : eventSubProcessNode.getEvents()) {
if ("variableChanged".equals(eventName)) {
continue;
}
eventDesciptions.add(new BaseEventDescription(eventName, (String) startNode.getMetaData().get("UniqueId"), startNode.getName(), "signal", null, getId(), dataType));
}
}
}
} else if (n instanceof EventNode) {
NamedDataType finalDataType = dataType;
getNodeInstances(n.getId()).forEach(ni -> eventDesciptions.add(new BaseEventDescription(((EventNode) n).getType(), (String) n.getMetaData().get(UNIQUE_ID), n.getName(), (String) n.getMetaData().getOrDefault(EVENT_TYPE, EVENT_TYPE_SIGNAL), ni.getId(), getId(), finalDataType)));
} else if (n instanceof StateNode) {
getNodeInstances(n.getId()).forEach(ni -> eventDesciptions.add(new BaseEventDescription((String) n.getMetaData().get(CONDITION), (String) n.getMetaData().get(UNIQUE_ID), n.getName(), (String) n.getMetaData().getOrDefault(EVENT_TYPE, EVENT_TYPE_SIGNAL), ni.getId(), getId(), null)));
}
});
return eventDesciptions;
}
use of io.automatiko.engine.workflow.base.core.timer.Timer in project automatiko-engine by automatiko-io.
the class WorkflowProcessInstanceImpl method signalEvent.
@Override
@SuppressWarnings("unchecked")
public void signalEvent(String type, Object event) {
logger.debug("Signal {} received with data {} in process instance {}", type, event, getId());
synchronized (this) {
if (getState() != ProcessInstance.STATE_ACTIVE) {
return;
}
InternalProcessRuntime processRuntime = getProcessRuntime();
processRuntime.getProcessEventSupport().fireBeforeProcessSignaled(type, event, this, processRuntime);
if ("timerTriggered".equals(type)) {
TimerInstance timer = (TimerInstance) event;
if (timer.getId().equals(slaTimerId)) {
handleSLAViolation();
// no need to pass the event along as it was purely for SLA tracking
return;
}
}
if ("slaViolation".equals(type)) {
handleSLAViolation();
// no need to pass the event along as it was purely for SLA tracking
return;
}
List<NodeInstance> currentView = new ArrayList<>(this.nodeInstances);
try {
this.activatingNodeIds = new ArrayList<>();
List<EventListener> listeners = eventListeners.get(type);
if (listeners != null) {
for (EventListener listener : listeners) {
listener.signalEvent(type, event);
}
}
listeners = externalEventListeners.get(type);
if (listeners != null) {
for (EventListener listener : listeners) {
listener.signalEvent(type, event);
}
}
if (!type.startsWith("Compensation")) {
for (Node node : getWorkflowProcess().getNodes()) {
if (node instanceof EventNodeInterface && ((EventNodeInterface) node).acceptsEvent(type, event, getResolver(node, currentView))) {
if (node instanceof EventNode && ((EventNode) node).getFrom() == null) {
EventNodeInstance eventNodeInstance = (EventNodeInstance) getNodeInstance(node);
eventNodeInstance.signalEvent(type, event);
} else {
if (node instanceof EventSubProcessNode && (resolveVariables(((EventSubProcessNode) node).getEvents()).contains(type))) {
EventSubProcessNodeInstance eventNodeInstance = (EventSubProcessNodeInstance) getNodeInstance(node);
eventNodeInstance.signalEvent(type, event);
} else {
List<NodeInstance> nodeInstances = getNodeInstances(node.getId(), currentView);
if (nodeInstances != null && !nodeInstances.isEmpty()) {
for (NodeInstance nodeInstance : nodeInstances) {
((EventNodeInstanceInterface) nodeInstance).signalEvent(type, event);
}
}
}
}
} else if (node instanceof StartNode && ((StartNode) node).getTriggers() != null) {
boolean accepted = ((StartNode) node).getTriggers().stream().filter(EventTrigger.class::isInstance).anyMatch(t -> ((EventTrigger) t).getEventFilters().stream().anyMatch(e -> e.acceptsEvent(type, event)));
if (accepted && node.getMetaData().get("acceptStartSignal") != null) {
StartNodeInstance startNodeInstance = (StartNodeInstance) getNodeInstance(node);
startNodeInstance.signalEvent(type, event);
}
}
}
if (((io.automatiko.engine.workflow.process.core.WorkflowProcess) getWorkflowProcess()).isDynamic()) {
for (Node node : getWorkflowProcess().getNodes()) {
if (node.hasMatchingEventListner(type) && node.getIncomingConnections().isEmpty()) {
NodeInstance nodeInstance = getNodeInstance(node);
if (nodeInstance != null) {
if (event != null) {
Map<String, Object> dynamicParams = new HashMap<>(getVariables());
if (event instanceof Map) {
dynamicParams.putAll((Map<String, Object>) event);
} else if (event instanceof WorkflowProcessInstance) {
// ignore variables of process instance type
} else {
dynamicParams.put("Data", event);
}
nodeInstance.setDynamicParameters(dynamicParams);
}
nodeInstance.trigger(null, io.automatiko.engine.workflow.process.core.Node.CONNECTION_DEFAULT_TYPE);
}
} else if (this instanceof ExecutableProcessInstance && node instanceof CompositeNode) {
Optional<NodeInstance> instance = this.nodeInstances.stream().filter(ni -> ni.getNodeId() == node.getId()).findFirst();
instance.ifPresent(n -> ((CompositeNodeInstance) n).signalEvent(type, event));
}
}
}
}
} finally {
processRuntime.getProcessEventSupport().fireAfterProcessSignaled(type, event, this, processRuntime);
if (this.activatingNodeIds != null) {
this.activatingNodeIds.clear();
this.activatingNodeIds = null;
}
}
}
}
Aggregations