Spring activiti統合レコード

18485 ワード



	
		
		
		
		
		
		
		
		
		
		
	
	
		
	
		 
	
	 
	
	 
	
	
	
	
	
	
	
	
    
        org.activiti
        activiti-engine
        5.22.0
      
      
        org.activiti
        activiti-spring
        5.22.0
      
@Service
public class Process  {
	@Autowired
	ProcessEngine processEngine;
	@Autowired
	ProcessEngineConfiguration processEngineConfiguration;
	@Autowired
	RepositoryService repositoryService;
	@Autowired
	ManagementService managementService;
	@Autowired
	RuntimeService runtimeService;
	@Autowired
	HistoryService historyService;
	@Autowired
	TaskService taskService;
	@Value("${activiti.save.path}")
	private String activitiPath;

	/**
	 *     
	 * 
	 * @param bpmnPath
	 *                   
	 * @param name
	 *                 
	 * @version 0.1.0 2016/12/04
	 * 
	 */
	public Deployment deployClasspathResource(String bpmnPath, String name) {
		/** 1:        ;2:       ;3: classpath      ,          ;4:     */
		Deployment deployment = repositoryService.createDeployment().name(name).addClasspathResource(bpmnPath).deploy();
		return deployment;
	}

	
	public Deployment deployInputStream(InputStream bpmnPath, InputStream pngPath, String name) {
		Deployment deployment = repositoryService.createDeployment().name(name).addInputStream(name + ".bpmn", bpmnPath).addInputStream(name + ".png", pngPath).deploy();
		return deployment;
	}

	
	public Deployment deployString(String bpmnXml, String name) {
		Deployment deployment = repositoryService.createDeployment().name(name).addString(name + ".bpmn", bpmnXml).deploy();
		return deployment;
	}

	/**
	 *       
	 * 
	 * @param id
	 *              id
	 * @param flag
	 *            ture         ;false           false
	 * @version 0.1.0 2016/12/04
	 * 
	 */

	public void deleteProcessDefinition(String id, boolean flag) {
		if (flag) {
			//                
			repositoryService.deleteDeployment(id, flag);
		} else {
			//              ,           
			repositoryService.deleteDeployment(id);//        id   id
		}
	}

	/**
	 *       
	 * 
	 * @param processDefinitionKey
	 *              key
	 * @version 0.1.0 2016/12/04
	 * 
	 */
	
	public ProcessInstance startProessInstance(String processDefinitionKey, String businessKey, Map jsnVariables) throws Exception {
		ProcessInstance processInstance = null;
		if (StringUtils.isNotBlank(businessKey)) {
			if (jsnVariables != null & !jsnVariables.isEmpty()) {
				processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, jsnVariables);
			} else {
				processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey);
			}
		} else {
			if (jsnVariables != null & !jsnVariables.isEmpty()) {
				processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, jsnVariables);
			} else {
				processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey);
			}
		}
		return processInstance;
	}

	/**
	 *       
	 * 
	 * @param assignee
	 *               
	 * @version 0.1.0 2016/12/04
	 * 
	 */

	public List queryAssigneeTask(String assignee) throws Exception {
		/**     TaskService        */
		List tasks = taskService.createTaskQuery().taskAssignee(assignee).list();
		return tasks;
	}


	public List queryTaskProcessInstanceId(String processInstanceId, Map jsnVariables) throws Exception {
		TaskQuery query = null;
		if (jsnVariables != null && StringUtils.isNotBlank(jsnVariables.getOrDefault("assignee", "").toString()))
			query = taskService.createTaskQuery().processInstanceId(processInstanceId).taskAssignee(jsnVariables.getOrDefault("assignee", "").toString()).orderByTaskName().asc();
		else
			query = taskService.createTaskQuery().processInstanceId(processInstanceId).orderByTaskName().asc();
		List tasks = null;
		if (query != null) {
			tasks = query.list();
		}
		return tasks;
	}

	/**
	 *        
	 */
	@Override
	@Transactional(value = FinalConstant.TRANSACTION_ACTIVITI, propagation = Propagation.REQUIRED)
	public List queryCandidateUserTask(String candidateUser) throws Exception {
		/**     TaskService        */
		List tasks = taskService.createTaskQuery().taskCandidateUser(candidateUser).list();
		return tasks;
	}

	/**
	 *      
	 */

	public List queryCandidateGroupTask(List candidateGroup) throws Exception {
		/**             */
		List tasks = taskService.createTaskQuery().taskCandidateGroupIn(candidateGroup).list();
		return tasks;
	}

	/**
	 *     
	 * 
	 * @param taskId
	 *              id
	 * @param variables
	 *                
	 * @version 0.1.0 2016/12/04
	 * 
	 */

	public void completeTask(String taskId, Map variables) throws Exception {
		/**     TaskService        */
		if (variables != null)
			taskService.complete(taskId, variables);
		else
			taskService.complete(taskId);
	}

	/**
	 *         
	 * 
	 * @param processInstanceId
	 *              id
	 * @param assignee
	 *               
	 * @param variables
	 *                
	 */

	public void completeTaskProcessInstanceId(String processInstanceId, String assignee, Map variables) {
		TaskQuery query = taskService.createTaskQuery().processInstanceId(processInstanceId).taskAssignee(assignee).orderByTaskName().asc();
		List tasks = query.list();
		for (Task task : tasks) {
			if (variables != null)
				taskService.complete(task.getId(), variables);
			else
				taskService.complete(task.getId());
		}
	}


	public ProcessInstance getProcessInstanceByBusinessKey(String businessKey) throws Exception {
		return runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();
	}

	
	public ProcessInstance getProcessInstanceById(String processInstanceId) throws Exception {
		return runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
	}

	
	public Task getTaskByBusinessKey(String businessKey) {
		// TODO Auto-generated method stub
		return taskService.createTaskQuery().processInstanceBusinessKey(businessKey).singleResult();
	}

	/**
	 *                             
	 */
	public void takeTask(String taskId, String userId) throws Exception {
		// claim   
		taskService.claim(taskId, userId);
	}

	/**
	 *   
	 */
	public void delegatedTask(String taskId, String userId) throws Exception {
		//   
		taskService.delegateTask(taskId, userId);
		//   :    Owner  ,   Assignee userId
	}

	/**
	 *         
	 * 
	 * @param processInstanceId
	 *                ID
	 * @version 0.1.0 2016/12/04
	 * 
	 */
	public boolean isFinished(String processInstanceId) {

		return historyService.createHistoricProcessInstanceQuery().finished().processInstanceId(processInstanceId).count() > 0;
	}

	/**           */
	public void addGroupUser(String taskId, String userId) {
		taskService.addCandidateUser(taskId, userId);
	}

	/**           */
	public void deleteGroupUser(String taskId, String userId) {
		taskService.deleteCandidateUser(taskId, userId);
	}

	/**
	 *       
	 * 
	 * @param deploymentId
	 *                id
	 * @param processDefinitionId
	 *               id
	 * @param processDefinitionKey
	 *                key
	 * @param processDefinitionKeyLike
	 *                key
	 * @param ascOrDesc
	 *                  1       
	 * @version 0.1.0 2016/12/04
	 * 
	 */
	public List findProcessDefintion(String deploymentId, String processDefinitionId, String processDefinitionKey, String processDefinitionKeyLike, String ascOrDesc) {
		ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
		//       
		if (StringUtils.isNotBlank(deploymentId)) {
			processDefinitionQuery.deploymentId(deploymentId);//       id  
		}
		if (StringUtils.isNotBlank(processDefinitionId)) {
			processDefinitionQuery.processDefinitionId(processDefinitionId);//       id  
		}
		if (StringUtils.isNotBlank(processDefinitionKey)) {
			processDefinitionQuery.processDefinitionKey(processDefinitionKey);//       key  
		}
		if (StringUtils.isNotBlank(processDefinitionKeyLike)) {
			processDefinitionQuery.processDefinitionKeyLike(processDefinitionKeyLike);//       key    
		}
		//   
		if (StringUtils.isBlank(ascOrDesc) || StringUtils.equalsIgnoreCase(ascOrDesc, "1")) {
			processDefinitionQuery.orderByProcessDefinitionVersion().asc();//         
		} else {
			processDefinitionQuery.orderByProcessDefinitionVersion().desc();//         
		}
		//      
		List list = processDefinitionQuery.list();//         ,      
		List alProcess = new ArrayList<>();
		JSONObject jsn;
		if (list != null && list.size() > 0) {
			for (ProcessDefinition pd : list) {
				jsn = (JSONObject) JSONObject.toJSON(pd);
				alProcess.add(jsn);
			}
			list.clear();
		}
		return alProcess;
	}

	/**
	 *      
	 * 
	 * @param processDefinitionEntity
	 *                  
	 * @param historicActivityInstances
	 *                  
	 * @return  ID  
	 * @version 0.1.0 2016/12/04
	 * 
	 */
	private List getHighLightedFlows(ProcessDefinitionEntity processDefinitionEntity, List historicActivityInstances) {
		List highFlows = new ArrayList<>();//         flowId
		for (int i = 0; i < historicActivityInstances.size(); i++) {//            
			ActivityImpl activityImpl = processDefinitionEntity.findActivity(historicActivityInstances.get(i).getActivityId());//  
																																//           
			List sameStartTimeNodes = new ArrayList<>();//                
			if ((i + 1) >= historicActivityInstances.size()) {
				break;
			}
			ActivityImpl sameActivityImpl1 = processDefinitionEntity.findActivity(historicActivityInstances.get(i + 1).getActivityId());//                     
			sameStartTimeNodes.add(sameActivityImpl1);
			for (int j = i + 1; j < historicActivityInstances.size() - 1; j++) {
				HistoricActivityInstance activityImpl1 = historicActivityInstances.get(j);//        
				HistoricActivityInstance activityImpl2 = historicActivityInstances.get(j + 1);//        
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(activityImpl1.getStartTime());
				calendar.set(Calendar.MILLISECOND, 0);
				Calendar calendar1 = Calendar.getInstance();
				calendar1.setTime(activityImpl2.getStartTime());
				calendar1.set(Calendar.MILLISECOND, 0);
				if (calendar.compareTo(calendar1) == 0) {//                      
					ActivityImpl sameActivityImpl2 = processDefinitionEntity.findActivity(activityImpl2.getActivityId());
					sameStartTimeNodes.add(sameActivityImpl2);
				} else {//         
					break;
				}
			}
			List pvmTransitions = activityImpl.getOutgoingTransitions();//            
			for (PvmTransition pvmTransition : pvmTransitions) {//          
				ActivityImpl pvmActivityImpl = (ActivityImpl) pvmTransition.getDestination();//                      ,     id,      
				if (sameStartTimeNodes.contains(pvmActivityImpl)) {
					highFlows.add(pvmTransition.getId());
				}
			}
		}
		return highFlows;
	}

	/**
	 *       
	 * 
	 * @param processDefinitionId
	 *                ID
	 * @param executionId
	 *                ID
	 * @param out
	 *               
	 * @throws Exception
	 * @version 0.1.0 2016/12/04
	 * 
	 */
	public InputStream processTracking(String processDefinitionId, String executionId) throws Exception {
		//       、   
		List activeActivityIds = new ArrayList<>();
		List highLightedFlows;
		//          
		if (this.isFinished(executionId)) {//         ,       
			activeActivityIds.add(historyService.createHistoricActivityInstanceQuery().executionId(executionId).activityType("endEvent").singleResult().getActivityId());
		} else {//         ,        
			//       ID           ActivityId  
			activeActivityIds = runtimeService.getActiveActivityIds(executionId);
		}
		//          -  
		//       
		//           (          ,            )
		List historicActivityInstances = historyService.createHistoricActivityInstanceQuery().processInstanceId(executionId).orderByHistoricActivityInstanceStartTime().asc()
				.list();
		//      
		highLightedFlows = getHighLightedFlows((ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(processDefinitionId), historicActivityInstances);
		//       -  
		//     
		if (null != activeActivityIds) {
			InputStream imageStream = null;
			try {
				//       ID  BpmnModel
				BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
				//            
				imageStream = new DefaultProcessDiagramGenerator().generateDiagram(bpmnModel, "jpg", activeActivityIds, highLightedFlows, processEngineConfiguration.getActivityFontName(),
						processEngineConfiguration.getLabelFontName(), processEngineConfiguration.getAnnotationFontName(), processEngineConfiguration.getClassLoader(), 1.0);
				// IOUtils.copy(imageStream, out);
				return imageStream;
			} catch (Exception e) {
				return imageStream;
			} finally {
				IOUtils.closeQuietly(imageStream);
			}
		}
		return null;
	}


	public Collection queryFlowElement(InputStream resouceStream) {
		Collection flowElements = null;
		try {
			InputStreamReader in = new InputStreamReader(resouceStream, "UTF-8");
			XMLStreamReader xtr = XMLInputFactory.newInstance().createXMLStreamReader(in);
			BpmnModel model = new BpmnXMLConverter().convertToBpmnModel(xtr);
			flowElements = model.getMainProcess().getFlowElements();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flowElements;
	}

	/*
	 *   key               
	 */
	
	public void deleteProcessDefinitionByKey(String processDefinitionKey) {
		//         key      ,        
		List list = repositoryService.createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey)//        key  
				.list();
		//   ,           ID
		if (list != null && list.size() > 0) {
			for (ProcessDefinition pd : list) {
				//     ID
				String deploymentId = pd.getDeploymentId();
				repositoryService.deleteDeployment(deploymentId, true);
			}
		}
	}


	public InputStream getDiagramByDeploymentId(String deploymentId) throws IOException {
		//         
		List list = repositoryService.getDeploymentResourceNames(deploymentId);
		//          
		String resourceName = "";
		if (list != null && list.size() > 0) {
			for (String name : list) {
				if (name.indexOf(".png") >= 0) {
					resourceName = name;
				}
			}
		}
		return repositoryService.getResourceAsStream(deploymentId, resourceName);
	}


	public Task queryTaskById(String taskId) {
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
		return task;
	}


	public Map getTaskVariables(String taskId) throws IOException {
		try {
			return taskService.getVariables(taskId);
		} catch (Exception e) {
			return null;
		}
	}

	public HistoricProcessInstance findHistoryProcessInstanceByBusKey(String businessKey) throws Exception {
		return historyService.createHistoricProcessInstanceQuery()
				.processInstanceBusinessKey(businessKey).singleResult();
	}
}