Search in sources :

Example 61 with Instance

use of org.wso2.carbon.bpel.core.ode.integration.jmx.Instance in project carbon-business-process by wso2.

the class ProcessStatisticsService method taskVariationOverTime.

/**
 * Task variation of user over time i.e. tasks started and completed by the user -- User Performance
 *
 * @param assignee taskAssignee/User selected to view the user performance of task completion over time
 * @return array with the tasks started and completed of the selected user
 */
@GET
@Path("/user-performance/variation/{assignee}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public ResponseHolder taskVariationOverTime(@PathParam("assignee") String assignee) throws UserStoreException {
    if (!validateCurrentUser(assignee)) {
        throw new ActivitiObjectNotFoundException("User with user id " + assignee + "not defined in the system");
    }
    ResponseHolder response = new ResponseHolder();
    List list = new ArrayList();
    SimpleDateFormat ft = new SimpleDateFormat("M");
    ProcessInstanceStatInfo[] taskStatPerMonths = new ProcessInstanceStatInfo[12];
    for (int i = 0; i < taskStatPerMonths.length; i++) {
        taskStatPerMonths[i] = new ProcessInstanceStatInfo(MONTHS[i], 0, 0);
    }
    // Get completed tasks
    List<HistoricTaskInstance> taskList = BPMNOSGIService.getHistoryService().createHistoricTaskInstanceQuery().taskTenantId(getTenantIdStr()).taskAssignee(assignee).finished().list();
    for (HistoricTaskInstance instance : taskList) {
        int startTime = Integer.parseInt(ft.format(instance.getCreateTime()));
        int endTime = Integer.parseInt(ft.format(instance.getEndTime()));
        taskStatPerMonths[startTime - 1].setInstancesStarted(taskStatPerMonths[startTime - 1].getInstancesStarted() + 1);
        taskStatPerMonths[endTime - 1].setInstancesCompleted(taskStatPerMonths[endTime - 1].getInstancesCompleted() + 1);
    }
    // Get active/started tasks
    List<Task> taskActive = BPMNOSGIService.getTaskService().createTaskQuery().taskTenantId(getTenantIdStr()).taskAssignee(assignee).active().list();
    for (Task instance : taskActive) {
        int startTime = Integer.parseInt(ft.format(instance.getCreateTime()));
        taskStatPerMonths[startTime - 1].setInstancesStarted(taskStatPerMonths[startTime - 1].getInstancesStarted() + 1);
    }
    // Get suspended tasks
    List<Task> taskSuspended = BPMNOSGIService.getTaskService().createTaskQuery().taskTenantId(getTenantIdStr()).taskAssignee(assignee).suspended().list();
    for (Task instance : taskSuspended) {
        int startTime = Integer.parseInt(ft.format(instance.getCreateTime()));
        taskStatPerMonths[startTime - 1].setInstancesStarted(taskStatPerMonths[startTime - 1].getInstancesStarted() + 1);
    }
    for (int i = 0; i < taskStatPerMonths.length; i++) {
        list.add(taskStatPerMonths[i]);
    }
    response.setData(list);
    return response;
}
Also used : ResponseHolder(org.wso2.carbon.bpmn.rest.model.stats.ResponseHolder) Task(org.activiti.engine.task.Task) HistoricTaskInstance(org.activiti.engine.history.HistoricTaskInstance) ProcessInstanceStatInfo(org.wso2.carbon.bpmn.rest.model.stats.ProcessInstanceStatInfo) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) ActivitiObjectNotFoundException(org.activiti.engine.ActivitiObjectNotFoundException) SimpleDateFormat(java.text.SimpleDateFormat) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 62 with Instance

use of org.wso2.carbon.bpel.core.ode.integration.jmx.Instance in project carbon-business-process by wso2.

the class ProcessStatisticsService method getAvgTimeDurationForCompletedProcesses.

/**
 * Get the average time duration of completed processes
 *
 * @return list with the completed processes and the average time duration taken for each process
 */
@GET
@Path("/process-instances/duration/average")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public ResponseHolder getAvgTimeDurationForCompletedProcesses() {
    ResponseHolder response = new ResponseHolder();
    List<Object> list = new ArrayList<>();
    HistoryService historyService = BPMNOSGIService.getHistoryService();
    RepositoryService repositoryService = BPMNOSGIService.getRepositoryService();
    List<ProcessDefinition> deployedProcessList = repositoryService.createProcessDefinitionQuery().processDefinitionTenantId(getTenantIdStr()).list();
    for (ProcessDefinition instance : deployedProcessList) {
        ProcessInstanceAverageInfo bpmnProcessInstance = new ProcessInstanceAverageInfo();
        bpmnProcessInstance.setProcessDefinitionId(instance.getId());
        double totalTime = 0;
        double averageTime;
        String processDefinitionID = instance.getId();
        HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery().processInstanceTenantId(getTenantIdStr()).processDefinitionId(processDefinitionID).finished();
        long instanceCount = historicProcessInstanceQuery.count();
        if (instanceCount != 0) {
            List<HistoricProcessInstance> instanceList = historicProcessInstanceQuery.list();
            for (HistoricProcessInstance completedProcess : instanceList) {
                double timeDurationOfTask = completedProcess.getDurationInMillis();
                double timeInMins = timeDurationOfTask / (1000 * 60);
                totalTime += timeInMins;
            }
            averageTime = totalTime / instanceCount;
            bpmnProcessInstance.setAverageTimeForCompletion(averageTime);
            list.add(bpmnProcessInstance);
        }
    }
    response.setData(list);
    return response;
}
Also used : HistoricProcessInstanceQuery(org.activiti.engine.history.HistoricProcessInstanceQuery) HistoricProcessInstance(org.activiti.engine.history.HistoricProcessInstance) ArrayList(java.util.ArrayList) HistoryService(org.activiti.engine.HistoryService) ProcessDefinition(org.activiti.engine.repository.ProcessDefinition) ResponseHolder(org.wso2.carbon.bpmn.rest.model.stats.ResponseHolder) ProcessInstanceAverageInfo(org.wso2.carbon.bpmn.rest.model.stats.ProcessInstanceAverageInfo) RepositoryService(org.activiti.engine.RepositoryService) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 63 with Instance

use of org.wso2.carbon.bpel.core.ode.integration.jmx.Instance in project carbon-business-process by wso2.

the class WorkflowTaskService method deleteTask.

@DELETE
@Path("/{taskId}")
public Response deleteTask(@PathParam("taskId") String taskId) {
    Boolean cascadeHistory = false;
    if (uriInfo.getQueryParameters().getFirst("cascadeHistory") != null) {
        cascadeHistory = Boolean.valueOf(uriInfo.getQueryParameters().getFirst("cascadeHistory"));
    }
    String deleteReason = uriInfo.getQueryParameters().getFirst("deleteReason");
    Task taskToDelete = getTaskFromRequest(taskId);
    if (taskToDelete.getExecutionId() != null) {
        // Can't delete a task that is part of a process instance
        throw new BPMNForbiddenException("Cannot delete a task that is part of a process-instance.");
    }
    TaskService taskService = BPMNOSGIService.getTaskService();
    if (cascadeHistory != null) {
        // Ignore delete-reason since the task-history (where the reason is recorded) will be deleted anyway
        taskService.deleteTask(taskToDelete.getId(), cascadeHistory);
    } else {
        // Delete with delete-reason
        taskService.deleteTask(taskToDelete.getId(), deleteReason);
    }
    return Response.ok().status(Response.Status.NO_CONTENT).build();
}
Also used : BaseTaskService(org.wso2.carbon.bpmn.rest.service.base.BaseTaskService) BPMNForbiddenException(org.wso2.carbon.bpmn.rest.common.exception.BPMNForbiddenException)

Example 64 with Instance

use of org.wso2.carbon.bpel.core.ode.integration.jmx.Instance in project carbon-business-process by wso2.

the class WorkflowTaskService method createTaskVariable.

@POST
@Path("/{taskId}/variables")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response createTaskVariable(@PathParam("taskId") String taskId, @Context HttpServletRequest httpServletRequest) {
    Task task = getTaskFromRequest(taskId);
    List<RestVariable> inputVariables = new ArrayList<>();
    List<RestVariable> resultVariables = new ArrayList<>();
    Response.ResponseBuilder responseBuilder = Response.ok();
    try {
        if (Utils.isApplicationJsonRequest(httpServletRequest)) {
            try {
                @SuppressWarnings("unchecked") List<Object> variableObjects = (List<Object>) new ObjectMapper().readValue(httpServletRequest.getInputStream(), List.class);
                for (Object restObject : variableObjects) {
                    RestVariable restVariable = new ObjectMapper().convertValue(restObject, RestVariable.class);
                    inputVariables.add(restVariable);
                }
            } catch (IOException e) {
                throw new ActivitiIllegalArgumentException("request body could not be transformed to a RestVariable " + "instance.", e);
            }
        } else if (Utils.isApplicationXmlRequest(httpServletRequest)) {
            JAXBContext jaxbContext = null;
            try {
                jaxbContext = JAXBContext.newInstance(RestVariableCollection.class);
                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                RestVariableCollection restVariableCollection = (RestVariableCollection) jaxbUnmarshaller.unmarshal(getXMLReader(httpServletRequest.getInputStream()));
                if (restVariableCollection == null) {
                    throw new ActivitiIllegalArgumentException("xml request body could not be transformed to a " + "RestVariable Collection instance.");
                }
                List<RestVariable> restVariableList = restVariableCollection.getRestVariables();
                if (restVariableList.size() == 0) {
                    throw new ActivitiIllegalArgumentException("xml request body could not identify any rest " + "variables to be updated");
                }
                for (RestVariable restVariable : restVariableList) {
                    inputVariables.add(restVariable);
                }
            } catch (JAXBException | IOException e) {
                throw new ActivitiIllegalArgumentException("xml request body could not be transformed to a " + "RestVariable instance.", e);
            }
        }
    } catch (Exception e) {
        throw new ActivitiIllegalArgumentException("Failed to serialize to a RestVariable instance", e);
    }
    if (inputVariables.size() == 0) {
        throw new ActivitiIllegalArgumentException("Request didn't contain a list of variables to create.");
    }
    RestVariable.RestVariableScope sharedScope = null;
    RestVariable.RestVariableScope varScope = null;
    Map<String, Object> variablesToSet = new HashMap<>();
    RestResponseFactory restResponseFactory = new RestResponseFactory();
    for (RestVariable var : inputVariables) {
        // Validate if scopes match
        varScope = var.getVariableScope();
        if (var.getName() == null) {
            throw new ActivitiIllegalArgumentException("Variable name is required");
        }
        if (varScope == null) {
            varScope = RestVariable.RestVariableScope.LOCAL;
        }
        if (sharedScope == null) {
            sharedScope = varScope;
        }
        if (varScope != sharedScope) {
            throw new ActivitiIllegalArgumentException("Only allowed to update multiple variables in the same scope.");
        }
        if (hasVariableOnScope(task, var.getName(), varScope)) {
            throw new BPMNConflictException("Variable '" + var.getName() + "' is already present on task '" + task.getId() + "'.");
        }
        Object actualVariableValue = restResponseFactory.getVariableValue(var);
        variablesToSet.put(var.getName(), actualVariableValue);
        resultVariables.add(restResponseFactory.createRestVariable(var.getName(), actualVariableValue, varScope, task.getId(), RestResponseFactory.VARIABLE_TASK, false, uriInfo.getBaseUri().toString()));
    }
    RuntimeService runtimeService = BPMNOSGIService.getRuntimeService();
    TaskService taskService = BPMNOSGIService.getTaskService();
    if (!variablesToSet.isEmpty()) {
        if (sharedScope == RestVariable.RestVariableScope.LOCAL) {
            taskService.setVariablesLocal(task.getId(), variablesToSet);
        } else {
            if (task.getExecutionId() != null) {
                // Explicitly set on execution, setting non-local variables on task will override local-variables if exists
                runtimeService.setVariables(task.getExecutionId(), variablesToSet);
            } else {
                // Standalone task, no global variables possible
                throw new ActivitiIllegalArgumentException("Cannot set global variables on task '" + task.getId() + "', task is not part of process.");
            }
        }
    }
    RestVariableCollection restVariableCollection = new RestVariableCollection();
    restVariableCollection.setRestVariables(resultVariables);
    responseBuilder.entity(restVariableCollection);
    return responseBuilder.status(Response.Status.CREATED).build();
}
Also used : BPMNConflictException(org.wso2.carbon.bpmn.rest.common.exception.BPMNConflictException) JAXBContext(javax.xml.bind.JAXBContext) RestVariable(org.wso2.carbon.bpmn.rest.engine.variable.RestVariable) Unmarshaller(javax.xml.bind.Unmarshaller) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) RestResponseFactory(org.wso2.carbon.bpmn.rest.common.RestResponseFactory) BaseTaskService(org.wso2.carbon.bpmn.rest.service.base.BaseTaskService) XMLStreamException(javax.xml.stream.XMLStreamException) BPMNForbiddenException(org.wso2.carbon.bpmn.rest.common.exception.BPMNForbiddenException) BPMNConflictException(org.wso2.carbon.bpmn.rest.common.exception.BPMNConflictException) JAXBException(javax.xml.bind.JAXBException) DataResponse(org.wso2.carbon.bpmn.rest.model.common.DataResponse) Response(javax.ws.rs.core.Response)

Example 65 with Instance

use of org.wso2.carbon.bpel.core.ode.integration.jmx.Instance in project carbon-business-process by wso2.

the class WorkflowTaskService method createTask.

/**
 * Create a new task instance for a process instance.
 * @param taskRequest
 * @return
 */
@POST
@Path("/")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response createTask(TaskRequest taskRequest) {
    TaskService taskService = BPMNOSGIService.getTaskService();
    Task task = taskService.newTask();
    // Populate the task properties based on the request
    populateTaskFromRequest(task, taskRequest);
    if (taskRequest.isTenantIdSet()) {
        ((TaskEntity) task).setTenantId(taskRequest.getTenantId());
    }
    taskService.saveTask(task);
    return Response.ok().entity(new RestResponseFactory().createTaskResponse(task, uriInfo.getBaseUri().toString())).build();
}
Also used : TaskEntity(org.activiti.engine.impl.persistence.entity.TaskEntity) RestResponseFactory(org.wso2.carbon.bpmn.rest.common.RestResponseFactory) BaseTaskService(org.wso2.carbon.bpmn.rest.service.base.BaseTaskService)

Aggregations

ArrayList (java.util.ArrayList)28 Test (org.junit.Test)23 Response (javax.ws.rs.core.Response)22 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)21 APIManagerFactory (org.wso2.carbon.apimgt.core.impl.APIManagerFactory)20 HashMap (java.util.HashMap)15 Path (javax.ws.rs.Path)15 RuntimeService (org.activiti.engine.RuntimeService)15 HistoricProcessInstance (org.activiti.engine.history.HistoricProcessInstance)15 InstanceManagementException (org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.InstanceManagementException)14 Produces (javax.ws.rs.Produces)13 RestResponseFactory (org.wso2.carbon.bpmn.rest.common.RestResponseFactory)13 IOException (java.io.IOException)12 APIMgtAdminServiceImpl (org.wso2.carbon.apimgt.core.impl.APIMgtAdminServiceImpl)12 GET (javax.ws.rs.GET)11 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)11 ActivitiObjectNotFoundException (org.activiti.engine.ActivitiObjectNotFoundException)10 ProcessInstance (org.activiti.engine.runtime.ProcessInstance)9 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)9 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)8