1. 程式人生 > >整合Activiti Modeler到SpringMVC

整合Activiti Modeler到SpringMVC

package com.isoftstone.cms.workflow.api;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.isoftstone.cms.common.pojo.AjaxDataEntity;
import com.isoftstone.cms.component.datagrid.pojo.DataGrid;
import com.isoftstone.cms.component.datagrid.pojo.DataResult;
import com.isoftstone.cms.component.datagrid.pojo.DataStyle;
import com.isoftstone.cms.component.datagrid.pojo.PangingParam;
import com.isoftstone.cms.component.datagrid.utils.DataTypeConstant;
import com.isoftstone.cms.component.datagrid.utils.PangingTools;
import com.isoftstone.cms.syscore.api.BaseController;
import com.isoftstone.cms.syscore.api.JSONFactory;
import com.isoftstone.cms.syscore.utils.MessageResourcesUtils;
import com.isoftstone.cms.syscore.utils.ServletUtils;
import com.isoftstone.cms.workflow.util.ActivtiManager;

@Scope("prototype")
@Controller
public class ModelController extends BaseController{

	private static Logger logger = LoggerFactory.getLogger(ModelController.class);
	
	private ActivtiManager activtiManager = ActivtiManager.getDefaultManage();
    
	/**
	 * 點選選單"模版管理"顯示“流程模板列表”列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/workflow/model/modelList.web")
	public String queryProvinceList(HttpServletRequest request, HttpServletResponse response) {
		
		return "/WEB-INF/jsp/workflow/model/modelList";
	}
	
	/**
	 * 開啟“模版管理”列表載入列表資料
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/workflow/model/queryModelListInfoDataGrid.json")
	public void queryModelListInfoDataGrid(HttpServletRequest request, HttpServletResponse response) {

		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;

		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);

/*			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);*/
			
		    RepositoryService repositoryService = activtiManager.getRepositoryService();
			long resultCount = repositoryService.createModelQuery().count();
			List<org.activiti.engine.repository.Model> resultList = repositoryService.createModelQuery().orderByCreateTime().desc().listPage((int)(pangingParam.getPage()-1), (int)dataGrid.getRows());

			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);

			dataStyle.addDepict("id", DataTypeConstant.STRING);
			dataStyle.addDepict("name", DataTypeConstant.STRING);
			dataStyle.addDepict("key", DataTypeConstant.STRING);
			dataStyle.addDepict("version", DataTypeConstant.LONG);
			dataStyle.addDepict("createTime", DataTypeConstant.DATETIME);
			dataStyle.addDepict("lastUpdateTime", DataTypeConstant.DATETIME);
			dataStyle.addDepict("metaInfo", DataTypeConstant.STRING);
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);

			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 跳轉流程模型新增頁面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/workflow/model/toAddModel.web")
	public String toAddModel(HttpServletRequest request, HttpServletResponse response) {
			return "/WEB-INF/jsp/workflow/model/modelAdd";
	}
	
	/**
	 * 新增流程模型
	 */
	@RequestMapping(value = "/workflow/model/addModel.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String addModel(HttpServletRequest request, HttpServletResponse response) {
		String modelId ="";
		try {
        	String name = request.getParameter("name");
        	String key = request.getParameter("key");
        	String description = StringUtils.defaultString(request.getParameter("description"));
        	   	
        	RepositoryService repositoryService = activtiManager.getRepositoryService();
        	ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);
         
			Model modelData = repositoryService.newModel();

            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
            modelData.setMetaInfo(modelObjectNode.toString());
            modelData.setName(name);
            modelData.setKey(StringUtils.defaultString(key));
            //存入ACT_RE_MODEL
            repositoryService.saveModel(modelData);
            //存入ACT_GE_BYTEARRAY
            repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));   
            modelId = modelData.getId();
        } catch (Exception e) {
            logger.error("建立模型失敗:", e);
        }
		return "redirect:/service/editor?id="+ modelId;
	}
	
	/**
	 * 刪除流程模型
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/workflow/model/deleteModel.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void deleteModel(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			String modelId = getRequest().getParameter("id");
			RepositoryService repositoryService = activtiManager.getRepositoryService();
			repositoryService.deleteModel(modelId);		
			getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));
		} catch (Exception e) {
			e.printStackTrace();
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert4"));
		}finally {
        	try {
				response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, getUserContext()));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
    /**
     * 根據Model部署
     */
    @RequestMapping(value = "/workflow/model/deploy.json",method = { RequestMethod.GET, RequestMethod.POST })
    public void deploy(HttpServletRequest request, HttpServletResponse response) {
    	AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
    	String modelId = request.getParameter("id");
    	RepositoryService repositoryService = activtiManager.getRepositoryService();
        try {
            Model modelData = repositoryService.getModel(modelId);

            ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
            byte[] bpmnBytes = null;

            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            bpmnBytes = new BpmnXMLConverter().convertToXML(model,"GBK");

            String processName = modelData.getName() + ".bpmn20.xml";
            Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes)).deploy();
    		//修改存入部署物件ID
    		//Model modelData = repositoryService.createModelQuery().modelId(modelId).singleResult();
    		modelData.setDeploymentId(deployment.getId());
    		repositoryService.saveModel(modelData);

            getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "workflow.alertinfo.deploysuccess"));
        } catch (Exception e) {
        	e.printStackTrace();
            logger.error("根據模型部署流程失敗:modelId={}", modelId, e);
            getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "workflow.alertinfo.deployfail"));
        }finally {
        	try {
				response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, getUserContext()));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
    }
    
   
    
    /**
	 * 匯出model物件為指定型別
	 * 
	 * @param modelId
	 *            模型ID
	 * @param type
	 *            匯出檔案型別(bpmn\json)
	 */
	@RequestMapping(value = "/workflow/model/export.web")
	public void export(HttpServletRequest request, HttpServletResponse response) {
		RepositoryService repositoryService = activtiManager.getRepositoryService();
		String modelId = request.getParameter("id");
		String type = "bpmn";//預設匯出bpmn格式
		try {				
			org.activiti.engine.repository.Model modelData = repositoryService.getModel(modelId);
			BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
			byte[] modelEditorSource = repositoryService.getModelEditorSource(modelData.getId());

			JsonNode editorNode = new ObjectMapper().readTree(modelEditorSource);
			BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);

			// 處理異常
			if (bpmnModel.getMainProcess() == null) {
				response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
				response.getOutputStream().println("no main process, can't export for type: " + type);
				response.flushBuffer();
				return;
			}

			String filename = "";
			byte[] exportBytes = null;

			String mainProcessId = bpmnModel.getMainProcess().getId();
			
			switch (type) {
			case "bpmn": {

				BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
				exportBytes = xmlConverter.convertToXML(bpmnModel,"GBK");

				filename = mainProcessId + ".bpmn20.xml";
				break;
			}

			case "json": {
				exportBytes = modelEditorSource;
				filename = mainProcessId + ".json";
			}
			}

			ByteArrayInputStream in = new ByteArrayInputStream(exportBytes);
			IOUtils.copy(in, response.getOutputStream());

			response.setHeader("Content-Disposition", "attachment; filename=" + filename);
			response.flushBuffer();
		} catch (Exception e) {
			logger.error("匯出model的xml檔案失敗:modelId={}, type={}", modelId, type, e);
		}
	}

}