Search in sources :

Example 1 with AbstractProcess

use of io.automatiko.engine.workflow.AbstractProcess in project automatiko-engine by automatiko-io.

the class ProcessInstanceMarshaller method unmarshallReadOnlyProcessInstance.

@SuppressWarnings({ "rawtypes", "unchecked" })
public ProcessInstance unmarshallReadOnlyProcessInstance(byte[] data, Process process) {
    WorkflowProcessInstance wpi = unmarshallWorkflowProcessInstance(data, process);
    Model model = ((AbstractProcess) process).createModel();
    model.fromMap(wpi.getVariables());
    return ((AbstractProcess) process).createReadOnlyInstance(wpi, model);
}
Also used : AbstractProcess(io.automatiko.engine.workflow.AbstractProcess) Model(io.automatiko.engine.api.Model) WorkflowProcessInstance(io.automatiko.engine.api.runtime.process.WorkflowProcessInstance)

Example 2 with AbstractProcess

use of io.automatiko.engine.workflow.AbstractProcess in project automatiko-engine by automatiko-io.

the class ProcessInstanceMarshaller method importWorkflowProcessInstance.

public WorkflowProcessInstance importWorkflowProcessInstance(String header, String data, List<Map<String, String>> timers, Process<?> process) {
    Map<String, io.automatiko.engine.api.definition.process.Process> processes = new HashMap<String, io.automatiko.engine.api.definition.process.Process>();
    io.automatiko.engine.api.definition.process.Process p = ((AbstractProcess<?>) process).process();
    // this can include version number in the id
    processes.put(process.id(), p);
    // this is raw process id as defined in bpmn or so
    processes.put(p.getId(), p);
    try (ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0])) {
        Map<String, Object> localEnv = new HashMap<String, Object>(env);
        localEnv.put("_import_", true);
        localEnv.put("_services_", ((AbstractProcess<?>) process).services());
        AutomatikoMessages.ProcessInstance.Builder builder = AutomatikoMessages.ProcessInstance.newBuilder();
        JsonFormat.parser().merge(data, builder);
        AutomatikoMessages.Header.Builder headerBuilder = AutomatikoMessages.Header.newBuilder();
        JsonFormat.parser().merge(header, headerBuilder);
        MarshallerReaderContext context = new MarshallerReaderContext(bais, null, processes, localEnv) {

            @Override
            protected void readStreamHeader() throws IOException, StreamCorruptedException {
            }
        };
        context.parameterObject = builder.build();
        PersisterHelper.loadStrategiesIndex(context, headerBuilder.build());
        io.automatiko.engine.workflow.marshalling.impl.ProcessInstanceMarshaller marshaller = ProcessMarshallerRegistry.INSTANCE.getMarshaller(builder.getProcessType());
        WorkflowProcessInstance pi = (WorkflowProcessInstance) marshaller.readProcessInstance(context);
        context.close();
        return pi;
    } catch (Exception e) {
        throw new RuntimeException("Error while unmarshalling process instance", e);
    }
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Process(io.automatiko.engine.api.workflow.Process) AbstractProcess(io.automatiko.engine.workflow.AbstractProcess) MarshallerReaderContext(io.automatiko.engine.workflow.marshalling.impl.MarshallerReaderContext) AbstractProcess(io.automatiko.engine.workflow.AbstractProcess) StreamCorruptedException(java.io.StreamCorruptedException) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) AbstractProcessInstance(io.automatiko.engine.workflow.AbstractProcessInstance) WorkflowProcessInstance(io.automatiko.engine.api.runtime.process.WorkflowProcessInstance) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) StringExportedProcessInstance(io.automatiko.engine.workflow.StringExportedProcessInstance) ExportedProcessInstance(io.automatiko.engine.api.workflow.ExportedProcessInstance) WorkflowProcessInstance(io.automatiko.engine.api.runtime.process.WorkflowProcessInstance)

Example 3 with AbstractProcess

use of io.automatiko.engine.workflow.AbstractProcess in project automatiko-engine by automatiko-io.

the class ProcessInstanceMarshaller method importProcessInstance.

@SuppressWarnings({ "rawtypes", "unchecked" })
public ProcessInstance importProcessInstance(ExportedProcessInstance<?> instance, Process process) {
    List<Map<String, String>> timers = instance.convertTimers();
    WorkflowProcessInstance wpi = importWorkflowProcessInstance((String) instance.getHeader(), (String) instance.getInstance(), timers, process);
    Model model = ((AbstractProcess) process).createModel();
    model.fromMap(wpi.getVariables());
    ProcessInstance processInstance = ((AbstractProcess) process).createInstance(wpi, model, 1);
    if (timers != null && !timers.isEmpty()) {
        String parentProcessInstanceId = wpi.getParentProcessInstanceId();
        if (parentProcessInstanceId != null && !parentProcessInstanceId.isEmpty()) {
            parentProcessInstanceId += ":";
        } else {
            parentProcessInstanceId = "";
        }
        JobsService jobService = ((WorkflowProcessInstanceImpl) wpi).getProcessRuntime().getJobsService();
        Collection<io.automatiko.engine.workflow.process.instance.NodeInstance> nodes = ((WorkflowProcessInstanceImpl) wpi).getNodeInstances(true);
        // keeps iterator for statebased node instance timers
        Map<String, Iterator<Timer>> nodeInstanceTimers = new LinkedHashMap<>();
        for (Map<String, String> timer : timers) {
            String nodeInstanceId = timer.get("nodeInstanceId");
            for (io.automatiko.engine.workflow.process.instance.NodeInstance ni : nodes) {
                if (ni.getId().equals(nodeInstanceId)) {
                    ExpirationTime expirationTime = null;
                    long timerNodeId = 0;
                    if (((NodeInstanceImpl) ni).getRetryJobId() != null && ((NodeInstanceImpl) ni).getRetryJobId().equals(timer.get("timerId"))) {
                        jobService.scheduleProcessInstanceJob(ProcessInstanceJobDescription.of(timer.get("timerId"), ni.getNodeId(), "retry:" + ni.getId(), expirationTime, ((NodeInstanceImpl) ni).getProcessInstanceIdWithParent(), ni.getProcessInstance().getRootProcessInstanceId(), ni.getProcessInstance().getProcessId(), ni.getProcessInstance().getProcess().getVersion(), ni.getProcessInstance().getRootProcessId()));
                        break;
                    } else if (ni instanceof TimerNodeInstance) {
                        TimerNodeInstance nodeInstance = (TimerNodeInstance) ni;
                        timerNodeId = nodeInstance.getTimerNode().getTimer().getId();
                        expirationTime = nodeInstance.createTimerInstance(nodeInstance.getTimerNode().getTimer());
                        expirationTime.reset(ZonedDateTime.parse(timer.get("scheduledAt")));
                    } else if (ni instanceof StateBasedNodeInstance) {
                        StateBasedNodeInstance nodeInstance = (StateBasedNodeInstance) ni;
                        if (nodeInstance.getTimerInstances().contains(timer.get("timerId"))) {
                            Iterator<Timer> it = nodeInstanceTimers.computeIfAbsent(nodeInstanceId, k -> nodeInstance.getEventBasedNode().getTimers().keySet().iterator());
                            expirationTime = nodeInstance.createTimerInstance(it.next());
                            expirationTime.reset(ZonedDateTime.parse(timer.get("scheduledAt")));
                        }
                    }
                    // lastly schedule timer on calculated expiration time
                    jobService.scheduleProcessInstanceJob(ProcessInstanceJobDescription.of(timer.get("timerId"), timerNodeId, expirationTime, ((NodeInstanceImpl) ni).getProcessInstanceIdWithParent(), wpi.getRootProcessInstanceId(), wpi.getProcessId(), wpi.getProcess().getVersion(), wpi.getRootProcessId()));
                    break;
                }
            }
        }
    }
    return processInstance;
}
Also used : WorkflowProcessInstanceImpl(io.automatiko.engine.workflow.process.instance.impl.WorkflowProcessInstanceImpl) ExpirationTime(io.automatiko.engine.api.jobs.ExpirationTime) LinkedHashMap(java.util.LinkedHashMap) JobsService(io.automatiko.engine.api.jobs.JobsService) Iterator(java.util.Iterator) NodeInstanceImpl(io.automatiko.engine.workflow.process.instance.impl.NodeInstanceImpl) StateBasedNodeInstance(io.automatiko.engine.workflow.process.instance.node.StateBasedNodeInstance) AbstractProcess(io.automatiko.engine.workflow.AbstractProcess) Timer(io.automatiko.engine.workflow.base.core.timer.Timer) Model(io.automatiko.engine.api.Model) AbstractProcessInstance(io.automatiko.engine.workflow.AbstractProcessInstance) WorkflowProcessInstance(io.automatiko.engine.api.runtime.process.WorkflowProcessInstance) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) StringExportedProcessInstance(io.automatiko.engine.workflow.StringExportedProcessInstance) ExportedProcessInstance(io.automatiko.engine.api.workflow.ExportedProcessInstance) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) 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) WorkflowProcessInstance(io.automatiko.engine.api.runtime.process.WorkflowProcessInstance)

Example 4 with AbstractProcess

use of io.automatiko.engine.workflow.AbstractProcess in project automatiko-engine by automatiko-io.

the class ProcessInstanceManagementResource method getInstance.

@APIResponses(value = { @APIResponse(responseCode = "404", description = "In case of instance with given id was not found", content = @Content(mediaType = "application/json")), @APIResponse(responseCode = "200", description = "Process instance details", content = @Content(mediaType = "application/json")) })
@Operation(summary = "Returns process instance details for given instance id")
@SuppressWarnings("unchecked")
@GET
@Path("/{processId}/instances/{instanceId}")
@Produces(MediaType.APPLICATION_JSON)
public ProcessInstanceDetailsDTO getInstance(@Context UriInfo uriInfo, @Parameter(description = "Unique identifier of the process", required = true) @PathParam("processId") String processId, @Parameter(description = "Unique identifier of the instance", required = true) @PathParam("instanceId") String instanceId, @Parameter(description = "Status of the process instance", required = false, schema = @Schema(enumeration = { "active", "completed", "aborted", "error" })) @QueryParam("status") @DefaultValue("active") final String status, @Parameter(description = "User identifier as alternative autroization info", required = false, hidden = true) @QueryParam("user") final String user, @Parameter(description = "Groups as alternative autroization info", required = false, hidden = true) @QueryParam("group") final List<String> groups) {
    try {
        identitySupplier.buildIdentityProvider(user, groups);
        return UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
            Process<?> process = processData.get(processId);
            Optional<ProcessInstance<?>> instance = (Optional<ProcessInstance<?>>) process.instances().findById(instanceId, mapStatus(status), ProcessInstanceReadMode.READ_ONLY);
            if (instance.isEmpty()) {
                throw new ProcessInstanceNotFoundException(instanceId);
            }
            ProcessInstance<?> pi = instance.get();
            ProcessInstanceDetailsDTO details = new ProcessInstanceDetailsDTO();
            String id = pi.id();
            if (pi.parentProcessInstanceId() != null) {
                id = pi.parentProcessInstanceId() + ":" + id;
            }
            details.setId(id);
            details.setProcessId(processId);
            details.setBusinessKey(pi.businessKey() == null ? "" : pi.businessKey());
            details.setDescription(pi.description());
            details.setState(pi.status());
            details.setFailed(pi.errors().isPresent());
            if (pi.errors().isPresent()) {
                details.setErrors(pi.errors().get().errors().stream().map(e -> new ErrorInfoDTO(e.failedNodeId(), e.errorId(), e.errorMessage(), e.errorDetails())).collect(Collectors.toList()));
            }
            details.setImage(uriInfo.getBaseUri().toString() + "management/processes/" + processId + "/instances/" + instanceId + "/image?status=" + reverseMapStatus(pi.status()));
            details.setTags(pi.tags().values());
            details.setVariables(pi.variables());
            details.setSubprocesses(pi.subprocesses().stream().map(spi -> new ProcessInstanceDTO(spi.id(), spi.businessKey(), spi.description(), spi.tags().values(), spi.errors().isPresent(), spi.process().id(), spi.status())).collect(Collectors.toList()));
            VariableScope variableScope = (VariableScope) ((ContextContainer) ((AbstractProcess<?>) process).process()).getDefaultContext(VariableScope.VARIABLE_SCOPE);
            details.setVersionedVariables(variableScope.getVariables().stream().filter(v -> v.hasTag(Variable.VERSIONED_TAG)).map(v -> v.getName()).collect(Collectors.toList()));
            return details;
        });
    } finally {
        IdentityProvider.set(null);
    }
}
Also used : Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) ProcessInstanceExporter(io.automatiko.engine.addons.process.management.export.ProcessInstanceExporter) MediaType(javax.ws.rs.core.MediaType) Application(io.automatiko.engine.api.Application) QueryParam(javax.ws.rs.QueryParam) ProcessImageNotFoundException(io.automatiko.engine.api.workflow.ProcessImageNotFoundException) ContextContainer(io.automatiko.engine.workflow.base.core.ContextContainer) SchemaType(org.eclipse.microprofile.openapi.annotations.enums.SchemaType) VariableNotFoundException(io.automatiko.engine.api.workflow.VariableNotFoundException) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) Instance(javax.enterprise.inject.Instance) DELETE(javax.ws.rs.DELETE) JsonExportedProcessInstance(io.automatiko.engine.addons.process.management.model.JsonExportedProcessInstance) IoUtils(io.automatiko.engine.services.utils.IoUtils) Context(javax.ws.rs.core.Context) Model(io.automatiko.engine.api.Model) IdentityProvider(io.automatiko.engine.api.auth.IdentityProvider) Operation(org.eclipse.microprofile.openapi.annotations.Operation) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) VariableScope(io.automatiko.engine.workflow.base.core.context.variable.VariableScope) Collectors(java.util.stream.Collectors) List(java.util.List) Response(javax.ws.rs.core.Response) Parameter(org.eclipse.microprofile.openapi.annotations.parameters.Parameter) ProcessInstanceDTO(io.automatiko.engine.addons.process.management.model.ProcessInstanceDTO) ProcessInstanceReadMode(io.automatiko.engine.api.workflow.ProcessInstanceReadMode) Optional(java.util.Optional) Tag(org.eclipse.microprofile.openapi.annotations.tags.Tag) Variable(io.automatiko.engine.workflow.base.core.context.variable.Variable) UriInfo(javax.ws.rs.core.UriInfo) ProcessInstanceNotFoundException(io.automatiko.engine.api.workflow.ProcessInstanceNotFoundException) PathParam(javax.ws.rs.PathParam) AbstractProcessInstance(io.automatiko.engine.workflow.AbstractProcessInstance) ByteArrayOutputStream(java.io.ByteArrayOutputStream) GET(javax.ws.rs.GET) ProcessInstanceDetailsDTO(io.automatiko.engine.addons.process.management.model.ProcessInstanceDetailsDTO) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) ArchivedProcessInstance(io.automatiko.engine.api.workflow.ArchivedProcessInstance) JsonArchiveBuilder(io.automatiko.engine.workflow.json.JsonArchiveBuilder) IdentitySupplier(io.automatiko.engine.api.auth.IdentitySupplier) ErrorInfoDTO(io.automatiko.engine.addons.process.management.model.ErrorInfoDTO) WorkflowProcess(io.automatiko.engine.workflow.process.core.WorkflowProcess) Process(io.automatiko.engine.api.workflow.Process) ProcessDTO(io.automatiko.engine.addons.process.management.model.ProcessDTO) Content(org.eclipse.microprofile.openapi.annotations.media.Content) AbstractProcess(io.automatiko.engine.workflow.AbstractProcess) Status(javax.ws.rs.core.Response.Status) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) UnitOfWorkExecutor(io.automatiko.engine.services.uow.UnitOfWorkExecutor) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) Schema(org.eclipse.microprofile.openapi.annotations.media.Schema) IOException(java.io.IOException) ExternalDocumentation(org.eclipse.microprofile.openapi.annotations.ExternalDocumentation) APIResponses(org.eclipse.microprofile.openapi.annotations.responses.APIResponses) Collections(java.util.Collections) ProcessInstanceDetailsDTO(io.automatiko.engine.addons.process.management.model.ProcessInstanceDetailsDTO) Optional(java.util.Optional) ErrorInfoDTO(io.automatiko.engine.addons.process.management.model.ErrorInfoDTO) AbstractProcess(io.automatiko.engine.workflow.AbstractProcess) ProcessInstanceDTO(io.automatiko.engine.addons.process.management.model.ProcessInstanceDTO) ProcessInstanceNotFoundException(io.automatiko.engine.api.workflow.ProcessInstanceNotFoundException) JsonExportedProcessInstance(io.automatiko.engine.addons.process.management.model.JsonExportedProcessInstance) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) AbstractProcessInstance(io.automatiko.engine.workflow.AbstractProcessInstance) ArchivedProcessInstance(io.automatiko.engine.api.workflow.ArchivedProcessInstance) VariableScope(io.automatiko.engine.workflow.base.core.context.variable.VariableScope) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) APIResponses(org.eclipse.microprofile.openapi.annotations.responses.APIResponses) Operation(org.eclipse.microprofile.openapi.annotations.Operation)

Example 5 with AbstractProcess

use of io.automatiko.engine.workflow.AbstractProcess in project automatiko-engine by automatiko-io.

the class ProcessInstanceMarshaller method unmarshallWorkflowProcessInstance.

public WorkflowProcessInstance unmarshallWorkflowProcessInstance(byte[] data, Process<?> process) {
    Map<String, io.automatiko.engine.api.definition.process.Process> processes = new HashMap<String, io.automatiko.engine.api.definition.process.Process>();
    io.automatiko.engine.api.definition.process.Process p = ((AbstractProcess<?>) process).process();
    // this can include version number in the id
    processes.put(process.id(), p);
    // this is raw process id as defined in bpmn or so
    processes.put(p.getId(), p);
    try (ByteArrayInputStream bais = new ByteArrayInputStream(data)) {
        MarshallerReaderContext context = new MarshallerReaderContext(bais, null, processes, this.env);
        ObjectInputStream stream = context.stream;
        String processInstanceType = stream.readUTF();
        io.automatiko.engine.workflow.marshalling.impl.ProcessInstanceMarshaller marshaller = ProcessMarshallerRegistry.INSTANCE.getMarshaller(processInstanceType);
        WorkflowProcessInstance pi = (WorkflowProcessInstance) marshaller.readProcessInstance(context);
        context.close();
        return pi;
    } catch (Exception e) {
        throw new RuntimeException("Error while unmarshalling process instance", e);
    }
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) AbstractProcess(io.automatiko.engine.workflow.AbstractProcess) Process(io.automatiko.engine.api.workflow.Process) AbstractProcess(io.automatiko.engine.workflow.AbstractProcess) StreamCorruptedException(java.io.StreamCorruptedException) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) MarshallerReaderContext(io.automatiko.engine.workflow.marshalling.impl.MarshallerReaderContext) WorkflowProcessInstance(io.automatiko.engine.api.runtime.process.WorkflowProcessInstance) ObjectInputStream(java.io.ObjectInputStream)

Aggregations

AbstractProcess (io.automatiko.engine.workflow.AbstractProcess)7 Model (io.automatiko.engine.api.Model)5 WorkflowProcessInstance (io.automatiko.engine.api.runtime.process.WorkflowProcessInstance)5 Process (io.automatiko.engine.api.workflow.Process)4 ProcessInstance (io.automatiko.engine.api.workflow.ProcessInstance)4 AbstractProcessInstance (io.automatiko.engine.workflow.AbstractProcessInstance)4 IOException (java.io.IOException)4 HashMap (java.util.HashMap)3 LinkedHashMap (java.util.LinkedHashMap)3 Map (java.util.Map)3 ProcessInstanceExporter (io.automatiko.engine.addons.process.management.export.ProcessInstanceExporter)2 ErrorInfoDTO (io.automatiko.engine.addons.process.management.model.ErrorInfoDTO)2 JsonExportedProcessInstance (io.automatiko.engine.addons.process.management.model.JsonExportedProcessInstance)2 ProcessDTO (io.automatiko.engine.addons.process.management.model.ProcessDTO)2 ProcessInstanceDTO (io.automatiko.engine.addons.process.management.model.ProcessInstanceDTO)2 ProcessInstanceDetailsDTO (io.automatiko.engine.addons.process.management.model.ProcessInstanceDetailsDTO)2 Application (io.automatiko.engine.api.Application)2 IdentityProvider (io.automatiko.engine.api.auth.IdentityProvider)2 IdentitySupplier (io.automatiko.engine.api.auth.IdentitySupplier)2 ArchivedProcessInstance (io.automatiko.engine.api.workflow.ArchivedProcessInstance)2