Search in sources :

Example 21 with Complete

use of org.wso2.carbon.humantask.core.engine.commands.Complete in project carbon-business-process by wso2.

the class ProcessStatisticsService method avgTaskTimeDurationForCompletedProcesses.

/**
 * Average task duration for completed processes
 *
 * @param pId processDefintionId of the process selected to view the average time duration for each task
 * @return list of completed tasks with the average time duration for the selected process
 */
@GET
@Path("/task-instances/duration/avarage/{pid}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public ResponseHolder avgTaskTimeDurationForCompletedProcesses(@PathParam("pid") String pId) {
    RepositoryService repositoryService = BPMNOSGIService.getRepositoryService();
    HistoryService historyService = BPMNOSGIService.getHistoryService();
    long processCount = repositoryService.createProcessDefinitionQuery().processDefinitionTenantId(getTenantIdStr()).processDefinitionId(pId).count();
    if (processCount == 0) {
        throw new ActivitiObjectNotFoundException("Count not find a matching process with PID '" + pId + "'.");
    }
    ResponseHolder response = new ResponseHolder();
    List<Object> taskListForProcess = new ArrayList<>();
    HashMap<String, Long> map = new HashMap<>();
    // Get the number of completed/finished process instance for each process definition
    HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery().processInstanceTenantId(getTenantIdStr()).processDefinitionId(pId).finished();
    // Get the count of the complete process instances
    long noOfHistoricInstances = historicProcessInstanceQuery.count();
    // If the deployed process does not have any completed process instances --> Ignore
    if (noOfHistoricInstances == 0) {
        response.setData(taskListForProcess);
    } else // If the deployed process has completed process instances --> then
    {
        TaskInstanceAverageInfo tInstance;
        // Get the list of completed tasks/activities in the completed process instance by passing the
        // process definition id of the process
        List<HistoricTaskInstance> taskList = BPMNOSGIService.getHistoryService().createHistoricTaskInstanceQuery().taskTenantId(getTenantIdStr()).processDefinitionId(pId).processFinished().list();
        // Iterate through each completed task/activity and get the task name and duration
        for (HistoricTaskInstance taskInstance : taskList) {
            // Get the task name
            String taskKey = taskInstance.getTaskDefinitionKey();
            // Get the time duration taken for the task to be completed
            long taskDuration = taskInstance.getDurationInMillis();
            if (map.containsKey(taskKey)) {
                long tt = map.get(taskKey);
                map.put(taskKey, taskDuration + tt);
            } else {
                map.put(taskKey, taskDuration);
            }
        // Iterating Task List finished
        }
        Iterator iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next().toString();
            double value = map.get(key) / noOfHistoricInstances;
            tInstance = new TaskInstanceAverageInfo();
            tInstance.setTaskDefinitionKey(key);
            tInstance.setAverageTimeForCompletion(value);
            taskListForProcess.add(tInstance);
        }
        response.setData(taskListForProcess);
    }
    return response;
}
Also used : HistoricTaskInstance(org.activiti.engine.history.HistoricTaskInstance) HistoricProcessInstanceQuery(org.activiti.engine.history.HistoricProcessInstanceQuery) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HistoryService(org.activiti.engine.HistoryService) ActivitiObjectNotFoundException(org.activiti.engine.ActivitiObjectNotFoundException) ResponseHolder(org.wso2.carbon.bpmn.rest.model.stats.ResponseHolder) Iterator(java.util.Iterator) TaskInstanceAverageInfo(org.wso2.carbon.bpmn.rest.model.stats.TaskInstanceAverageInfo) RepositoryService(org.activiti.engine.RepositoryService) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 22 with Complete

use of org.wso2.carbon.humantask.core.engine.commands.Complete in project carbon-business-process by wso2.

the class HumanTaskStore method deploy.

/**
 * Handles the deployment steps for the master node and salve node in the cluster
 * @param humanTaskFile
 * @throws Exception
 */
public void deploy(File humanTaskFile) throws Exception {
    // Currently using the registry read/write mount property to determine whether this node is a master node
    // or a salve node.
    // Handle this properly with hazelcast leader for cluster scenario TODO
    boolean isMasterServer = !isServerReadOnly();
    // Versions of this ht package is already deployed
    boolean isExistingPackage = false;
    // Exactly matching ht package already exists
    boolean isPackageReload = false;
    DeploymentUnitDAO currentlyActiveTaskPackage = null;
    String md5sum = HumanTaskStoreUtils.getMD5Checksum(humanTaskFile);
    String packageName = FilenameUtils.removeExtension(humanTaskFile.getName());
    List<DeploymentUnitDAO> existingDeploymentUnitsForPackage = getExistingDeploymentUnitsForPackage(packageName.trim());
    if (existingDeploymentUnitsForPackage != null && existingDeploymentUnitsForPackage.size() > 0) {
        isExistingPackage = true;
        for (DeploymentUnitDAO dao : existingDeploymentUnitsForPackage) {
            if ((dao.getStatus() == (TaskPackageStatus.ACTIVE))) {
                // extract the currently active task package
                currentlyActiveTaskPackage = dao;
                if (dao.getChecksum().equals(md5sum)) {
                    // Check whether the md5sum matches the active task package.
                    isPackageReload = true;
                }
            }
        }
    }
    // We will only allow writes to db only for the master node to avoid duplicate version creation
    if (isExistingPackage && isPackageReload) {
        // Reload the existing versions of the human task package . No need of creating a new version of the package
        // This could be due to server restart, deployment of the same package or master node has already deployed the
        // new version of the package
        // First check if the currently active task package is already loaded
        String activePackageName = loadedPackages.get(currentlyActiveTaskPackage.getPackageName());
        if (activePackageName != null && activePackageName.equals(currentlyActiveTaskPackage.getName())) {
            if (log.isDebugEnabled()) {
                log.debug("This task package and its previous versions are already loaded " + activePackageName);
            }
            // This task package and its previous versions are already loaded , hence return
            return;
        }
        // Load the existing versions of the package
        reloadExistingTaskVersions(existingDeploymentUnitsForPackage, humanTaskFile, md5sum, isMasterServer);
        return;
    }
    // New version of the package is being deployed on top of the existing version
    if (isExistingPackage && !isPackageReload) {
        if (isMasterServer) {
            // Retire the existing version of the package and deploy the new version
            // This could be two scenarios. Server restart with new version and deploying on existing version.
            String activePackageName = loadedPackages.get(currentlyActiveTaskPackage.getPackageName());
            if (activePackageName == null) {
                // This is a server restart, we need to load existing versions
                reloadExistingTaskVersions(existingDeploymentUnitsForPackage, humanTaskFile, md5sum, isMasterServer);
            }
            long newVersion = getNextVersion();
            HumanTaskDeploymentUnit newDeploymentUnit = createNewDeploymentUnit(humanTaskFile, tenantId, newVersion, md5sum);
            validateTaskConfig(newDeploymentUnit);
            retireTaskPackageConfigurations(currentlyActiveTaskPackage.getName());
            currentlyActiveTaskPackage.setStatus(TaskPackageStatus.RETIRED);
            updateDeploymentUnitDao(currentlyActiveTaskPackage);
            // Retiring of currently active package is complete.
            // Create and deploy new version
            deployNewTaskVersion(newDeploymentUnit, newVersion);
            // Add new version of human task package to registry
            // Update the zip and package properties in the registry
            repository.handleNewHumanTaskPackageAddition(newDeploymentUnit, humanTaskFile);
            // Successfully deployed the packages.
            return;
        } else {
            // Cannot allow creation of a new version from slave nodes, deploy the new version on the master node
            // first to avoid duplicate version creation
            // Write log, issue warning and return
            log.warn("Cannot deploy new version of the task in slave node. Hence deploy the task archive in master" + "node fist");
            return;
        }
    }
    if (!isMasterServer) {
        // Issue warning, write warn message and return as we cannot allow deployment of new versions on slave nodes
        // before deployment of the ht package in the master node
        log.warn("Cannot deploy a new version on the package on the salve node first, " + "Deploy the package on the master node first");
        return;
    }
    // Create new version of deployment unit
    // Process the human task configurations
    // Store deployment unit information to the db
    // Deploy axis2 services
    // Adding HumanTask package the registry.
    long newVersion = getNextVersion();
    HumanTaskDeploymentUnit newDeploymentUnit = createNewDeploymentUnit(humanTaskFile, tenantId, newVersion, md5sum);
    validateTaskConfig(newDeploymentUnit);
    deployNewTaskVersion(newDeploymentUnit, newVersion);
    repository.handleNewHumanTaskPackageAddition(newDeploymentUnit, humanTaskFile);
    return;
}
Also used : DeploymentUnitDAO(org.wso2.carbon.humantask.core.dao.DeploymentUnitDAO) HumanTaskDeploymentUnit(org.wso2.carbon.humantask.core.deployment.HumanTaskDeploymentUnit)

Aggregations

WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)9 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)3 List (java.util.List)3 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)3 GatewayException (org.wso2.carbon.apimgt.core.exception.GatewayException)3 RepositoryService (org.activiti.engine.RepositoryService)2 Element (org.w3c.dom.Element)2 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)2 ContainerBasedGatewayException (org.wso2.carbon.apimgt.core.exception.ContainerBasedGatewayException)2 Application (org.wso2.carbon.apimgt.core.models.Application)2 HumanTaskException (org.wso2.carbon.humantask.core.engine.HumanTaskException)2 Complete (org.wso2.carbon.humantask.core.engine.commands.Complete)2 HazelcastInstance (com.hazelcast.core.HazelcastInstance)1 File (java.io.File)1 IOException (java.io.IOException)1 Files (java.nio.file.Files)1 Paths (java.nio.file.Paths)1 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1