org.activiti.engine.RepositoryService

Here are the examples of the java api org.activiti.engine.RepositoryService taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

208 Examples 7

19 Source : ProcessDefinitionCache.java
with Apache License 2.0
from yfh0918

public static void setRepositoryService(RepositoryService repositoryService) {
    ProcessDefinitionCache.repositoryService = repositoryService;
}

19 Source : ProcessDefineController.java
with Apache License 2.0
from qinyou

// 挂起操作
@Before({ IdsRequired.clreplaced, Tx.clreplaced })
public void suspendProcessDefine() {
    String ids = getPara("ids");
    RepositoryService service = ActivitiUtils.getRepositoryService();
    for (String id : ids.split(",")) {
        if (!service.isProcessDefinitionSuspended(id)) {
            // 挂起定义的同时 挂起流程实例
            service.suspendProcessDefinitionById(id, true, null);
        }
    }
    renderSuccess("挂起成功");
}

19 Source : ProcessDefineController.java
with Apache License 2.0
from qinyou

// 流程定义数据
public void query() {
    int pageNumber = getInt("page", 1);
    int pageSize = getInt("rows", 30);
    String name = get("extra_name");
    String key = getPara("extra_key");
    RepositoryService service = ActivitiUtils.getRepositoryService();
    ProcessDefinitionQuery query = service.createProcessDefinitionQuery();
    if (StringUtils.notEmpty(name)) {
        query.processDefinitionNameLike("%" + name + "%");
    }
    if (StringUtils.notEmpty(key)) {
        query.processDefinitionKeyLike("%" + key + "%");
    }
    List<Map<String, Object>> list = new ArrayList<>();
    query.orderByProcessDefinitionCategory().asc().orderByProcessDefinitionKey().desc().orderByProcessDefinitionVersion().desc().listPage((pageNumber - 1) * pageSize, pageSize).forEach(definition -> {
        Map<String, Object> item = new HashMap<>();
        item.put("id", definition.getId());
        item.put("key", definition.getKey());
        item.put("version", definition.getVersion());
        if (definition.getName() != null) {
            item.put("name", definition.getName());
        }
        if (definition.getDescription() != null) {
            item.put("description", definition.getDescription());
        }
        item.put("deploymentId", definition.getDeploymentId());
        item.put("state", !service.isProcessDefinitionSuspended(definition.getId()));
        list.add(item);
    });
    Long total = query.count();
    renderDatagrid(list, total.intValue());
}

19 Source : ActivitiRule.java
with Apache License 2.0
from dingziyang

public void setRepositoryService(RepositoryService repositoryService) {
    this.repositoryService = repositoryService;
}

19 Source : ProcessEngineMvcEndpoint.java
with Apache License 2.0
from dingziyang

/**
 * Renders a valid running BPMN process definition as a BPMN diagram.
 *
 * This is duplicative of the functionality in the full REST API implementation.
 *
 * @author Joram Barrez
 * @author Josh Long
 */
public clreplaced ProcessEngineMvcEndpoint {

    private final RepositoryService repositoryService;

    private final ProcessEngineEndpoint processEngineEndpoint;

    public ProcessEngineMvcEndpoint(ProcessEngineEndpoint processEngineEndpoint, RepositoryService repositoryService) {
        // super(processEngineEndpoint);
        this.processEngineEndpoint = processEngineEndpoint;
        this.repositoryService = repositoryService;
    }

    /**
     * Look up the process definition by key. For example,
     * this is <A href="http://localhost:8080/activiti/processes/fulfillmentProcess">process-diagram for</A>
     * a process definition named {@code fulfillmentProcess}.
     */
    @RequestMapping(value = "/processes/{processDefinitionKey:.*}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public ResponseEnreplacedy processDefinitionDiagram(@PathVariable String processDefinitionKey) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey).latestVersion().singleResult();
        if (processDefinition == null) {
            return ResponseEnreplacedy.status(HttpStatus.NOT_FOUND).body(null);
        }
        ProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
        if (bpmnModel.getLocationMap().size() == 0) {
            BpmnAutoLayout autoLayout = new BpmnAutoLayout(bpmnModel);
            autoLayout.execute();
        }
        InputStream is = processDiagramGenerator.generateJpgDiagram(bpmnModel);
        return ResponseEnreplacedy.ok(new InputStreamResource(is));
    }
}

18 Source : ProcessDefinitionCache.java
with Apache License 2.0
from yfh0918

/**
 * 流程定义缓存
 *
 * @author henryyan
 */
public clreplaced ProcessDefinitionCache {

    private static Map<String, ProcessDefinition> map = Maps.newHashMap();

    private static Map<String, List<ActivityImpl>> activities = Maps.newHashMap();

    private static Map<String, ActivityImpl> singleActivity = Maps.newHashMap();

    private static RepositoryService repositoryService;

    public static ProcessDefinition get(String processDefinitionId) {
        ProcessDefinition processDefinition = map.get(processDefinitionId);
        if (processDefinition == null) {
            processDefinition = (ProcessDefinitionEnreplacedy) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(processDefinitionId);
            if (processDefinition != null) {
                put(processDefinitionId, processDefinition);
            }
        }
        return processDefinition;
    }

    public static void put(String processDefinitionId, ProcessDefinition processDefinition) {
        map.put(processDefinitionId, processDefinition);
        ProcessDefinitionEnreplacedy pde = (ProcessDefinitionEnreplacedy) processDefinition;
        activities.put(processDefinitionId, pde.getActivities());
        for (ActivityImpl activityImpl : pde.getActivities()) {
            singleActivity.put(processDefinitionId + "_" + activityImpl.getId(), activityImpl);
        }
    }

    public static ActivityImpl getActivity(String processDefinitionId, String activityId) {
        ProcessDefinition processDefinition = get(processDefinitionId);
        if (processDefinition != null) {
            ActivityImpl activityImpl = singleActivity.get(processDefinitionId + "_" + activityId);
            if (activityImpl != null) {
                return activityImpl;
            }
        }
        return null;
    }

    @SuppressWarnings("deprecation")
    public static String getActivityName(String processDefinitionId, String activityId) {
        ActivityImpl activity = getActivity(processDefinitionId, activityId);
        if (activity != null) {
            return ObjectUtils.toString(activity.getProperty("name"));
        }
        return null;
    }

    public static void setRepositoryService(RepositoryService repositoryService) {
        ProcessDefinitionCache.repositoryService = repositoryService;
    }
}

18 Source : ProcessModelController.java
with Apache License 2.0
from qinyou

// 删除模型
@Before(IdsRequired.clreplaced)
public void deleteAction() {
    String ids = getPara("ids");
    RepositoryService service = ActivitiUtils.getRepositoryService();
    for (String id : ids.split(",")) {
        service.deleteModel(id);
    }
    renderSuccess("删除成功");
}

18 Source : ProDefinedController.java
with MIT License
from PearAdmin

/**
 * Describe: 流程定义控制器
 * Author: 就眠仪式
 * createTime: 2019/10/23
 */
@RestController
@RequestMapping("/process/defined")
public clreplaced ProDefinedController extends BaseController {

    /**
     * 基础路径
     */
    private String modelPath = "process/defined/";

    /**
     * 工作流程服务
     */
    @Resource
    private RepositoryService repositoryService;

    /**
     * Describe: 获取流程定义列表视图
     * Param: modelAndView
     * Return: 流程定义列表视图
     */
    @GetMapping("main")
    public ModelAndView main() {
        return JumpPage(modelPath + "main");
    }

    /**
     * Describe: 获取流程定义列表数据
     * Param: modelAndView
     * Return: 流程定义列表数据
     */
    @GetMapping("data")
    public ResultTable data(PageDomain pageDomain) {
        List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionVersion().asc().listPage(pageDomain.start(), pageDomain.end());
        List<ProDefined> data = new ArrayList<>();
        processDefinitions.forEach(processDefinition -> {
            ProDefined defined = new ProDefined();
            defined.setId(processDefinition.getId());
            defined.setName(processDefinition.getName());
            defined.setVersion(processDefinition.getVersion());
            defined.setKey(processDefinition.getKey());
            defined.setBpmn(processDefinition.getResourceName());
            defined.setPng(processDefinition.getDiagramResourceName());
            defined.setDeploymentId(processDefinition.getDeploymentId());
            data.add(defined);
        });
        long count = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionVersion().asc().count();
        return pageTable(data, count);
    }

    /**
     * Describe: 根据 Id 删除流程定义
     * Param: deploymentId
     * Return: Result
     */
    @DeleteMapping("remove/{deploymentId}")
    public Result remove(@PathVariable String deploymentId) {
        repositoryService.deleteDeployment(deploymentId, true);
        return Result.success("删除成功");
    }

    /**
     * Describe: 获取流程资源文件
     * Param: processDefineId
     * Param: resourceName
     * Return: InputStream
     */
    private InputStream getProcessDefineResource(String processDefineId, String resourceName) {
        return repositoryService.getResourcereplacedtream(processDefineId, resourceName);
    }

    /**
     * Describe: 获取流程模型列表视图
     * Param: processDefineId
     * Param: resourceName
     * Return: 流程模型列表视图
     */
    @GetMapping("/resource")
    public void getProcessDefineResource(HttpServletResponse response, @RequestParam("definedId") String processDefineId, String resourceName) {
        InputStream inputStream = getProcessDefineResource(processDefineId, resourceName);
        byte[] bytes = new byte[1024];
        try {
            OutputStream outputStream = response.getOutputStream();
            while (inputStream.read(bytes) != -1) {
                outputStream.write(bytes);
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

18 Source : DisabledSchemaValidationTest.java
with Apache License 2.0
from dingziyang

/**
 * @author Joram Barrez
 */
public clreplaced DisabledSchemaValidationTest {

    protected ProcessEngine processEngine;

    protected RepositoryService repositoryService;

    @Before
    public void setup() {
        StandaloneInMemProcessEngineConfiguration processEngineConfiguration = new StandaloneInMemProcessEngineConfiguration();
        processEngineConfiguration.setJdbcUrl("jdbc:h2:mem:activiti-process-validation;DB_CLOSE_DELAY=1000");
        processEngineConfiguration.setActiviti5CompatibilityEnabled(true);
        this.processEngine = processEngineConfiguration.buildProcessEngine();
        this.repositoryService = processEngine.getRepositoryService();
    }

    @After
    public void tearDown() {
        for (Deployment deployment : repositoryService.createDeploymentQuery().list()) {
            repositoryService.deleteDeployment(deployment.getId());
        }
        ProcessEngines.unregister(processEngine);
        processEngine = null;
        repositoryService = null;
    }

    @Test
    public void testDisableValidation() {
        // Should fail
        try {
            repositoryService.createDeployment().addClreplacedpathResource("org/activiti5/standalone/validation/invalid_process_xsd_error.bpmn20.xml").deploymentProperty(DeploymentProperties.DEPLOY_AS_ACTIVITI5_PROCESS_DEFINITION, Boolean.TRUE).deploy();
            replacedert.fail();
        } catch (XMLException e) {
        // expected exception
        }
        // Should fail with validation errors
        try {
            repositoryService.createDeployment().addClreplacedpathResource("org/activiti5/standalone/validation/invalid_process_xsd_error.bpmn20.xml").deploymentProperty(DeploymentProperties.DEPLOY_AS_ACTIVITI5_PROCESS_DEFINITION, Boolean.TRUE).disableSchemaValidation().deploy();
            replacedert.fail();
        } catch (ActivitiException e) {
        // expected exception
        }
    }
}

18 Source : DeployBean.java
with Apache License 2.0
from dingziyang

/**
 * @author Joram Barrez
 */
public clreplaced DeployBean {

    @Autowired
    protected RepositoryService repositoryService;

    @Transactional
    public void deployProcesses() {
        repositoryService.createDeployment().addString("process01.bpmn20.xml", "<definitions xmlns='http://www.omg.org/spec/BPMN/20100524/MODEL' targetNamespace='http://activiti.org/BPMN20'>" + "<process id='process01' name='Insurance Damage Report' /></definitions>").deploy();
        repositoryService.createDeployment().addString("process01.bpmn20.xml", "<definitions xmlns='http://www.omg.org/spec/BPMN/20100524/MODEL' targetNamespace='http://activiti.org/BPMN20'>" + "<process id='process01' name='Insurance Damage Report' this_should='fail' /></definitions>").deploy();
    }

    public RepositoryService getRepositoryService() {
        return repositoryService;
    }

    public void setRepositoryService(RepositoryService repositoryService) {
        this.repositoryService = repositoryService;
    }
}

18 Source : SpringAutoDeployTest.java
with Apache License 2.0
from dingziyang

/**
 * @author Tom Baeyens
 * @author Joram Barrez
 */
public clreplaced SpringAutoDeployTest extends PvmTestCase {

    protected static final String CTX_PATH = "org/activiti5/spring/test/autodeployment/SpringAutoDeployTest-context.xml";

    protected static final String CTX_NO_DROP_PATH = "org/activiti5/spring/test/autodeployment/SpringAutoDeployTest-no-drop-context.xml";

    protected static final String CTX_CREATE_DROP_CLEAN_DB = "org/activiti5/spring/test/autodeployment/SpringAutoDeployTest-create-drop-clean-db-context.xml";

    protected static final String CTX_DEPLOYMENT_MODE_DEFAULT = "org/activiti5/spring/test/autodeployment/SpringAutoDeployTest-deploymentmode-default-context.xml";

    protected static final String CTX_DEPLOYMENT_MODE_SINGLE_RESOURCE = "org/activiti5/spring/test/autodeployment/SpringAutoDeployTest-deploymentmode-single-resource-context.xml";

    protected static final String CTX_DEPLOYMENT_MODE_RESOURCE_PARENT_FOLDER = "org/activiti5/spring/test/autodeployment/SpringAutoDeployTest-deploymentmode-resource-parent-folder-context.xml";

    protected ApplicationContext applicationContext;

    protected RepositoryService repositoryService;

    protected void createAppContext(String path) {
        this.applicationContext = new ClreplacedPathXmlApplicationContext(path);
        this.repositoryService = applicationContext.getBean(RepositoryService.clreplaced);
    }

    protected void tearDown() throws Exception {
        removeAllDeployments();
        this.applicationContext = null;
        this.repositoryService = null;
        super.tearDown();
    }

    public void testBasicActivitiSpringIntegration() {
        createAppContext("org/activiti5/spring/test/autodeployment/SpringAutoDeployTest-context.xml");
        List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery().list();
        Set<String> processDefinitionKeys = new HashSet<String>();
        for (ProcessDefinition processDefinition : processDefinitions) {
            processDefinitionKeys.add(processDefinition.getKey());
        }
        Set<String> expectedProcessDefinitionKeys = new HashSet<String>();
        expectedProcessDefinitionKeys.add("a");
        expectedProcessDefinitionKeys.add("b");
        expectedProcessDefinitionKeys.add("c");
        replacedertEquals(expectedProcessDefinitionKeys, processDefinitionKeys);
    }

    public void testNoRedeploymentForSpringContainerRestart() throws Exception {
        createAppContext(CTX_PATH);
        DeploymentQuery deploymentQuery = repositoryService.createDeploymentQuery();
        replacedertEquals(1, deploymentQuery.count());
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
        replacedertEquals(3, processDefinitionQuery.count());
        // Creating a new app context with same resources doesn't lead to more
        // deployments
        new ClreplacedPathXmlApplicationContext(CTX_NO_DROP_PATH);
        replacedertEquals(1, deploymentQuery.count());
        replacedertEquals(3, processDefinitionQuery.count());
    }

    // Updating the bpmn20 file should lead to a new deployment when restarting
    // the Spring container
    public void testResourceRedeploymentAfterProcessDefinitionChange() throws Exception {
        createAppContext(CTX_PATH);
        replacedertEquals(1, repositoryService.createDeploymentQuery().count());
        ((AbstractXmlApplicationContext) applicationContext).destroy();
        String filePath = "org/activiti5/spring/test/autodeployment/autodeploy.a.bpmn20.xml";
        String originalBpmnFileContent = IoUtil.readFilereplacedtring(filePath);
        String updatedBpmnFileContent = originalBpmnFileContent.replace("flow1", "fromStartToEndFlow");
        replacedertTrue(updatedBpmnFileContent.length() > originalBpmnFileContent.length());
        IoUtil.writeStringToFile(updatedBpmnFileContent, filePath);
        // Clreplacedic produced/consumer problem here:
        // The file is already written in Java, but not yet completely persisted
        // by
        // the OS
        // Constructing the new app context reads the same file which is
        // sometimes
        // not yet fully written to disk
        waitUntilFileIsWritten(filePath, updatedBpmnFileContent.length());
        try {
            applicationContext = new ClreplacedPathXmlApplicationContext(CTX_NO_DROP_PATH);
            repositoryService = (RepositoryService) applicationContext.getBean("repositoryService");
        } finally {
            // Reset file content such that future test are not seeing something
            // funny
            IoUtil.writeStringToFile(originalBpmnFileContent, filePath);
        }
        // replacedertions come AFTER the file write! Otherwise the process file is
        // messed up if the replacedertions fail.
        replacedertEquals(2, repositoryService.createDeploymentQuery().count());
        replacedertEquals(6, repositoryService.createProcessDefinitionQuery().count());
    }

    public void testAutoDeployWithCreateDropOnCleanDb() {
        createAppContext(CTX_CREATE_DROP_CLEAN_DB);
        replacedertEquals(1, repositoryService.createDeploymentQuery().count());
        replacedertEquals(3, repositoryService.createProcessDefinitionQuery().count());
    }

    public void testAutoDeployWithDeploymentModeDefault() {
        createAppContext(CTX_DEPLOYMENT_MODE_DEFAULT);
        replacedertEquals(1, repositoryService.createDeploymentQuery().count());
        replacedertEquals(3, repositoryService.createProcessDefinitionQuery().count());
    }

    public void testAutoDeployWithDeploymentModeSingleResource() {
        createAppContext(CTX_DEPLOYMENT_MODE_SINGLE_RESOURCE);
        replacedertEquals(3, repositoryService.createDeploymentQuery().count());
        replacedertEquals(3, repositoryService.createProcessDefinitionQuery().count());
    }

    public void testAutoDeployWithDeploymentModeResourceParentFolder() {
        createAppContext(CTX_DEPLOYMENT_MODE_RESOURCE_PARENT_FOLDER);
        replacedertEquals(2, repositoryService.createDeploymentQuery().count());
        replacedertEquals(4, repositoryService.createProcessDefinitionQuery().count());
    }

    // --Helper methods
    // ----------------------------------------------------------
    private void removeAllDeployments() {
        for (Deployment deployment : repositoryService.createDeploymentQuery().list()) {
            repositoryService.deleteDeployment(deployment.getId(), true);
        }
    }

    private boolean waitUntilFileIsWritten(String filePath, int expectedBytes) throws URISyntaxException {
        while (IoUtil.getFile(filePath).length() != (long) expectedBytes) {
            try {
                wait(100L);
            } catch (InterruptedException e) {
                fail(e.getMessage());
            }
        }
        return true;
    }
}

18 Source : SpringAutoDeployTest.java
with Apache License 2.0
from dingziyang

/**
 * @author Tom Baeyens
 * @author Joram Barrez
 */
public clreplaced SpringAutoDeployTest extends AbstractTestCase {

    protected static final String CTX_PATH = "org/activiti/spring/test/autodeployment/SpringAutoDeployTest-context.xml";

    protected static final String CTX_NO_DROP_PATH = "org/activiti/spring/test/autodeployment/SpringAutoDeployTest-no-drop-context.xml";

    protected static final String CTX_CREATE_DROP_CLEAN_DB = "org/activiti/spring/test/autodeployment/SpringAutoDeployTest-create-drop-clean-db-context.xml";

    protected static final String CTX_DEPLOYMENT_MODE_DEFAULT = "org/activiti/spring/test/autodeployment/SpringAutoDeployTest-deploymentmode-default-context.xml";

    protected static final String CTX_DEPLOYMENT_MODE_SINGLE_RESOURCE = "org/activiti/spring/test/autodeployment/SpringAutoDeployTest-deploymentmode-single-resource-context.xml";

    protected static final String CTX_DEPLOYMENT_MODE_RESOURCE_PARENT_FOLDER = "org/activiti/spring/test/autodeployment/SpringAutoDeployTest-deploymentmode-resource-parent-folder-context.xml";

    protected ApplicationContext applicationContext;

    protected RepositoryService repositoryService;

    protected void createAppContext(String path) {
        this.applicationContext = new ClreplacedPathXmlApplicationContext(path);
        this.repositoryService = applicationContext.getBean(RepositoryService.clreplaced);
    }

    protected void tearDown() throws Exception {
        removeAllDeployments();
        this.applicationContext = null;
        this.repositoryService = null;
        super.tearDown();
    }

    public void testBasicActivitiSpringIntegration() {
        createAppContext("org/activiti/spring/test/autodeployment/SpringAutoDeployTest-context.xml");
        List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery().list();
        Set<String> processDefinitionKeys = new HashSet<String>();
        for (ProcessDefinition processDefinition : processDefinitions) {
            processDefinitionKeys.add(processDefinition.getKey());
        }
        Set<String> expectedProcessDefinitionKeys = new HashSet<String>();
        expectedProcessDefinitionKeys.add("a");
        expectedProcessDefinitionKeys.add("b");
        expectedProcessDefinitionKeys.add("c");
        replacedertEquals(expectedProcessDefinitionKeys, processDefinitionKeys);
    }

    public void testNoRedeploymentForSpringContainerRestart() throws Exception {
        createAppContext(CTX_PATH);
        DeploymentQuery deploymentQuery = repositoryService.createDeploymentQuery();
        replacedertEquals(1, deploymentQuery.count());
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
        replacedertEquals(3, processDefinitionQuery.count());
        // Creating a new app context with same resources doesn't lead to more
        // deployments
        new ClreplacedPathXmlApplicationContext(CTX_NO_DROP_PATH);
        replacedertEquals(1, deploymentQuery.count());
        replacedertEquals(3, processDefinitionQuery.count());
    }

    // Updating the bpmn20 file should lead to a new deployment when restarting
    // the Spring container
    public void testResourceRedeploymentAfterProcessDefinitionChange() throws Exception {
        createAppContext(CTX_PATH);
        replacedertEquals(1, repositoryService.createDeploymentQuery().count());
        ((AbstractXmlApplicationContext) applicationContext).destroy();
        String filePath = "org/activiti/spring/test/autodeployment/autodeploy.a.bpmn20.xml";
        String originalBpmnFileContent = IoUtil.readFilereplacedtring(filePath);
        String updatedBpmnFileContent = originalBpmnFileContent.replace("flow1", "fromStartToEndFlow");
        replacedertTrue(updatedBpmnFileContent.length() > originalBpmnFileContent.length());
        IoUtil.writeStringToFile(updatedBpmnFileContent, filePath);
        // Clreplacedic produced/consumer problem here:
        // The file is already written in Java, but not yet completely persisted
        // by
        // the OS
        // Constructing the new app context reads the same file which is
        // sometimes
        // not yet fully written to disk
        waitUntilFileIsWritten(filePath, updatedBpmnFileContent.length());
        try {
            applicationContext = new ClreplacedPathXmlApplicationContext(CTX_NO_DROP_PATH);
            repositoryService = (RepositoryService) applicationContext.getBean("repositoryService");
        } finally {
            // Reset file content such that future test are not seeing something
            // funny
            IoUtil.writeStringToFile(originalBpmnFileContent, filePath);
        }
        // replacedertions come AFTER the file write! Otherwise the process file is
        // messed up if the replacedertions fail.
        replacedertEquals(2, repositoryService.createDeploymentQuery().count());
        replacedertEquals(6, repositoryService.createProcessDefinitionQuery().count());
    }

    public void testAutoDeployWithCreateDropOnCleanDb() {
        createAppContext(CTX_CREATE_DROP_CLEAN_DB);
        replacedertEquals(1, repositoryService.createDeploymentQuery().count());
        replacedertEquals(3, repositoryService.createProcessDefinitionQuery().count());
    }

    public void testAutoDeployWithDeploymentModeDefault() {
        createAppContext(CTX_DEPLOYMENT_MODE_DEFAULT);
        replacedertEquals(1, repositoryService.createDeploymentQuery().count());
        replacedertEquals(3, repositoryService.createProcessDefinitionQuery().count());
    }

    public void testAutoDeployWithDeploymentModeSingleResource() {
        createAppContext(CTX_DEPLOYMENT_MODE_SINGLE_RESOURCE);
        replacedertEquals(3, repositoryService.createDeploymentQuery().count());
        replacedertEquals(3, repositoryService.createProcessDefinitionQuery().count());
    }

    public void testAutoDeployWithDeploymentModeResourceParentFolder() {
        createAppContext(CTX_DEPLOYMENT_MODE_RESOURCE_PARENT_FOLDER);
        replacedertEquals(2, repositoryService.createDeploymentQuery().count());
        replacedertEquals(4, repositoryService.createProcessDefinitionQuery().count());
    }

    // --Helper methods
    // ----------------------------------------------------------
    private void removeAllDeployments() {
        for (Deployment deployment : repositoryService.createDeploymentQuery().list()) {
            repositoryService.deleteDeployment(deployment.getId(), true);
        }
    }

    private boolean waitUntilFileIsWritten(String filePath, int expectedBytes) throws URISyntaxException {
        while (IoUtil.getFile(filePath).length() != (long) expectedBytes) {
            try {
                wait(100L);
            } catch (InterruptedException e) {
                fail(e.getMessage());
            }
        }
        return true;
    }
}

18 Source : ProcessDefinitionsMBean.java
with Apache License 2.0
from dingziyang

/**
 * @author Saeid Mirzaei
 */
@ManagedResource(description = "Process definition MBean")
public clreplaced ProcessDefinitionsMBean {

    RepositoryService repositoryService;

    public ProcessDefinitionsMBean(ProcessEngineConfiguration processEngineConfig) {
        if (processEngineConfig != null)
            repositoryService = processEngineConfig.getRepositoryService();
    }

    @ManagedAttribute(description = "List of Process definitions")
    public List<List<String>> getProcessDefinitions() {
        List<ProcessDefinition> deployments = repositoryService.createProcessDefinitionQuery().list();
        List<List<String>> result = new ArrayList<List<String>>(deployments.size());
        for (ProcessDefinition deployment : deployments) {
            List<String> item = new ArrayList<String>(3);
            item.add(deployment.getId());
            item.add(deployment.getName());
            item.add(Integer.toString(deployment.getVersion()));
            item.add(Boolean.toString(deployment.isSuspended()));
            item.add(deployment.getDescription());
            result.add(item);
        }
        return result;
    }

    @ManagedOperation(description = "get a specific process definition")
    public List<String> getProcessDefinitionById(String id) {
        ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().processDefinitionId(id).singleResult();
        List<String> item = new ArrayList<String>(3);
        item.add(pd.getId());
        item.add(pd.getName());
        item.add(Integer.toString(pd.getVersion()));
        item.add(Boolean.toString(pd.isSuspended()));
        item.add(pd.getDescription());
        return item;
    }

    @ManagedAttribute(description = "List of deployed Processes")
    public List<List<String>> getDeployments() {
        List<Deployment> deployments = repositoryService.createDeploymentQuery().list();
        List<List<String>> result = new ArrayList<List<String>>(deployments.size());
        for (Deployment deployment : deployments) {
            List<String> item = new ArrayList<String>(3);
            item.add(deployment.getId());
            item.add(deployment.getName());
            item.add(deployment.getTenantId());
            result.add(item);
        }
        return result;
    }

    @ManagedOperation(description = "delete deployment")
    public void deleteDeployment(String deploymentId) {
        repositoryService.deleteDeployment(deploymentId);
    }

    @ManagedOperation(description = "Suspend given process ID")
    public void suspendProcessDefinitionById(String processId) {
        repositoryService.suspendProcessDefinitionById(processId);
    }

    @ManagedOperation(description = "Activate given process ID")
    public void activatedProcessDefinitionById(String processId) {
        repositoryService.activateProcessDefinitionById(processId);
    }

    @ManagedOperation(description = "Suspend given process ID")
    public void suspendProcessDefinitionByKey(String processDefinitionKey) {
        repositoryService.suspendProcessDefinitionByKey(processDefinitionKey);
    }

    @ManagedOperation(description = "Activate given process ID")
    public void activatedProcessDefinitionByKey(String processDefinitionKey) {
        repositoryService.activateProcessDefinitionByKey(processDefinitionKey);
    }

    @ManagedOperation(description = "Deploy Process Definition")
    public void deployProcessDefinition(String resourceName, String processDefinitionFile) throws FileNotFoundException {
        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
        Deployment deployment = deploymentBuilder.addInputStream(resourceName, new FileInputStream(processDefinitionFile)).deploy();
    }
}

18 Source : DisabledSchemaValidationTest.java
with Apache License 2.0
from dingziyang

/**
 * @author Joram Barrez
 */
public clreplaced DisabledSchemaValidationTest {

    protected ProcessEngine processEngine;

    protected RepositoryService repositoryService;

    @Before
    public void setup() {
        this.processEngine = new StandaloneInMemProcessEngineConfiguration().setProcessEngineName(this.getClreplaced().getName()).setJdbcUrl("jdbc:h2:mem:activiti-process-validation;DB_CLOSE_DELAY=1000").buildProcessEngine();
        this.repositoryService = processEngine.getRepositoryService();
    }

    @After
    public void tearDown() {
        for (Deployment deployment : repositoryService.createDeploymentQuery().list()) {
            repositoryService.deleteDeployment(deployment.getId());
        }
        ProcessEngines.unregister(processEngine);
        processEngine = null;
        repositoryService = null;
    }

    @Test
    public void testDisableValidation() {
        // Should fail
        try {
            repositoryService.createDeployment().addClreplacedpathResource("org/activiti/standalone/validation/invalid_process_xsd_error.bpmn20.xml").deploy();
            replacedert.fail();
        } catch (XMLException e) {
        // expected exception
        }
        // Should fail with validation errors
        try {
            repositoryService.createDeployment().addClreplacedpathResource("org/activiti/standalone/validation/invalid_process_xsd_error.bpmn20.xml").disableSchemaValidation().deploy();
            replacedert.fail();
        } catch (ActivitiException e) {
        // expected exception
        }
    }
}

18 Source : ActivitiSmokeTest.java
with GNU Lesser General Public License v3.0
from Alfresco

public void testDeploy() throws Exception {
    ProcessEngine engine = buildProcessEngine();
    RepositoryService repoService = engine.getRepositoryService();
    Deployment deployment = deployDefinition(repoService);
    replacedertNotNull(deployment);
    RuntimeService runtimeService = engine.getRuntimeService();
    try {
        ProcessInstance instance = runtimeService.startProcessInstanceByKey("testTask");
        replacedertNotNull(instance);
        String instanceId = instance.getId();
        ProcessInstance instanceInDb = findProcessInstance(runtimeService, instanceId);
        replacedertNotNull(instanceInDb);
        runtimeService.deleteProcessInstance(instanceId, "");
    } finally {
        // List<Deployment> deployments = repoService.createDeploymentQuery().list();
        // for (Deployment deployment2 : deployments)
        // {
        // repoService.deleteDeployment(deployment2.getId());
        // }
        repoService.deleteDeployment(deployment.getId());
    }
}

18 Source : DeploymentsImpl.java
with GNU Lesser General Public License v3.0
from Alfresco

@Override
public Deployment getDeployment(String deploymentId) {
    // Only admin-user is allowed to get deployments
    if (!authorityService.isAdminAuthority(AuthenticationUtil.getRunAsUser())) {
        throw new PermissionDeniedException();
    }
    RepositoryService repositoryService = activitiProcessEngine.getRepositoryService();
    DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentId(deploymentId);
    if (tenantService.isEnabled() && deployWorkflowsInTenant) {
        query.processDefinitionKeyLike("@" + TenantUtil.getCurrentDomain() + "@%");
    }
    org.activiti.engine.repository.Deployment deployment = null;
    try {
        deployment = query.singleResult();
    } catch (ActivitiException e) {
        // The next exception will cause a response status 400: Bad request
        throw new InvalidArgumentException("Invalid deployment id: " + deploymentId);
    }
    if (deployment == null) {
        // The next exception will cause a response status 404: Not found
        throw new EnreplacedyNotFoundException(deploymentId);
    }
    Deployment deploymentRest = new Deployment(deployment);
    return deploymentRest;
}

17 Source : ActivitiModelServiceImpl.java
with Apache License 2.0
from weizhiqiang1995

/**
 * @replacedle: editActivitiModelToDeploy
 * @Description: 发布模型为流程定义
 * @param @param inputObject
 * @param @param outputObject
 * @param @throws Exception    参数
 * @return void    返回类型
 * @throws
 */
@Override
public void editActivitiModelToDeploy(InputObject inputObject, OutputObject outputObject) throws Exception {
    Map<String, Object> map = inputObject.getParams();
    String modelId = map.get("modelId").toString();
    // 获取模型
    RepositoryService repositoryService = processEngine.getRepositoryService();
    Model modelData = repositoryService.getModel(modelId);
    byte[] bytes = repositoryService.getModelEditorSource(modelData.getId());
    if (bytes == null) {
        outputObject.setreturnMessage("模型数据为空,请先设计流程并成功保存,再进行发布。");
    } else {
        JsonNode modelNode = new ObjectMapper().readTree(bytes);
        BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
        if (model.getProcesses().size() == 0) {
            outputObject.setreturnMessage("数据模型不符要求,请至少设计一条主线流程。");
        } else {
            byte[] bpmnBytes = new BpmnXMLConverter().convertToXML(model);
            // 发布流程
            String processName = modelData.getName() + ".bpmn20.xml";
            Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes, "UTF-8")).deploy();
            modelData.setDeploymentId(deployment.getId());
            repositoryService.saveModel(modelData);
        }
    }
}

17 Source : ActivitiModelServiceImpl.java
with Apache License 2.0
from weizhiqiang1995

/**
 * @replacedle: queryActivitiModelList
 * @Description: 获取所有模型
 * @param @param inputObject
 * @param @param outputObject
 * @param @throws Exception    参数
 * @return void    返回类型
 * @throws
 */
@Override
public void queryActivitiModelList(InputObject inputObject, OutputObject outputObject) throws Exception {
    Map<String, Object> map = inputObject.getParams();
    RepositoryService repositoryService = processEngine.getRepositoryService();
    List<Model> beans = repositoryService.createModelQuery().listPage(Integer.parseInt(map.get("limit").toString()) * (Integer.parseInt(map.get("page").toString()) - 1), Integer.parseInt(map.get("limit").toString()));
    long count = repositoryService.createModelQuery().count() - repositoryService.createDeploymentQuery().count();
    List<Map<String, Object>> rows = new ArrayList<>();
    for (Model model : beans) {
        if (ToolUtil.isBlank(model.getDeploymentId())) {
            rows.add(ToolUtil.javaBean2Map(model));
        }
    }
    outputObject.setBeans(rows);
    outputObject.settotal(count);
}

17 Source : ProcessDefineController.java
with Apache License 2.0
from qinyou

// 激活操作
@Before({ IdsRequired.clreplaced, Tx.clreplaced })
public void activateProcessDefine() {
    String ids = getPara("ids");
    RepositoryService service = ActivitiUtils.getRepositoryService();
    for (String id : ids.split(",")) {
        if (service.isProcessDefinitionSuspended(id)) {
            // 激活定义的同时激活流程实例
            service.activateProcessDefinitionById(id, true, null);
        }
    }
    renderSuccess("激活成功");
}

17 Source : ModelEditorSaveRestResource.java
with MIT License
from PearAdmin

@RestController
@RequestMapping("service")
public clreplaced ModelEditorSaveRestResource implements ModelDataJsonConstants {

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private ObjectMapper objectMapper;

    /**
     * 保存流程
     * @param modelId 模型ID
     * @param name 流程模型名称
     * @param description
     * @param json_xml 流程文件
     * @param svg_xml 图片
     */
    @RequestMapping(value = "/model/{modelId}/save", method = RequestMethod.PUT)
    @ResponseStatus(value = HttpStatus.OK)
    public void saveModel(@PathVariable String modelId, String name, String description, String json_xml, String svg_xml) {
        try {
            Model model = repositoryService.getModel(modelId);
            ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
            modelJson.put(MODEL_NAME, name);
            modelJson.put(MODEL_DESCRIPTION, description);
            model.setMetaInfo(modelJson.toString());
            model.setName(name);
            repositoryService.saveModel(model);
            repositoryService.addModelEditorSource(model.getId(), json_xml.getBytes("utf-8"));
            InputStream svgStream = new ByteArrayInputStream(svg_xml.getBytes("utf-8"));
            TranscoderInput input = new TranscoderInput(svgStream);
            PNGTranscoder transcoder = new PNGTranscoder();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            TranscoderOutput output = new TranscoderOutput(outStream);
            transcoder.transcode(input, output);
            final byte[] result = outStream.toByteArray();
            repositoryService.addModelEditorSourceExtra(model.getId(), result);
            outStream.close();
        } catch (Exception e) {
            throw new ActivitiException("Error saving model", e);
        }
    }
}

17 Source : ProModelController.java
with MIT License
from PearAdmin

/**
 * Describe: 流程模型控制器
 * Author: 就眠仪式
 * createTime: 2019/10/23
 */
@RestController
@RequestMapping("/process/model/")
public clreplaced ProModelController extends BaseController {

    private String modelPath = "process/model/";

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private ObjectMapper objectMapper;

    /**
     * Describe: 获取流程模型列表视图
     * Param: modelAndView
     * Return: 流程模型列表视图
     */
    @GetMapping("main")
    public ModelAndView view(ModelAndView modelAndView) {
        modelAndView.setViewName(modelPath + "main");
        return modelAndView;
    }

    /**
     * Describe: 获取流程编辑器视图
     * Param: modelAndView
     * Return: 流程编辑视图
     */
    @GetMapping("editor")
    public ModelAndView editor(ModelAndView modelAndView) {
        modelAndView.setViewName(modelPath + "editor");
        return modelAndView;
    }

    /**
     * Describe: 获取流程模型列表数据
     * Param: modelAndView
     * Return: ResultTable
     */
    @GetMapping("data")
    public ResultTable list(PageDomain pageDomain) {
        List<Model> list = repositoryService.createModelQuery().listPage(pageDomain.start(), pageDomain.end());
        List<ProModel> data = new ArrayList<>();
        list.forEach(model -> {
            ProModel proModel = new ProModel();
            proModel.setId(model.getId());
            proModel.setKey(model.getKey());
            proModel.setName(model.getName());
            proModel.setVersion(model.getVersion());
            data.add(proModel);
        });
        long count = repositoryService.createModelQuery().list().size();
        return pageTable(data, count);
    }

    /**
     * Describe: 流程创建视图
     * Param: modelAndView
     * Return: 流程创建视图
     */
    @GetMapping("add")
    public ModelAndView add(ModelAndView modelAndView) {
        modelAndView.setViewName(modelPath + "add");
        return modelAndView;
    }

    /**
     * Describe: 创建流程图
     * Param: createModelParam
     * Return: Result
     */
    @PostMapping("create")
    public Result create(@RequestBody CreateModelParam param) throws IOException {
        Model model = repositoryService.newModel();
        ObjectNode modelNode = objectMapper.createObjectNode();
        modelNode.put(ModelDataJsonConstants.MODEL_NAME, param.getName());
        modelNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, param.getDescription());
        modelNode.put(ModelDataJsonConstants.MODEL_REVISION, param.getVersion());
        model.setName(param.getName());
        model.setKey(param.getKey());
        model.setMetaInfo(modelNode.toString());
        repositoryService.saveModel(model);
        createObjectNode(model.getId());
        return success("创建成功", model.getId());
    }

    /**
     * Describe: 创建流程图节点信息
     * Param: modelId
     * Return: null
     */
    private void createObjectNode(String modelId) {
        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);
        try {
            repositoryService.addModelEditorSource(modelId, editorNode.toString().getBytes("utf-8"));
        } catch (Exception e) {
            System.out.println("创建模型时完善ModelEditorSource服务异常:" + e);
        }
        System.out.println("创建模型完善ModelEditorSource结束");
    }

    /**
     * Describe: 根据 Id 删除流程图
     * Param: modelId
     * Return: Result
     */
    @PostMapping("deleteById")
    public Result deleteById(String modelId) {
        repositoryService.deleteModel(modelId);
        return success("删除成功");
    }

    /**
     * Describe: 发布流程
     * Param: modelId
     * Return: Result
     */
    @ResponseBody
    @RequestMapping("/publish")
    public Result publish(String modelId) {
        try {
            Model modelData = repositoryService.getModel(modelId);
            byte[] bytes = repositoryService.getModelEditorSource(modelData.getId());
            if (bytes == null) {
                return failure("模板数据为空");
            }
            JsonNode modelNode = new ObjectMapper().readTree(bytes);
            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addBpmnModel(modelData.getKey() + ".bpmn20.xml", model).deploy();
            modelData.setDeploymentId(deployment.getId());
            repositoryService.saveModel(modelData);
            return success("部署成功");
        } catch (Exception e) {
            return failure("部署异常");
        }
    }
}

17 Source : EndpointAutoConfiguration.java
with Apache License 2.0
from dingziyang

@Bean
public ProcessEngineMvcEndpoint processEngineMvcEndpoint(ProcessEngineEndpoint engineEndpoint, RepositoryService repositoryService) {
    return new ProcessEngineMvcEndpoint(engineEndpoint, repositoryService);
}

17 Source : BaseProcessDefinitionResource.java
with Apache License 2.0
from dingziyang

/**
 * @author Tijs Rademakers
 */
public clreplaced BaseProcessDefinitionResource {

    @Autowired
    protected RestResponseFactory restResponseFactory;

    @Autowired
    protected RepositoryService repositoryService;

    /**
     * Returns the {@link ProcessDefinition} that is requested. Throws the right exceptions when bad request was made or definition is not found.
     */
    protected ProcessDefinition getProcessDefinitionFromRequest(String processDefinitionId) {
        ProcessDefinition processDefinition = repositoryService.getProcessDefinition(processDefinitionId);
        if (processDefinition == null) {
            throw new ActivitiObjectNotFoundException("Could not find a process definition with id '" + processDefinitionId + "'.", ProcessDefinition.clreplaced);
        }
        return processDefinition;
    }
}

17 Source : BaseModelResource.java
with Apache License 2.0
from dingziyang

/**
 * @author Frederik Heremans
 */
public clreplaced BaseModelResource {

    @Autowired
    protected RestResponseFactory restResponseFactory;

    @Autowired
    protected RepositoryService repositoryService;

    /**
     * Returns the {@link Model} that is requested. Throws the right exceptions when bad request was made or model is not found.
     */
    protected Model getModelFromRequest(String modelId) {
        Model model = repositoryService.createModelQuery().modelId(modelId).singleResult();
        if (model == null) {
            throw new ActivitiObjectNotFoundException("Could not find a model with id '" + modelId + "'.", ProcessDefinition.clreplaced);
        }
        return model;
    }
}

17 Source : BaseDeploymentResourceDataResource.java
with Apache License 2.0
from dingziyang

/**
 * @author Frederik Heremans
 */
public clreplaced BaseDeploymentResourceDataResource {

    @Autowired
    protected ContentTypeResolver contentTypeResolver;

    @Autowired
    protected RepositoryService repositoryService;

    protected byte[] getDeploymentResourceData(String deploymentId, String resourceName, HttpServletResponse response) {
        if (deploymentId == null) {
            throw new ActivitiIllegalArgumentException("No deployment id provided");
        }
        if (resourceName == null) {
            throw new ActivitiIllegalArgumentException("No resource name provided");
        }
        // Check if deployment exists
        Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
        if (deployment == null) {
            throw new ActivitiObjectNotFoundException("Could not find a deployment with id '" + deploymentId + "'.", Deployment.clreplaced);
        }
        List<String> resourceList = repositoryService.getDeploymentResourceNames(deploymentId);
        if (resourceList.contains(resourceName)) {
            final InputStream resourceStream = repositoryService.getResourcereplacedtream(deploymentId, resourceName);
            String contentType = contentTypeResolver.resolveContentType(resourceName);
            response.setContentType(contentType);
            try {
                return IOUtils.toByteArray(resourceStream);
            } catch (Exception e) {
                throw new ActivitiException("Error converting resource stream", e);
            }
        } else {
            // Resource not found in deployment
            throw new ActivitiObjectNotFoundException("Could not find a resource with name '" + resourceName + "' in deployment '" + deploymentId + "'.", String.clreplaced);
        }
    }
}

17 Source : ActivitiProducer.java
with Apache License 2.0
from dingziyang

public clreplaced ActivitiProducer extends DefaultProducer {

    protected IdenreplacedyService idenreplacedyService;

    protected RuntimeService runtimeService;

    protected RepositoryService repositoryService;

    public static final String PROCESS_KEY_PROPERTY = "PROCESS_KEY_PROPERTY";

    public static final String PROCESS_ID_PROPERTY = "PROCESS_ID_PROPERTY";

    public static final String EXECUTION_ID_PROPERTY = "EXECUTION_ID_PROPERTY";

    private final long timeout;

    private final long timeResolution;

    private String processKey = null;

    private String activity = null;

    public ActivitiProducer(ActivitiEndpoint endpoint, long timeout, long timeResolution) {
        super(endpoint);
        String[] path = endpoint.getEndpointKey().split(":");
        processKey = path[1].replace("//", "");
        if (path.length > 2) {
            activity = path[2];
        }
        this.timeout = timeout;
        this.timeResolution = timeResolution;
    }

    public void process(Exchange exchange) throws Exception {
        if (shouldStartProcess()) {
            ProcessInstance pi = startProcess(exchange);
            copyResultToCamel(exchange, pi);
        } else {
            signal(exchange);
        }
    }

    protected void copyResultToCamel(Exchange exchange, ProcessInstance pi) {
        exchange.setProperty(PROCESS_ID_PROPERTY, pi.getProcessInstanceId());
        Map<String, Object> returnVars = getActivitiEndpoint().getReturnVarMap();
        if (returnVars != null && returnVars.size() > 0) {
            Map<String, Object> processVariables = null;
            if (repositoryService.isActiviti5ProcessDefinition(pi.getProcessDefinitionId())) {
                Activiti5CompatibilityHandler activiti5CompatibilityHandler = Activiti5Util.getActiviti5CompatibilityHandler();
                processVariables = activiti5CompatibilityHandler.getVariables(pi);
            } else {
                processVariables = ((ExecutionEnreplacedy) pi).getVariables();
            }
            if (processVariables != null) {
                for (String variableName : returnVars.keySet()) {
                    if (processVariables.containsKey(variableName)) {
                        exchange.setProperty(variableName, processVariables.get(variableName));
                    }
                }
            }
        }
    }

    protected boolean shouldStartProcess() {
        return activity == null;
    }

    protected void signal(Exchange exchange) {
        String processInstanceId = findProcessInstanceId(exchange);
        String executionId = exchange.getProperty(EXECUTION_ID_PROPERTY, String.clreplaced);
        boolean firstTime = true;
        long initialTime = System.currentTimeMillis();
        Execution execution = null;
        while (firstTime || (timeout > 0 && (System.currentTimeMillis() - initialTime < timeout))) {
            try {
                Thread.sleep(timeResolution);
            } catch (InterruptedException e) {
                throw new ActivitiException("error occured while waiting for activiti=" + activity + " for processInstanceId=" + processInstanceId);
            }
            firstTime = false;
            if (executionId != null) {
                execution = runtimeService.createExecutionQuery().executionId(executionId).activityId(activity).singleResult();
            } else {
                execution = runtimeService.createExecutionQuery().processDefinitionKey(processKey).processInstanceId(processInstanceId).activityId(activity).singleResult();
            }
            if (execution != null) {
                break;
            }
        }
        if (execution == null) {
            throw new ActivitiException("Couldn't find activity " + activity + " for processId " + processInstanceId + " in defined timeout.");
        }
        runtimeService.setVariables(execution.getId(), ExchangeUtils.prepareVariables(exchange, getActivitiEndpoint()));
        runtimeService.trigger(execution.getId());
    }

    protected String findProcessInstanceId(Exchange exchange) {
        String processInstanceId = exchange.getProperty(PROCESS_ID_PROPERTY, String.clreplaced);
        if (processInstanceId != null) {
            return processInstanceId;
        }
        String processInstanceKey = exchange.getProperty(PROCESS_KEY_PROPERTY, String.clreplaced);
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(processInstanceKey).singleResult();
        if (processInstance == null) {
            throw new ActivitiException("Could not find activiti with key " + processInstanceKey);
        }
        return processInstance.getId();
    }

    protected ProcessInstance startProcess(Exchange exchange) {
        ActivitiEndpoint endpoint = getActivitiEndpoint();
        String key = exchange.getProperty(PROCESS_KEY_PROPERTY, String.clreplaced);
        try {
            if (endpoint.isSetProcessInitiator()) {
                setProcessInitiator(ExchangeUtils.prepareInitiator(exchange, endpoint));
            }
            if (key == null) {
                return runtimeService.startProcessInstanceByKey(processKey, ExchangeUtils.prepareVariables(exchange, endpoint));
            } else {
                return runtimeService.startProcessInstanceByKey(processKey, key, ExchangeUtils.prepareVariables(exchange, endpoint));
            }
        } finally {
            if (endpoint.isSetProcessInitiator()) {
                setProcessInitiator(null);
            }
        }
    }

    protected void setProcessInitiator(String processInitiator) {
        if (idenreplacedyService == null) {
            throw new ActivitiException("IdenreplacedyService is missing and must be provided to set process initiator.");
        }
        idenreplacedyService.setAuthenticatedUserId(processInitiator);
    }

    protected ActivitiEndpoint getActivitiEndpoint() {
        return (ActivitiEndpoint) getEndpoint();
    }

    public void setIdenreplacedyService(IdenreplacedyService idenreplacedyService) {
        this.idenreplacedyService = idenreplacedyService;
    }

    public void setRuntimeService(RuntimeService runtimeService) {
        this.runtimeService = runtimeService;
    }

    public void setRepositoryService(RepositoryService repositoryService) {
        this.repositoryService = repositoryService;
    }
}

17 Source : ActivitiComponent.java
with Apache License 2.0
from dingziyang

/**
 * This clreplaced has been modified to be consistent with the changes to CamelBehavior and its implementations. The set of changes significantly increases the flexibility of our Camel integration, as you
 * can either choose one of three "out-of-the-box" modes, or you can choose to create your own. Please reference the comments for the "CamelBehavior" clreplaced for more information on the out-of-the-box
 * implementation clreplaced options.
 *
 * @author Ryan Johnston (@rjfsu), Tijs Rademakers, Arnold Schrijver
 */
public clreplaced ActivitiComponent extends DefaultComponent {

    protected IdenreplacedyService idenreplacedyService;

    protected RuntimeService runtimeService;

    protected RepositoryService repositoryService;

    protected boolean copyVariablesToProperties;

    protected boolean copyVariablesToBodyAsMap;

    protected boolean copyCamelBodyToBody;

    public ActivitiComponent() {
    }

    @Override
    public void setCamelContext(CamelContext context) {
        super.setCamelContext(context);
        idenreplacedyService = getByType(context, IdenreplacedyService.clreplaced);
        runtimeService = getByType(context, RuntimeService.clreplaced);
        repositoryService = getByType(context, RepositoryService.clreplaced);
    }

    private <T> T getByType(CamelContext ctx, Clreplaced<T> kls) {
        Map<String, T> looked = ctx.getRegistry().findByTypeWithName(kls);
        if (looked.isEmpty()) {
            return null;
        }
        return looked.values().iterator().next();
    }

    @Override
    protected Endpoint createEndpoint(String s, String s1, Map<String, Object> parameters) throws Exception {
        ActivitiEndpoint ae = new ActivitiEndpoint(s, getCamelContext());
        ae.setIdenreplacedyService(idenreplacedyService);
        ae.setRuntimeService(runtimeService);
        ae.setRepositoryService(repositoryService);
        ae.setCopyVariablesToProperties(this.copyVariablesToProperties);
        ae.setCopyVariablesToBodyAsMap(this.copyVariablesToBodyAsMap);
        ae.setCopyCamelBodyToBody(this.copyCamelBodyToBody);
        Map<String, Object> returnVars = IntrospectionSupport.extractProperties(parameters, "var.return.");
        if (returnVars != null && returnVars.size() > 0) {
            ae.getReturnVarMap().putAll(returnVars);
        }
        return ae;
    }

    public boolean isCopyVariablesToProperties() {
        return copyVariablesToProperties;
    }

    public void setCopyVariablesToProperties(boolean copyVariablesToProperties) {
        this.copyVariablesToProperties = copyVariablesToProperties;
    }

    public boolean isCopyCamelBodyToBody() {
        return copyCamelBodyToBody;
    }

    public void setCopyCamelBodyToBody(boolean copyCamelBodyToBody) {
        this.copyCamelBodyToBody = copyCamelBodyToBody;
    }

    public boolean isCopyVariablesToBodyAsMap() {
        return copyVariablesToBodyAsMap;
    }

    public void setCopyVariablesToBodyAsMap(boolean copyVariablesToBodyAsMap) {
        this.copyVariablesToBodyAsMap = copyVariablesToBodyAsMap;
    }
}

17 Source : ActivitiSmokeTest.java
with GNU Lesser General Public License v3.0
from Alfresco

private Deployment deployDefinition(RepositoryService repoService) throws IOException {
    ClreplacedPathResource resource = new ClreplacedPathResource("org/alfresco/repo/workflow/activiti/testTransaction.bpmn20.xml");
    Deployment deployment = repoService.createDeployment().addInputStream(resource.getFilename(), resource.getInputStream()).deploy();
    return deployment;
}

17 Source : ProcessDefinitionMetaControllerImpl.java
with Apache License 2.0
from Activiti

@RestController
public clreplaced ProcessDefinitionMetaControllerImpl implements ProcessDefinitionMetaController {

    private final RepositoryService repositoryService;

    private final ProcessDefinitionMetaResourcereplacedembler resourcereplacedembler;

    @Autowired
    public ProcessDefinitionMetaControllerImpl(RepositoryService repositoryService, ProcessDefinitionMetaResourcereplacedembler resourcereplacedembler) {
        this.repositoryService = repositoryService;
        this.resourcereplacedembler = resourcereplacedembler;
    }

    @Override
    public Resource<ProcessDefinitionMeta> getProcessDefinitionMetadata(@PathVariable String id) {
        org.activiti.engine.repository.ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(id).singleResult();
        if (processDefinition == null) {
            throw new ActivitiObjectNotFoundException("Unable to find process definition for the given id:'" + id + "'");
        }
        List<Process> processes = repositoryService.getBpmnModel(id).getProcesses();
        Set<ProcessDefinitionVariable> variables = new HashSet<>();
        Set<String> users = new HashSet<>();
        Set<String> groups = new HashSet<>();
        Set<ProcessDefinitionUserTask> userTasks = new HashSet<>();
        Set<ProcessDefinitionServiceTask> serviceTasks = new HashSet<>();
        for (Process process : processes) {
            variables.addAll(getVariables(process));
            List<FlowElement> flowElementList = (List<FlowElement>) process.getFlowElements();
            for (FlowElement flowElement : flowElementList) {
                if (flowElement.getClreplaced().equals(UserTask.clreplaced)) {
                    UserTask userTask = (UserTask) flowElement;
                    ProcessDefinitionUserTask task = new ProcessDefinitionUserTask(userTask.getName(), userTask.getDoreplacedentation());
                    userTasks.add(task);
                    users.addAll(userTask.getCandidateUsers());
                    groups.addAll(userTask.getCandidateGroups());
                }
                if (flowElement.getClreplaced().equals(ServiceTask.clreplaced)) {
                    ServiceTask serviceTask = (ServiceTask) flowElement;
                    ProcessDefinitionServiceTask task = new ProcessDefinitionServiceTask(serviceTask.getName(), serviceTask.getImplementation());
                    serviceTasks.add(task);
                }
            }
        }
        return resourcereplacedembler.toResource(new ProcessDefinitionMeta(processDefinition.getId(), processDefinition.getName(), processDefinition.getDescription(), processDefinition.getVersion(), users, groups, variables, userTasks, serviceTasks));
    }

    private List<ProcessDefinitionVariable> getVariables(Process process) {
        List<ProcessDefinitionVariable> variables = new ArrayList<>();
        if (!process.getExtensionElements().isEmpty()) {
            Iterator<List<ExtensionElement>> it = process.getExtensionElements().values().iterator();
            while (it.hasNext()) {
                List<ExtensionElement> extensionElementList = it.next();
                Iterator<ExtensionElement> it2 = extensionElementList.iterator();
                while (it2.hasNext()) {
                    ExtensionElement ee = it2.next();
                    String name = ee.getAttributeValue(ee.getNamespace(), "variableName");
                    String type = ee.getAttributeValue(ee.getNamespace(), "variableType");
                    ProcessDefinitionVariable variable = new ProcessDefinitionVariable(name, type);
                    variables.add(variable);
                }
            }
        }
        return variables;
    }
}

17 Source : ProcessDefinitionMetaControllerImpl.java
with Apache License 2.0
from Activiti

@RestController
public clreplaced ProcessDefinitionMetaControllerImpl implements ProcessDefinitionMetaController {

    private final RepositoryService repositoryService;

    private final ProcessDefinitionMetaRepresentationModelreplacedembler representationModelreplacedembler;

    @Autowired
    public ProcessDefinitionMetaControllerImpl(RepositoryService repositoryService, ProcessDefinitionMetaRepresentationModelreplacedembler representationModelreplacedembler) {
        this.repositoryService = repositoryService;
        this.representationModelreplacedembler = representationModelreplacedembler;
    }

    @Override
    public EnreplacedyModel<ProcessDefinitionMeta> getProcessDefinitionMetadata(@PathVariable String id) {
        org.activiti.engine.repository.ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(id).singleResult();
        if (processDefinition == null) {
            throw new ActivitiObjectNotFoundException("Unable to find process definition for the given id:'" + id + "'");
        }
        List<Process> processes = repositoryService.getBpmnModel(id).getProcesses();
        Set<ProcessDefinitionVariable> variables = new HashSet<>();
        Set<String> users = new HashSet<>();
        Set<String> groups = new HashSet<>();
        Set<ProcessDefinitionUserTask> userTasks = new HashSet<>();
        Set<ProcessDefinitionServiceTask> serviceTasks = new HashSet<>();
        for (Process process : processes) {
            variables.addAll(getVariables(process));
            List<FlowElement> flowElementList = (List<FlowElement>) process.getFlowElements();
            for (FlowElement flowElement : flowElementList) {
                if (flowElement.getClreplaced().equals(UserTask.clreplaced)) {
                    UserTask userTask = (UserTask) flowElement;
                    ProcessDefinitionUserTask task = new ProcessDefinitionUserTask(userTask.getName(), userTask.getDoreplacedentation());
                    userTasks.add(task);
                    users.addAll(userTask.getCandidateUsers());
                    groups.addAll(userTask.getCandidateGroups());
                }
                if (flowElement.getClreplaced().equals(ServiceTask.clreplaced)) {
                    ServiceTask serviceTask = (ServiceTask) flowElement;
                    ProcessDefinitionServiceTask task = new ProcessDefinitionServiceTask(serviceTask.getName(), serviceTask.getImplementation());
                    serviceTasks.add(task);
                }
            }
        }
        return representationModelreplacedembler.toModel(new ProcessDefinitionMeta(processDefinition.getId(), processDefinition.getName(), processDefinition.getDescription(), processDefinition.getVersion(), users, groups, variables, userTasks, serviceTasks));
    }

    private List<ProcessDefinitionVariable> getVariables(Process process) {
        List<ProcessDefinitionVariable> variables = new ArrayList<>();
        if (!process.getExtensionElements().isEmpty()) {
            Iterator<List<ExtensionElement>> it = process.getExtensionElements().values().iterator();
            while (it.hasNext()) {
                List<ExtensionElement> extensionElementList = it.next();
                Iterator<ExtensionElement> it2 = extensionElementList.iterator();
                while (it2.hasNext()) {
                    ExtensionElement ee = it2.next();
                    String name = ee.getAttributeValue(ee.getNamespace(), "variableName");
                    String type = ee.getAttributeValue(ee.getNamespace(), "variableType");
                    ProcessDefinitionVariable variable = new ProcessDefinitionVariable(name, type);
                    variables.add(variable);
                }
            }
        }
        return variables;
    }
}

16 Source : ProcessDefinitionController.java
with Apache License 2.0
from Yiuman

/**
 * 获取流程的资源文件
 *
 * @param processDefinitionId 流程定义ID
 * @param type                资源类型 默认/0 bpmn 1 png
 */
@GetMapping("/resource/{processDefinitionId}")
public void getProcessResource(@PathVariable String processDefinitionId, Integer type) throws IOException {
    RepositoryService repositoryService = getProcessEngine().getRepositoryService();
    ProcessDefinition processDefinition = repositoryService.getProcessDefinition(processDefinitionId);
    String resourceName = ObjectUtils.isEmpty(type) || type == 0 ? processDefinition.getResourceName() : processDefinition.getDiagramResourceName();
    InputStream resourcereplacedtream = repositoryService.getResourcereplacedtream(processDefinition.getDeploymentId(), resourceName);
    WebUtils.export(resourcereplacedtream, resourceName);
}

16 Source : ModelSaveRestResource.java
with Apache License 2.0
from happy-panda

/**
 * @author Tijs Rademakers
 */
@RestController
@Slf4j
@RequestMapping("activiti/activitiService")
public clreplaced ModelSaveRestResource implements ModelDataJsonConstants {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private ObjectMapper objectMapper;

    @RequestMapping(value = "/model/{modelId}/save", method = RequestMethod.PUT)
    @ResponseStatus(value = HttpStatus.OK)
    public void saveModel(@PathVariable String modelId, HttpServletRequest request) {
        try {
            Model model = repositoryService.getModel(modelId);
            ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
            modelJson.put(MODEL_NAME, request.getParameter("name"));
            modelJson.put(MODEL_DESCRIPTION, request.getParameter("description"));
            model.setMetaInfo(modelJson.toString());
            model.setName(request.getParameter("name"));
            repositoryService.saveModel(model);
            repositoryService.addModelEditorSource(model.getId(), request.getParameter("json_xml").getBytes("utf-8"));
            InputStream svgStream = new ByteArrayInputStream(request.getParameter("svg_xml").getBytes("utf-8"));
            TranscoderInput input = new TranscoderInput(svgStream);
            PNGTranscoder transcoder = new PNGTranscoder();
            // Setup output
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            TranscoderOutput output = new TranscoderOutput(outStream);
            // Do the transformation
            transcoder.transcode(input, output);
            final byte[] result = outStream.toByteArray();
            repositoryService.addModelEditorSourceExtra(model.getId(), result);
            outStream.close();
        } catch (Exception e) {
            log.error("Error saving model", e);
            throw new ActivitiException("Error saving model", e);
        }
    }
}

16 Source : ResourceParentFolderAutoDeploymentStrategy.java
with Apache License 2.0
from flowable

@Override
public void deployResources(final String deploymentNameHint, final Resource[] resources, final RepositoryService repositoryService) {
    // Create a deployment for each distinct parent folder using the name
    // hint
    // as a prefix
    final Map<String, Set<Resource>> resourcesMap = createMap(resources);
    for (final Entry<String, Set<Resource>> group : resourcesMap.entrySet()) {
        final String deploymentName = determineDeploymentName(deploymentNameHint, group.getKey());
        final DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering().name(deploymentName);
        for (final Resource resource : group.getValue()) {
            final String resourceName = determineResourceName(resource);
            try {
                if (resourceName.endsWith(".bar") || resourceName.endsWith(".zip") || resourceName.endsWith(".jar")) {
                    deploymentBuilder.addZipInputStream(new ZipInputStream(resource.getInputStream()));
                } else {
                    deploymentBuilder.addInputStream(resourceName, resource.getInputStream());
                }
            } catch (IOException e) {
                throw new ActivitiException("couldn't auto deploy resource '" + resource + "': " + e.getMessage(), e);
            }
        }
        deploymentBuilder.deploy();
    }
}

16 Source : ProcessController.java
with Apache License 2.0
from egojit8

@Controller
@RequestMapping("/admin/workflow/process")
@Api(value = "工作流管理", description = "工作流管理")
public clreplaced ProcessController extends BaseWebController {

    @Autowired
    RepositoryService repositoryService;

    @RequestMapping("/index")
    @ApiOperation(value = "工作流管理")
    public String index() {
        return "/workflow/process/index";
    }

    @ResponseBody
    @PostMapping("/index")
    @ApiOperation(value = "工作流管理")
    public Object index(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        // RepositoryService repositoryService = processEngine.getRepositoryService();
        Page<Process> pg = new Page<Process>(request, response);
        List<ProcessDefinition> definitions = repositoryService.createProcessDefinitionQuery().listPage(pg.getPage() - 1, pg.getPageSize());
        long count = repositoryService.createProcessDefinitionQuery().count();
        List<Process> list = new ArrayList<Process>();
        if (definitions != null) {
            for (ProcessDefinition item : definitions) {
                Process p = new Process();
                BeanUtils.copyProperties(p, item);
                list.add(p);
            }
        }
        pg.setList(list);
        pg.setRecords(count);
        return pg;
    }

    @RequestMapping("/edit")
    @ApiOperation(value = "流程添加界面")
    public String add() {
        return "/workflow/process/edit";
    }

    @ApiOperation(value = "流程添加接口")
    @PostMapping("/edit")
    @ResponseBody
    public BaseResult edit(HttpServletRequest request, Process process) {
        BaseResult result = new BaseResult(BaseResultCode.SUCCESS, "部署成功!");
        try {
            String filePath = request.getSession().getServletContext().getRealPath("process/");
            File file = new File(filePath + process.getResourceName());
            // 部署
            InputStream inputStream = new FileInputStream(file);
            // 实例化zip输入流对象
            ZipInputStream zipInputStream = new ZipInputStream(inputStream);
            // ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
            // RepositoryService repositoryService = processEngine.getRepositoryService();
            repositoryService.createDeployment().name(process.getName()).category(process.getCategory()).key(process.getKey()).addZipInputStream(zipInputStream).deploy();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            result = new BaseResult(BaseResultCode.EXCEPTION, "部署失败");
        } catch (IOException e) {
            e.printStackTrace();
            result = new BaseResult(BaseResultCode.EXCEPTION, "部署失败");
        }
        return result;
    }

    @ApiOperation(value = "流程添加接口")
    @PostMapping("/processfile")
    @ResponseBody
    public BaseResult prcessFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        BaseResult result = new BaseResult(BaseResultCode.EXCEPTION, "上传失败,因为文件是空的");
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            String filePath = request.getSession().getServletContext().getRealPath("process/");
            try {
                FileUtil.uploadFile(file.getBytes(), filePath, fileName);
                result = new BaseResult(BaseResultCode.SUCCESS, fileName);
            } catch (Exception e) {
                // TODO: handle exception
                result = new BaseResult(BaseResultCode.EXCEPTION, "上传失败");
            }
        } else {
            result = new BaseResult(BaseResultCode.EXCEPTION, "上传失败,因为文件是空的");
        }
        return result;
    }
    // @ResponseBody
    // @PostMapping("/delete")
    // @ApiOperation(value = "用户管理接口")
    // public BaseResult delete(String ids){
    // BaseResult result=new BaseResult(BaseResultCode.SUCCESS,"删除成功");
    // List<String> idList= JSON.parseArray(ids,String.clreplaced);
    // int count= userService.deleteByIds(idList);
    // _log.info("删除了:"+count+"数据");
    // return result;
    // }
}

16 Source : AbstractProcessInstanceQueryResource.java
with Apache License 2.0
from dingziyang

public abstract clreplaced AbstractProcessInstanceQueryResource {

    private static final int DEFAULT_PAGE_SIZE = 25;

    @Autowired
    protected RepositoryService repositoryService;

    @Autowired
    protected HistoryService historyService;

    @Autowired
    protected UserCache userCache;

    public ResultListDataRepresentation getProcessInstances(ObjectNode requestNode) {
        HistoricProcessInstanceQuery instanceQuery = historyService.createHistoricProcessInstanceQuery();
        User currentUser = SecurityUtils.getCurrentUserObject();
        instanceQuery.involvedUser(String.valueOf(currentUser.getId()));
        // Process definition
        JsonNode processDefinitionIdNode = requestNode.get("processDefinitionId");
        if (processDefinitionIdNode != null && processDefinitionIdNode.isNull() == false) {
            instanceQuery.processDefinitionId(processDefinitionIdNode.asText());
        }
        JsonNode deploymentKeyNode = requestNode.get("deploymentKey");
        if (deploymentKeyNode != null && deploymentKeyNode.isNull() == false) {
            // Results need to be filtered in an app-context. We need to fetch the deployment id for this app and use that in the query
            List<Deployment> deployments = repositoryService.createDeploymentQuery().deploymentKey(deploymentKeyNode.asText()).list();
            List<String> deploymentIds = new ArrayList<String>();
            for (Deployment deployment : deployments) {
                deploymentIds.add(deployment.getId());
            }
            instanceQuery.deploymentIdIn(deploymentIds);
        }
        // State filtering
        JsonNode stateNode = requestNode.get("state");
        if (stateNode != null && !stateNode.isNull()) {
            String state = stateNode.asText();
            if ("running".equals(state)) {
                instanceQuery.unfinished();
            } else if ("completed".equals(state)) {
                instanceQuery.finished();
            } else if (!"all".equals(state)) {
                throw new BadRequestException("Illegal state filter value preplaceded, only 'running', 'completed' or 'all' are supported");
            }
        } else {
            // Default filtering, only running
            instanceQuery.unfinished();
        }
        // Sort and ordering
        JsonNode sortNode = requestNode.get("sort");
        if (sortNode != null && !sortNode.isNull()) {
            if ("created-desc".equals(sortNode.asText())) {
                instanceQuery.orderByProcessInstanceStartTime().desc();
            } else if ("created-asc".equals(sortNode.asText())) {
                instanceQuery.orderByProcessInstanceStartTime().asc();
            } else if ("ended-desc".equals(sortNode.asText())) {
                instanceQuery.orderByProcessInstanceEndTime().desc();
            } else if ("ended-asc".equals(sortNode.asText())) {
                instanceQuery.orderByProcessInstanceEndTime().asc();
            }
        } else {
            // Revert to default
            instanceQuery.orderByProcessInstanceStartTime().desc();
        }
        int page = 0;
        JsonNode pageNode = requestNode.get("page");
        if (pageNode != null && !pageNode.isNull()) {
            page = pageNode.asInt(0);
        }
        int size = DEFAULT_PAGE_SIZE;
        JsonNode sizeNode = requestNode.get("size");
        if (sizeNode != null && !sizeNode.isNull()) {
            size = sizeNode.asInt(DEFAULT_PAGE_SIZE);
        }
        List<HistoricProcessInstance> instances = instanceQuery.listPage(page * size, size);
        ResultListDataRepresentation result = new ResultListDataRepresentation(convertInstanceList(instances));
        // In case we're not on the first page and the size exceeds the page size, we need to do an additional count for the total
        if (page != 0 || instances.size() == size) {
            Long totalCount = instanceQuery.count();
            result.setTotal(Long.valueOf(totalCount.intValue()));
            result.setStart(page * size);
        }
        return result;
    }

    protected List<ProcessInstanceRepresentation> convertInstanceList(List<HistoricProcessInstance> instances) {
        List<ProcessInstanceRepresentation> result = new ArrayList<ProcessInstanceRepresentation>();
        if (CollectionUtils.isNotEmpty(instances)) {
            for (HistoricProcessInstance processInstance : instances) {
                User userRep = null;
                if (processInstance.getStartUserId() != null) {
                    CachedUser user = userCache.getUser(processInstance.getStartUserId());
                    if (user != null && user.getUser() != null) {
                        userRep = user.getUser();
                    }
                }
                ProcessDefinitionEnreplacedy procDef = (ProcessDefinitionEnreplacedy) repositoryService.getProcessDefinition(processInstance.getProcessDefinitionId());
                ProcessInstanceRepresentation instanceRepresentation = new ProcessInstanceRepresentation(processInstance, procDef, procDef.isGraphicalNotationDefined(), userRep);
                result.add(instanceRepresentation);
            }
        }
        return result;
    }
}

16 Source : AbstractProcessDefinitionsResource.java
with Apache License 2.0
from dingziyang

public abstract clreplaced AbstractProcessDefinitionsResource {

    @Autowired
    protected RepositoryService repositoryService;

    @Autowired
    protected FormRepositoryService formRepositoryService;

    @Autowired
    protected PermissionService permissionService;

    public ResultListDataRepresentation getProcessDefinitions(Boolean latest, String deploymentKey) {
        ProcessDefinitionQuery definitionQuery = repositoryService.createProcessDefinitionQuery();
        if (deploymentKey != null) {
            Deployment deployment = repositoryService.createDeploymentQuery().deploymentKey(deploymentKey).latest().singleResult();
            if (deployment != null) {
                definitionQuery.deploymentId(deployment.getId());
            } else {
                return new ResultListDataRepresentation(new ArrayList<ProcessDefinitionRepresentation>());
            }
        } else {
            if (latest != null && latest) {
                definitionQuery.latestVersion();
            }
        }
        List<ProcessDefinition> definitions = definitionQuery.list();
        ResultListDataRepresentation result = new ResultListDataRepresentation(convertDefinitionList(definitions));
        return result;
    }

    protected List<ProcessDefinitionRepresentation> convertDefinitionList(List<ProcessDefinition> definitions) {
        Map<String, Boolean> startFormMap = new HashMap<String, Boolean>();
        List<ProcessDefinitionRepresentation> result = new ArrayList<ProcessDefinitionRepresentation>();
        if (CollectionUtils.isNotEmpty(definitions)) {
            for (ProcessDefinition processDefinition : definitions) {
                if (startFormMap.containsKey(processDefinition.getId()) == false) {
                    BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
                    List<StartEvent> startEvents = bpmnModel.getMainProcess().findFlowElementsOfType(StartEvent.clreplaced, false);
                    boolean hreplacedtartForm = false;
                    for (StartEvent startEvent : startEvents) {
                        if (StringUtils.isNotEmpty(startEvent.getFormKey())) {
                            FormDefinition formDefinition = formRepositoryService.getFormDefinitionByKey(startEvent.getFormKey());
                            if (formDefinition != null) {
                                hreplacedtartForm = true;
                                break;
                            }
                        }
                    }
                    startFormMap.put(processDefinition.getId(), hreplacedtartForm);
                }
                ProcessDefinitionRepresentation rep = new ProcessDefinitionRepresentation(processDefinition);
                rep.setHreplacedtartForm(startFormMap.get(processDefinition.getId()));
                result.add(rep);
            }
        }
        return result;
    }
}

16 Source : SerializableVariablesDiabledTest.java
with Apache License 2.0
from dingziyang

/**
 * @author Joram Barrez
 */
public clreplaced SerializableVariablesDiabledTest {

    private RepositoryService repositoryService;

    private RuntimeService runtimeService;

    private IdenreplacedyService idenreplacedyService;

    private TaskService taskService;

    private String serverUrlPrefix;

    private String testUserId;

    private String testGroupId;

    @Before
    public void setupServer() {
        if (serverUrlPrefix == null) {
            TestServer testServer = TestServerUtil.createAndStartServer(ObjectVariableSerializationDisabledApplicationConfiguration.clreplaced);
            serverUrlPrefix = testServer.getServerUrlPrefix();
            this.repositoryService = testServer.getApplicationContext().getBean(RepositoryService.clreplaced);
            this.runtimeService = testServer.getApplicationContext().getBean(RuntimeService.clreplaced);
            this.idenreplacedyService = testServer.getApplicationContext().getBean(IdenreplacedyService.clreplaced);
            this.taskService = testServer.getApplicationContext().getBean(TaskService.clreplaced);
            User user = idenreplacedyService.newUser("kermit");
            user.setFirstName("Kermit");
            user.setLastName("the Frog");
            user.setPreplacedword("kermit");
            idenreplacedyService.saveUser(user);
            Group group = idenreplacedyService.newGroup("admin");
            group.setName("Administrators");
            idenreplacedyService.saveGroup(group);
            idenreplacedyService.createMembership(user.getId(), group.getId());
            this.testUserId = user.getId();
            this.testGroupId = group.getId();
        }
    }

    @After
    public void removeUsers() {
        idenreplacedyService.deleteMembership(testUserId, testGroupId);
        idenreplacedyService.deleteGroup(testGroupId);
        idenreplacedyService.deleteUser(testUserId);
        for (Deployment deployment : repositoryService.createDeploymentQuery().list()) {
            repositoryService.deleteDeployment(deployment.getId(), true);
        }
    }

    @Test
    public void testCreateSingleSerializableProcessVariable() throws Exception {
        repositoryService.createDeployment().addClreplacedpathResource("org/activiti/rest/service/api/runtime/ProcessInstanceVariablesCollectionResourceTest.testProcess.bpmn20.xml").deploy();
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
        TestSerializableVariable serializable = new TestSerializableVariable();
        serializable.setSomeField("some value");
        // Serialize object to readable stream for representation
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutputStream output = new ObjectOutputStream(buffer);
        output.writeObject(serializable);
        output.close();
        InputStream binaryContent = new ByteArrayInputStream(buffer.toByteArray());
        // Add name, type and scope
        Map<String, String> additionalFields = new HashMap<String, String>();
        additionalFields.put("name", "serializableVariable");
        additionalFields.put("type", "serializable");
        // Upload a valid BPMN-file using multipart-data
        HttpPost httpPost = new HttpPost(serverUrlPrefix + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_VARIABLE_COLLECTION, processInstance.getId()));
        httpPost.setEnreplacedy(HttpMultipartHelper.getMultiPartEnreplacedy("value", "application/x-java-serialized-object", binaryContent, additionalFields));
        // We have serializeable object disabled, we should get a 415.
        replacedertResponseStatus(httpPost, HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE);
    }

    @Test
    public void testCreateSingleSerializableTaskVariable() throws Exception {
        repositoryService.createDeployment().addClreplacedpathResource("org/activiti/rest/service/api/runtime/ProcessInstanceVariablesCollectionResourceTest.testProcess.bpmn20.xml").deploy();
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        TestSerializableVariable serializable = new TestSerializableVariable();
        serializable.setSomeField("some value");
        // Serialize object to readable stream for representation
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutputStream output = new ObjectOutputStream(buffer);
        output.writeObject(serializable);
        output.close();
        InputStream binaryContent = new ByteArrayInputStream(buffer.toByteArray());
        // Add name, type and scope
        Map<String, String> additionalFields = new HashMap<String, String>();
        additionalFields.put("name", "serializableVariable");
        additionalFields.put("type", "serializable");
        HttpPost httpPost = new HttpPost(serverUrlPrefix + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()));
        httpPost.setEnreplacedy(HttpMultipartHelper.getMultiPartEnreplacedy("value", "application/x-java-serialized-object", binaryContent, additionalFields));
        // We have serializeable object disabled, we should get a 415.
        replacedertResponseStatus(httpPost, HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE);
    }

    public void replacedertResponseStatus(HttpUriRequest request, int expectedStatusCode) {
        CloseableHttpResponse response = null;
        try {
            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePreplacedwordCredentials credentials = new UsernamePreplacedwordCredentials("kermit", "kermit");
            provider.setCredentials(AuthScope.ANY, credentials);
            HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
            response = (CloseableHttpResponse) client.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            replacedert.replacedertEquals(expectedStatusCode, statusCode);
            if (client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
            response.close();
        } catch (ClientProtocolException e) {
            replacedert.fail(e.getMessage());
        } catch (IOException e) {
            replacedert.fail(e.getMessage());
        }
    }
}

16 Source : Extender.java
with Apache License 2.0
from dingziyang

private void checkBundle(Bundle bundle) {
    LOGGER.debug("Scanning bundle {} for activiti process", bundle.getSymbolicName());
    try {
        List<URL> pathList = new ArrayList<URL>();
        String activitiHeader = (String) bundle.getHeaders().get(BUNDLE_ACTIVITI_HEADER);
        if (activitiHeader == null) {
            activitiHeader = "OSGI-INF/activiti/";
        }
        List<PathElement> paths = HeaderParser.parseHeader(activitiHeader);
        for (PathElement path : paths) {
            String name = path.getName();
            if (name.endsWith("/")) {
                addEntries(bundle, name, "*.*", pathList);
            } else {
                String baseName;
                String filePattern;
                int pos = name.lastIndexOf('/');
                if (pos < 0) {
                    baseName = "/";
                    filePattern = name;
                } else {
                    baseName = name.substring(0, pos + 1);
                    filePattern = name.substring(pos + 1);
                }
                if (hasWildcards(filePattern)) {
                    addEntries(bundle, baseName, filePattern, pathList);
                } else {
                    addEntry(bundle, name, pathList);
                }
            }
        }
        if (!pathList.isEmpty()) {
            LOGGER.debug("Found activiti process in bundle {} with paths: {}", bundle.getSymbolicName(), pathList);
            ProcessEngine engine = (ProcessEngine) engineServiceTracker.waitForService(timeout);
            if (engine == null) {
                throw new IllegalStateException("Unable to find a ProcessEngine service");
            }
            RepositoryService service = engine.getRepositoryService();
            DeploymentBuilder builder = service.createDeployment();
            builder.name(bundle.getSymbolicName());
            for (URL url : pathList) {
                InputStream is = url.openStream();
                if (is == null) {
                    throw new IOException("Error opening url: " + url);
                }
                try {
                    builder.addInputStream(getPath(url), is);
                } finally {
                    is.close();
                }
            }
            builder.enableDuplicateFiltering();
            builder.deploy();
        } else {
            LOGGER.debug("No activiti process found in bundle {}", bundle.getSymbolicName());
        }
    } catch (Throwable t) {
        LOGGER.error("Unable to deploy activiti bundle", t);
    }
}

16 Source : PlaybackProcessStartTest.java
with Apache License 2.0
from dingziyang

public void demoCheckStatus() {
    final HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().finished().includeProcessVariables().singleResult();
    replacedertNotNull(historicProcessInstance);
    RepositoryService repositoryService = processEngine.getRepositoryService();
    final ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(historicProcessInstance.getProcessDefinitionId()).singleResult();
    replacedertEquals(SIMPLEST_PROCESS, processDefinition.getKey());
    replacedertEquals(1, historicProcessInstance.getProcessVariables().size());
    replacedertEquals(TEST_VALUE, historicProcessInstance.getProcessVariables().get(TEST_VARIABLE));
    replacedertEquals(BUSINESS_KEY, historicProcessInstance.getBusinessKey());
}

16 Source : ActivitiEndpoint.java
with Apache License 2.0
from dingziyang

/**
 * This clreplaced has been modified to be consistent with the changes to CamelBehavior and its implementations. The set of changes
 * significantly increases the flexibility of our Camel integration, as you can either choose one of three "out-of-the-box" modes,
 * or you can choose to create your own. Please reference the comments for the "CamelBehavior" clreplaced for more information on the
 * out-of-the-box implementation clreplaced options.
 *
 * @author Ryan Johnston (@rjfsu), Tijs Rademakers, Arnold Schrijver
 */
public clreplaced ActivitiEndpoint extends DefaultEndpoint {

    protected IdenreplacedyService idenreplacedyService;

    protected RuntimeService runtimeService;

    protected RepositoryService repositoryService;

    protected ActivitiConsumer activitiConsumer;

    protected boolean copyVariablesToProperties;

    protected boolean copyVariablesToBodyAsMap;

    protected boolean copyCamelBodyToBody;

    protected String copyVariablesFromProperties;

    protected String copyVariablesFromHeader;

    protected boolean copyCamelBodyToBodyreplacedtring;

    protected String processInitiatorHeaderName;

    protected Map<String, Object> returnVarMap = new HashMap<String, Object>();

    protected long timeout = 5000;

    protected int timeResolution = 100;

    public ActivitiEndpoint(String uri, CamelContext camelContext) {
        super();
        setCamelContext(camelContext);
        setEndpointUri(uri);
    }

    public void process(Exchange ex) throws Exception {
        if (activitiConsumer == null) {
            throw new ActivitiException("Activiti consumer not defined for " + getEndpointUri());
        }
        activitiConsumer.getProcessor().process(ex);
    }

    public Producer createProducer() throws Exception {
        ActivitiProducer producer = new ActivitiProducer(this, getTimeout(), getTimeResolution());
        producer.setRuntimeService(runtimeService);
        producer.setIdenreplacedyService(idenreplacedyService);
        producer.setRepositoryService(repositoryService);
        return producer;
    }

    public Consumer createConsumer(Processor processor) throws Exception {
        return new ActivitiConsumer(this, processor);
    }

    protected void addConsumer(ActivitiConsumer consumer) {
        if (activitiConsumer != null) {
            throw new ActivitiException("Activiti consumer already defined for " + getEndpointUri() + "!");
        }
        activitiConsumer = consumer;
    }

    protected void removeConsumer() {
        activitiConsumer = null;
    }

    public boolean isSingleton() {
        return true;
    }

    public void setIdenreplacedyService(IdenreplacedyService idenreplacedyService) {
        this.idenreplacedyService = idenreplacedyService;
    }

    public void setRuntimeService(RuntimeService runtimeService) {
        this.runtimeService = runtimeService;
    }

    public void setRepositoryService(RepositoryService repositoryService) {
        this.repositoryService = repositoryService;
    }

    public boolean isCopyVariablesToProperties() {
        return copyVariablesToProperties;
    }

    public void setCopyVariablesToProperties(boolean copyVariablesToProperties) {
        this.copyVariablesToProperties = copyVariablesToProperties;
    }

    public boolean isCopyCamelBodyToBody() {
        return copyCamelBodyToBody;
    }

    public void setCopyCamelBodyToBody(boolean copyCamelBodyToBody) {
        this.copyCamelBodyToBody = copyCamelBodyToBody;
    }

    public boolean isCopyVariablesToBodyAsMap() {
        return copyVariablesToBodyAsMap;
    }

    public void setCopyVariablesToBodyAsMap(boolean copyVariablesToBodyAsMap) {
        this.copyVariablesToBodyAsMap = copyVariablesToBodyAsMap;
    }

    public String getCopyVariablesFromProperties() {
        return copyVariablesFromProperties;
    }

    public void setCopyVariablesFromProperties(String copyVariablesFromProperties) {
        this.copyVariablesFromProperties = copyVariablesFromProperties;
    }

    public String getCopyVariablesFromHeader() {
        return copyVariablesFromHeader;
    }

    public void setCopyVariablesFromHeader(String copyVariablesFromHeader) {
        this.copyVariablesFromHeader = copyVariablesFromHeader;
    }

    public boolean isCopyCamelBodyToBodyreplacedtring() {
        return copyCamelBodyToBodyreplacedtring;
    }

    public void setCopyCamelBodyToBodyreplacedtring(boolean copyCamelBodyToBodyreplacedtring) {
        this.copyCamelBodyToBodyreplacedtring = copyCamelBodyToBodyreplacedtring;
    }

    public boolean isSetProcessInitiator() {
        return StringUtils.isNotEmpty(getProcessInitiatorHeaderName());
    }

    public Map<String, Object> getReturnVarMap() {
        return returnVarMap;
    }

    public void setReturnVarMap(Map<String, Object> returnVarMap) {
        this.returnVarMap = returnVarMap;
    }

    public String getProcessInitiatorHeaderName() {
        return processInitiatorHeaderName;
    }

    public void setProcessInitiatorHeaderName(String processInitiatorHeaderName) {
        this.processInitiatorHeaderName = processInitiatorHeaderName;
    }

    @Override
    public boolean isLenientProperties() {
        return true;
    }

    public long getTimeout() {
        return timeout;
    }

    public int getTimeResolution() {
        return timeResolution;
    }
}

16 Source : TextQueryTest.java
with MIT License
from CoderDream

public static void main(String[] args) throws Exception {
    // 新建流程引擎
    ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
    // 存储服务
    RepositoryService repositoryService = engine.getRepositoryService();
    // 新建部署构造器
    DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
    deploymentBuilder.addClreplacedpathResource("my_text.txt");
    Deployment deployment = deploymentBuilder.deploy();
    // 数据查询
    InputStream inputStream = repositoryService.getResourcereplacedtream(deployment.getId(), "my_text.txt");
    int count = inputStream.available();
    byte[] contents = new byte[count];
    inputStream.read(contents);
    String result = new String(contents);
    // 输入结果
    System.out.println(result);
    // 关闭流程引擎
    engine.close();
}

16 Source : AddBpmnModelTest.java
with MIT License
from CoderDream

public static void main(String[] args) throws Exception {
    // 新建流程引擎
    ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
    // 存储服务
    RepositoryService repositoryService = engine.getRepositoryService();
    // 新建部署构造器
    DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
    String resourceName = "My Process";
    BpmnModel bpmnModel = createProcessModel();
    // 发布部署构造器
    deploymentBuilder.addBpmnModel(resourceName, bpmnModel);
    // 发布部署构造器
    deploymentBuilder.deploy();
    // 关闭流程引擎
    engine.close();
}

16 Source : ProcessBatchPreparation.java
with Apache License 2.0
from cijujoseph

@Component("processBatchPreparation")
public clreplaced ProcessBatchPreparation {

    protected static final Logger logger = LoggerFactory.getLogger(ProcessBatchPreparation.clreplaced);

    @Value("${replacedytics.excludedProcessDefinitionKeys}")
    private String excludedProcessDefinitionKeys;

    @Value("${replacedytics.sql.queryBatchSize}")
    private String queryBatchSize;

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");

    @Autowired
    private ActivitiEventLogRepository activitiEventLogRepository;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired(required = false)
    private ProcessedActivitiEventsRepository processedActivitiEventsRepository;

    @Value("${replacedytics.dbType}")
    private String dbType;

    @Value("${replacedytics.isEnterprise}")
    private String isEnterprise;

    @Value("${replacedytics.eventSource.isProcessedEventsTable}")
    private String isProcessedEventsTable;

    public Map<String, Object> getBatchMetadata(String lastUpdatedTimestamp) throws ParseException {
        Map<String, Object> batchMetadata = new HashMap<String, Object>();
        String maxTimeStamp = getMostRecentTimestamp(lastUpdatedTimestamp);
        if (maxTimeStamp != null) {
            // Get a list of processes instances
            List<Map<String, Object>> processIdQueryList = getProcessIdList(lastUpdatedTimestamp, maxTimeStamp);
            if (processIdQueryList != null && processIdQueryList.size() > 0) {
                batchMetadata.put("newEventsExist", true);
                batchMetadata.put("toTimestamp", maxTimeStamp);
                batchMetadata.put("processIdList", processIdQueryList);
            } else {
                batchMetadata.put("newEventsExist", false);
            }
            logger.info("done!");
        } else {
            batchMetadata.put("newEventsExist", false);
        }
        return batchMetadata;
    }

    private List<String> getExcludedProcessIds() {
        String[] excludedProcessDefinitionKeyArray = excludedProcessDefinitionKeys.split("\\s*,\\s*");
        List<String> excludedIdList = new ArrayList<String>();
        for (String excludedProcessDefinitionKey : excludedProcessDefinitionKeyArray) {
            List<ProcessDefinition> excludedProcessDefinitions = repositoryService.createProcessDefinitionQuery().processDefinitionKey(excludedProcessDefinitionKey).list();
            for (ProcessDefinition excludedProcessDefinition : excludedProcessDefinitions) {
                excludedIdList.add(excludedProcessDefinition.getId());
            }
        }
        if (excludedIdList.size() == 0) {
            excludedIdList.add("");
        }
        return excludedIdList;
    }

    private List<Map<String, Object>> getProcessIdList(String lastUpdatedTimestamp, String maxTimeStamp) throws ParseException {
        List<Map<String, Object>> processIdQueryList;
        if (isEnterprise.equals("true") && isProcessedEventsTable.equals("true")) {
            processIdQueryList = processedActivitiEventsRepository.findUniqueProcessList(df.parse(lastUpdatedTimestamp), df.parse(maxTimeStamp), getExcludedProcessIds());
        } else {
            processIdQueryList = activitiEventLogRepository.findUniqueProcessList(df.parse(lastUpdatedTimestamp), df.parse(maxTimeStamp), getExcludedProcessIds());
        }
        logger.info("getProcessIdList() SQL Response: " + processIdQueryList);
        return processIdQueryList;
    }

    private String getMostRecentTimestamp(String lastUpdatedTimestamp) throws ParseException {
        if (isEnterprise.equals("true") && isProcessedEventsTable.equals("true")) {
            if (dbType.equals("PostgreSQL")) {
                return processedActivitiEventsRepository.getMaxTimestampPostgres(df.parse(lastUpdatedTimestamp), queryBatchSize, getExcludedProcessIds());
            } else {
                return processedActivitiEventsRepository.getMaxTimestamp(df.parse(lastUpdatedTimestamp), queryBatchSize, getExcludedProcessIds());
            }
        } else {
            if (dbType.equals("PostgreSQL")) {
                return activitiEventLogRepository.getMaxTimestampPostgres(df.parse(lastUpdatedTimestamp), queryBatchSize, getExcludedProcessIds());
            } else {
                return activitiEventLogRepository.getMaxTimestamp(df.parse(lastUpdatedTimestamp), queryBatchSize, getExcludedProcessIds());
            }
        }
    }
}

15 Source : BaseWorkflowService.java
with Apache License 2.0
from Yiuman

protected void setCandidateOrreplacedigned(Task task, ProcessPersonalModel model) {
    task.getProcessInstanceId();
    TaskService taskService = getProcessEngine().getTaskService();
    // 查询当前任务是否已经有候选人或办理人
    RepositoryService repositoryService = getProcessEngine().getRepositoryService();
    BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
    FlowElement flowElement = bpmnModel.getFlowElement(task.getTaskDefinitionKey());
    if (flowElement instanceof UserTask) {
        UserTask userTask = (UserTask) flowElement;
        List<String> taskCandidateUsersDefine = userTask.getCandidateUsers();
        // 没有负责人,则用解析器解析流程任务定义的候选人或参数传入来的候选人
        if (StringUtils.isBlank(task.getreplacedignee())) {
            List<String> allCandidateOrreplacedigned = new ArrayList<>();
            allCandidateOrreplacedigned.addAll(model.getCandidateOrreplacedigned());
            allCandidateOrreplacedigned.addAll(taskCandidateUsersDefine);
            // 删除任务候选人
            allCandidateOrreplacedigned.forEach(candidateDefine -> taskService.deleteCandidateUser(task.getId(), candidateDefine));
            RuntimeService runtimeService = getProcessEngine().getRuntimeService();
            WorkflowContextImpl workflowContext = WorkflowContextImpl.builder().processInstance(runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult()).task(task).flowElement(flowElement).currentUserId(model.getUserId()).build();
            // 解析器解析完成后,把真正的候选人添加到任务中去
            Optional.ofNullable(getTaskCandidateResolver().resolve(workflowContext, allCandidateOrreplacedigned)).ifPresent(resolvedCandidates -> {
                if (resolvedCandidates.size() == 1) {
                    taskService.setreplacedignee(task.getId(), resolvedCandidates.get(1));
                } else {
                    resolvedCandidates.forEach(realUserId -> taskService.addCandidateUser(task.getId(), realUserId));
                }
            });
        }
    }
}

15 Source : WorkflowCreateServiceImpl.java
with Apache License 2.0
from yfh0918

@SuppressWarnings("unchecked")
@Component
public clreplaced WorkflowCreateServiceImpl implements WorkflowCreateService {

    private static Logger logger = LoggerFactory.getLogger(WorkflowCreateService.clreplaced);

    @Autowired
    private RepositoryService repositoryService;

    /*Model*/
    @Override
    public BpmnModel createBpmnModel() {
        return new BpmnModel();
    }

    @Override
    public BpmnModel createBpmnModel(String json) {
        Map<String, Object> diagramMap = createDiagramMap(json);
        return createBpmnModel(diagramMap);
    }

    @Override
    public BpmnModel createBpmnModel(Map<String, Object> diagramMap) {
        List<Map<String, Object>> processList = (List<Map<String, Object>>) diagramMap.get(PROCESS);
        List<Process> processObjList = new ArrayList<>();
        for (Map<String, Object> process : processList) {
            if (process.get(NAME) == null) {
                process.put(NAME, process.get(ID));
            }
            Process processObj = createProcess(process.get(ID).toString(), process.get(NAME).toString());
            processObjList.add(processObj);
            // START_EVENT
            Map<String, Object> startEvent = (Map<String, Object>) process.get(START_EVENT);
            processObj.addFlowElement(createStartEvent(startEvent));
            // USER_TASK
            if (process.get(USER_TASK) != null) {
                List<Map<String, Object>> userTaskList = (List<Map<String, Object>>) process.get(USER_TASK);
                for (Map<String, Object> userTask : userTaskList) {
                    processObj.addFlowElement(createUserTask(userTask));
                }
            }
            // PA_GW
            if (process.get(PA_GW) != null) {
                List<Map<String, Object>> paGatewayList = (List<Map<String, Object>>) process.get(PA_GW);
                for (Map<String, Object> paGateway : paGatewayList) {
                    processObj.addFlowElement(createParallelGateway(paGateway));
                }
            }
            // EX_GW
            if (process.get(EX_GW) != null) {
                List<Map<String, Object>> exGatewayList = (List<Map<String, Object>>) process.get(EX_GW);
                for (Map<String, Object> exGateway : exGatewayList) {
                    processObj.addFlowElement(createExclusiveGateway(exGateway));
                }
            }
            // END_EVENT
            Map<String, Object> endEvent = (Map<String, Object>) process.get(END_EVENT);
            processObj.addFlowElement(createEndEvent(endEvent));
            // SEQUENCE_FLOW
            if (process.get(SEQUENCE_FLOW) != null) {
                List<Map<String, Object>> sequenceFlowList = (List<Map<String, Object>>) process.get(SEQUENCE_FLOW);
                for (Map<String, Object> sequenceFlow : sequenceFlowList) {
                    processObj.addFlowElement(createSequenceFlow(sequenceFlow));
                }
            }
        }
        BpmnModel bpmnModel = new BpmnModel();
        for (Process process : processObjList) {
            bpmnModel.addProcess(process);
        }
        return bpmnModel;
    }

    /*Process*/
    @Override
    public Process createProcess(String id, String name) {
        Process process = new Process();
        process.setId(id);
        process.setName(name);
        return process;
    }

    @Override
    public List<Map<String, Object>> getAllProcess(Map<String, Object> diagramMap) {
        return (List<Map<String, Object>>) diagramMap.get(PROCESS);
    }

    /*任务节点*/
    @Override
    public UserTask createUserTask(String id, String name) {
        return createUserTask(id, name, null);
    }

    @Override
    public UserTask createUserTask(String id, String name, List<String> candidateGroups) {
        UserTask userTask = new UserTask();
        userTask.setName(name);
        userTask.setId(id);
        if (candidateGroups != null) {
            userTask.setCandidateGroups(candidateGroups);
        }
        return userTask;
    }

    @Override
    public UserTask createUserTask(Map<String, Object> userTaskMap) {
        return BeanUtil.toBean(UserTask.clreplaced, JacksonUtil.toJson(userTaskMap), true);
    }

    @Override
    public List<Map<String, Object>> getAllTaskMap(Map<String, Object> processMap) {
        return (List<Map<String, Object>>) processMap.get(USER_TASK);
    }

    /*连线*/
    @Override
    public SequenceFlow createSequenceFlow(String sourceRef, String targetRef) {
        return createSequenceFlow(sourceRef, targetRef, null, null);
    }

    @Override
    public SequenceFlow createSequenceFlow(String sourceRef, String targetRef, String name) {
        return createSequenceFlow(sourceRef, targetRef, name, null);
    }

    @Override
    public SequenceFlow createSequenceFlow(String sourceRef, String targetRef, String name, String conditionExpression) {
        SequenceFlow flow = new SequenceFlow();
        flow.setSourceRef(sourceRef);
        flow.setTargetRef(targetRef);
        if (!StringUtils.isEmpty(name)) {
            flow.setName(name);
        }
        if (!StringUtils.isEmpty(conditionExpression)) {
            flow.setConditionExpression(conditionExpression);
        }
        return flow;
    }

    @Override
    public SequenceFlow createSequenceFlow(Map<String, Object> sequenceFlowMap) {
        return BeanUtil.toBean(SequenceFlow.clreplaced, JacksonUtil.toJson(sequenceFlowMap), true);
    }

    @Override
    public List<Map<String, Object>> getAllSequenceFlowMap(Map<String, Object> processMap) {
        return (List<Map<String, Object>>) processMap.get(SEQUENCE_FLOW);
    }

    /*排他网关*/
    @Override
    public ExclusiveGateway createExclusiveGateway(String id) {
        return createExclusiveGateway(id, null);
    }

    @Override
    public ExclusiveGateway createExclusiveGateway(String id, String name) {
        ExclusiveGateway exclusiveGateway = new ExclusiveGateway();
        exclusiveGateway.setId(id);
        if (!StringUtils.isEmpty(name)) {
            exclusiveGateway.setName(name);
        }
        return exclusiveGateway;
    }

    @Override
    public ExclusiveGateway createExclusiveGateway(Map<String, Object> exclusiveGatewayMap) {
        return BeanUtil.toBean(ExclusiveGateway.clreplaced, JacksonUtil.toJson(exclusiveGatewayMap), true);
    }

    @Override
    public List<Map<String, Object>> getAllExclusiveGatewayMap(Map<String, Object> processMap) {
        return (List<Map<String, Object>>) processMap.get(EX_GW);
    }

    /*并行网关*/
    @Override
    public ParallelGateway createParallelGateway(String id) {
        return createParallelGateway(id, null);
    }

    @Override
    public ParallelGateway createParallelGateway(String id, String name) {
        ParallelGateway parallelGateway = new ParallelGateway();
        parallelGateway.setId(id);
        if (!StringUtils.isEmpty(name)) {
            parallelGateway.setName(name);
        }
        return parallelGateway;
    }

    @Override
    public ParallelGateway createParallelGateway(Map<String, Object> parallelGatewayMap) {
        return BeanUtil.toBean(ParallelGateway.clreplaced, JacksonUtil.toJson(parallelGatewayMap), true);
    }

    @Override
    public List<Map<String, Object>> getAllParallelGatewayMap(Map<String, Object> processMap) {
        return (List<Map<String, Object>>) processMap.get(PA_GW);
    }

    /*开始节点*/
    @Override
    public StartEvent createStartEvent() {
        return createStartEvent(null, null);
    }

    @Override
    public StartEvent createStartEvent(String id, String name) {
        StartEvent startEvent = new StartEvent();
        if (StringUtils.isEmpty(id)) {
            id = "startEvent";
        }
        startEvent.setId(id);
        if (!StringUtils.isEmpty(name)) {
            startEvent.setName(name);
        }
        return startEvent;
    }

    @Override
    public StartEvent createStartEvent(Map<String, Object> startEventMap) {
        return BeanUtil.toBean(StartEvent.clreplaced, JacksonUtil.toJson(startEventMap), true);
    }

    /*结束节点*/
    @Override
    public EndEvent createEndEvent() {
        return createEndEvent(null, null);
    }

    @Override
    public EndEvent createEndEvent(String id, String name) {
        EndEvent endEvent = new EndEvent();
        if (StringUtils.isEmpty(id)) {
            id = "endEvent";
        }
        endEvent.setId(id);
        if (!StringUtils.isEmpty(name)) {
            endEvent.setName(name);
        }
        return endEvent;
    }

    @Override
    public EndEvent createEndEvent(Map<String, Object> endEventMap) {
        return BeanUtil.toBean(EndEvent.clreplaced, JacksonUtil.toJson(endEventMap), true);
    }

    /**
     * 动态创建流程Map
     *
     * @param map
     */
    @Override
    public Map<String, Object> createDiagramMap(String json) {
        return JacksonUtil.toObj(json, new TypeReference<Map<String, Object>>() {
        });
    }

    /**
     * 动态创建流程
     *
     * @param WorkflowDto dto
     */
    @Override
    @Transactional
    public String createDiagram(String name, Process... processes) {
        BpmnModel bpmnModel = createBpmnModel();
        return createDiagram(name, bpmnModel, processes);
    }

    @Override
    @Transactional
    public String createDiagram(String name, BpmnModel bpmnModel, Process... processes) {
        if (processes != null) {
            for (Process process : processes) {
                bpmnModel.addProcess(process);
            }
        }
        // 2. Generate graphical information
        new BpmnAutoLayout(bpmnModel).execute();
        // 3. Deploy the process to the engine
        Deployment deployment = repositoryService.createDeployment().addBpmnModel(prefix + name + suffix, bpmnModel).name(name).deploy();
        // save bpmn
        try {
            InputStream processBpmn = repositoryService.getResourcereplacedtream(deployment.getId(), prefix + name + suffix);
            String fileName = FileUtil.getFullPath(prefix + name + suffix);
            FileUtils.copyInputStreamToFile(processBpmn, new File(fileName));
        } catch (Exception ex) {
            logger.error("create BPMN file error:{}", ex);
        }
        return deployment.getId();
    }

    /**
     * 部署单个流程定义
     *
     * @param WorkflowDto dto
     */
    @Override
    @Transactional
    public WorkflowDto deployDiagram(String name, String exportDir) {
        WorkflowDto result = new WorkflowDto();
        if (StringUtil.isEmpty(name)) {
            result.setMessage(WorkflowDto.MESSAGE_INFO[1]);
            result.setCode(String.valueOf(Constant.RESULT_FAIL));
            return result;
        }
        try {
            // 载入流程
            ResourceLoader resourceLoader = new DefaultResourceLoader();
            String clreplacedpathResourceUrl = prefix + name + suffix;
            logger.debug("read workflow from: {}", clreplacedpathResourceUrl);
            Resource resource = resourceLoader.getResource(clreplacedpathResourceUrl);
            InputStream inputStream = null;
            inputStream = resource.getInputStream();
            if (inputStream == null) {
                logger.warn("ignore deploy workflow module: {}", clreplacedpathResourceUrl);
            } else {
                logger.debug("finded workflow module: {}, deploy it!", clreplacedpathResourceUrl);
                Deployment deployment = repositoryService.createDeployment().name(name).addClreplacedpathResource(clreplacedpathResourceUrl).deploy();
                // export diagram
                List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).list();
                result.setDeploymentId(deployment.getId());
                if (!StringUtil.isEmpty(exportDir)) {
                    for (ProcessDefinition processDefinition : list) {
                        WorkflowUtils.exportDiagramToFile(repositoryService, processDefinition, exportDir);
                    }
                }
            }
            result.setCode(Constant.RESULT_SUCCESS);
        } catch (Exception ex) {
            logger.error("异常", ex);
            result.setCode(String.valueOf(Constant.RESULT_FAIL));
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 删除部署的流程,级联删除流程实例
     *
     * @param deploymentId 流程部署ID
     */
    @Override
    @Transactional
    public WorkflowDto deleteDiagram(String deploymentId) {
        // 参数检查
        WorkflowDto dto = new WorkflowDto();
        if (StringUtil.isEmpty(deploymentId)) {
            dto.setMessage(WorkflowDto.MESSAGE_INFO[5]);
            dto.setCode(String.valueOf(Constant.RESULT_FAIL));
            return dto;
        }
        // 删除发布图
        try {
            repositoryService.deleteDeployment(deploymentId, true);
            dto.setCode(Constant.RESULT_SUCCESS);
        } catch (Exception ex) {
            logger.error("异常", ex);
            dto.setCode(String.valueOf(Constant.RESULT_FAIL));
            dto.setMessage(ex.getMessage());
        }
        return dto;
    }

    /**
     * 获取流程
     *
     * @param enreplacedy
     */
    @Override
    public WorkflowDto getDiagram(String processDefinitionId) {
        // 参数检查
        WorkflowDto dto = new WorkflowDto();
        if (StringUtil.isEmpty(processDefinitionId)) {
            dto.setMessage(WorkflowDto.MESSAGE_INFO[13]);
            dto.setCode(String.valueOf(Constant.RESULT_FAIL));
            return dto;
        }
        InputStream processDiagram = repositoryService.getProcessDiagram(processDefinitionId);
        dto.setProcessDiagram(processDiagram);
        dto.setCode(Constant.RESULT_SUCCESS);
        return dto;
    }

    /**
     * 查询当前系统中已经部署的流程
     *
     * @return 流程的名称和key的集合
     * @throws Exception
     */
    @Override
    public WorkflowDto getAllDeployment() {
        List<Deployment> deploymentList = repositoryService.createDeploymentQuery().list();
        // 查询ACT_RE_PROCDEF,获取中文名称  只有开启流程才会有中文名称
        List<Map<String, Object>> resultList = new ArrayList<>();
        String key;
        InputStream resouceStream;
        InputStreamReader in;
        XMLStreamReader xtr;
        BpmnModel model;
        XMLInputFactory xif = XMLInputFactory.newInstance();
        List<Process> processes;
        for (Deployment deployment : deploymentList) {
            // 获取部署的流程的key名称
            key = deployment.getName();
            // 由于没有启动的流程回去不到中文名称,只能从生成xml文件读取
            try {
                resouceStream = repositoryService.getResourcereplacedtream(deployment.getId(), prefix + key + suffix);
                in = new InputStreamReader(resouceStream, Constant.UTF_CODE);
                xtr = xif.createXMLStreamReader(in);
            } catch (Exception e) {
                logger.error("解析工作流文件出错,ERROR:", e);
                continue;
            }
            model = new BpmnXMLConverter().convertToBpmnModel(xtr);
            // 创建map,存放流程的key及中文名称
            processes = model.getProcesses();
            if (CollectionUtil.isEmpty(processes)) {
                continue;
            }
            Map<String, Object> tmpMap = new HashMap<>();
            tmpMap.put("showValue", processes.get(0).getDoreplacedentation());
            tmpMap.put("definitionKey", processes.get(0).getId());
            resultList.add(tmpMap);
        }
        WorkflowDto dto = new WorkflowDto();
        dto.setData(resultList);
        return dto;
    }
}

15 Source : ActUtils.java
with Apache License 2.0
from Xiao-Y

/**
 * 流程图生成工具
 *
 * @author liuyongtao
 * @create 2019-08-27 8:31
 */
public clreplaced ActUtils {

    private static Logger logger = LoggerFactory.getLogger(ActUtils.clreplaced);

    @Autowired
    private HistoryService historyService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    /**
     * 获取原始的流程图
     *
     * @param deploymentId 部署id
     * @return java.io.InputStream
     * @author LiuYongTao
     * @date 2019/8/27 12:22
     */
    public InputStream genOriginalProcessImage(String deploymentId) {
        InputStream imageStream = null;
        if (deploymentId == null || "".equals(deploymentId)) {
            logger.error("deploymentId is null");
            return imageStream;
        }
        try {
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
            if (processDefinition == null) {
                logger.error("deploymentId:{},没有查询到流程定义", deploymentId);
                return imageStream;
            }
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            imageStream = new CustomProcessDiagramGenerator().generatePngDiagram(bpmnModel);
        } catch (Exception e) {
            logger.error("deploymentId:" + deploymentId + "生成流程图失败,原因:" + e.getMessage(), e);
        }
        return imageStream;
    }

    /**
     * 获取流程图,并且显示活动节点(显示运行轨迹)
     *
     * @param processInstanceId 流程实例ID
     * @return 流程图输入流
     */
    public InputStream genActiveProccessImage(String processInstanceId) {
        InputStream imageStream = null;
        if (processInstanceId == null || "".equals(processInstanceId)) {
            logger.error("processInstanceId is null");
            return imageStream;
        }
        try {
            // 查询历史流程实例
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            // 查询流程定义对象
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(historicProcessInstance.getProcessDefinitionId()).singleResult();
            // 查询已经执行过的流程节点,包括Gateway等
            List<HistoricActivityInstance> highLightedActivitList = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).list();
            // 高亮线路id集合
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            List<String> highLightedFlows = this.getHighLightedFlows(bpmnModel, highLightedActivitList);
            logger.debug("Executed flow : {}", highLightedFlows);
            // 高亮环节id集合
            List<String> highLightedActivities = new ArrayList<>();
            for (HistoricActivityInstance tempActivity : highLightedActivitList) {
                String activityId = tempActivity.getActivityId();
                highLightedActivities.add(activityId);
            }
            logger.debug("Executed activity: {}", highLightedActivities);
            // 得到正在执行的Activity的Id
            List<String> activityIds = this.getCurrrentActivity(processInstanceId);
            logger.debug("Current activity ids : {}", activityIds);
            imageStream = new CustomProcessDiagramGenerator().generateDiagram(bpmnModel, highLightedActivities, highLightedFlows, activityIds);
        } catch (Exception e) {
            logger.error("processInstanceId:" + processInstanceId + "生成流程图失败,原因:" + e.getMessage(), e);
        }
        return imageStream;
    }

    /**
     * 获取已经执行过的流程线,用于高亮显示
     *
     * @param bpmnModel
     * @param historicActivityInstances
     * @return java.util.List<java.lang.String>
     * @author billow
     * @date 2019/9/14 11:52
     */
    public List<String> getHighLightedFlows(BpmnModel bpmnModel, List<HistoricActivityInstance> historicActivityInstances) {
        // 24小时制
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 用以保存高亮的线flowId
        List<String> highFlows = new ArrayList<>();
        // 对历史流程节点进行遍历
        for (int i = 0; i < historicActivityInstances.size() - 1; i++) {
            // 获得当前活动对应的节点信息
            FlowNode activityImpl = (FlowNode) bpmnModel.getMainProcess().getFlowElement(historicActivityInstances.get(i).getActivityId());
            // 用以保存后续开始时间相同的节点
            List<FlowNode> sameStartTimeNodes = new ArrayList<>();
            // 找到紧跟在后面的一个节点
            FlowNode sameActivityImpl1 = null;
            // 第一个节点
            HistoricActivityInstance activityImpl_ = historicActivityInstances.get(i);
            for (int k = i + 1; k <= historicActivityInstances.size() - 1; k++) {
                // 后续第1个节点
                HistoricActivityInstance activityImp2_ = historicActivityInstances.get(k);
                // 都是usertask,且主节点与后续节点的开始时间相同,说明不是真实的后继节点
                if (activityImpl_.getActivityType().equals("userTask") && activityImp2_.getActivityType().equals("userTask") && df.format(activityImpl_.getStartTime()).equals(df.format(activityImp2_.getStartTime()))) {
                } else {
                    // 找到紧跟在后面的一个节点
                    sameActivityImpl1 = (FlowNode) bpmnModel.getMainProcess().getFlowElement(historicActivityInstances.get(k).getActivityId());
                    break;
                }
            }
            // 将后面第一个节点放在时间相同节点的集合里
            sameStartTimeNodes.add(sameActivityImpl1);
            for (int j = i + 1; j < historicActivityInstances.size() - 1; j++) {
                // 后续第一个节点
                HistoricActivityInstance activityImpl1 = historicActivityInstances.get(j);
                // 后续第二个节点
                HistoricActivityInstance activityImpl2 = historicActivityInstances.get(j + 1);
                // 如果第一个节点和第二个节点开始时间相同保存
                if (df.format(activityImpl1.getStartTime()).equals(df.format(activityImpl2.getStartTime()))) {
                    FlowNode sameActivityImpl2 = (FlowNode) bpmnModel.getMainProcess().getFlowElement(activityImpl2.getActivityId());
                    sameStartTimeNodes.add(sameActivityImpl2);
                } else {
                    // 有不相同跳出循环
                    break;
                }
            }
            // 获得当前活动对应的节点的所有出去的线信息
            List<SequenceFlow> pvmTransitions = activityImpl.getOutgoingFlows();
            // 对所有的线进行遍历
            for (SequenceFlow pvmTransition : pvmTransitions) {
                // 如果取出的线的目标节点存在时间相同的节点里,保存该线的id,进行高亮显示
                FlowNode pvmActivityImpl = (FlowNode) bpmnModel.getMainProcess().getFlowElement(pvmTransition.getTargetRef());
                if (sameStartTimeNodes.contains(pvmActivityImpl)) {
                    highFlows.add(pvmTransition.getId());
                }
            }
        }
        return highFlows;
    }

    /**
     * 获取流程当前的节点
     *
     * @param processInstanceId
     * @return java.util.List<java.lang.String>
     * @author LiuYongTao
     * @date 2019/8/27 8:57
     */
    private List<String> getCurrrentActivity(String processInstanceId) {
        List<String> activityIds = new ArrayList<>();
        // 查询流程当前活动的执行对象,代办任务节点
        List<Execution> executions = runtimeService.createExecutionQuery().processInstanceId(processInstanceId).list();
        for (Execution exe : executions) {
            List<String> ids = runtimeService.getActiveActivityIds(exe.getId());
            activityIds.addAll(ids);
        }
        return activityIds;
    }
}

15 Source : ProcessServiceImpl.java
with MIT License
from wligang

/**
 * @author Ligang.Wang[@wlgdo.com]
 */
@Service
@AllArgsConstructor
public clreplaced ProcessServiceImpl implements ProcessService {

    private final RepositoryService repositoryService;

    private final RuntimeService runtimeService;

    private final LeaveBillMapper leaveBillMapper;

    /**
     * 分页流程列表
     *
     * @param params
     * @return
     */
    @Override
    public IPage<ProcessDefDTO> getProcessByPage(ProcessDTO params) {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionTenantId(String.valueOf(0)).latestVersion();
        String category = params.getCategory();
        if (StrUtil.isNotBlank(category)) {
            query.processDefinitionCategory(category);
        }
        int page = params.getCurrent() == null ? 1 : params.getCurrent();
        int limit = params.getCurrent() == null ? 20 : params.getSize();
        IPage result = new Page(page, limit);
        result.setTotal(query.count());
        List<ProcessDefDTO> deploymentList = query.listPage((page - 1) * limit, limit).stream().map(processDefinition -> {
            Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(processDefinition.getDeploymentId()).singleResult();
            return ProcessDefDTO.toProcessDefDTO(processDefinition, deployment);
        }).collect(Collectors.toList());
        result.setRecords(deploymentList);
        return result;
    }

    /**
     * 读取xml/image资源
     *
     * @param procDefId
     * @param proInsId
     * @param resType
     * @return
     */
    @Override
    public InputStream readResource(String procDefId, String proInsId, String resType) {
        if (StrUtil.isBlank(procDefId)) {
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(proInsId).singleResult();
            procDefId = processInstance.getProcessDefinitionId();
        }
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(procDefId).singleResult();
        String resourceName = "";
        if (ResourceTypeEnum.IMAGE.getType().equals(resType)) {
            resourceName = processDefinition.getDiagramResourceName();
        } else if (ResourceTypeEnum.XML.getType().equals(resType)) {
            resourceName = processDefinition.getResourceName();
        }
        InputStream resourcereplacedtream = repositoryService.getResourcereplacedtream(processDefinition.getDeploymentId(), resourceName);
        return resourcereplacedtream;
    }

    /**
     * 更新状态
     *
     * @param status
     * @param procDefId
     * @return
     */
    @Override
    public Boolean updateStatus(String status, String procDefId) {
        if (ProcessStatusEnum.ACTIVE.getStatus().equals(status)) {
            repositoryService.activateProcessDefinitionById(procDefId, true, null);
        } else if (ProcessStatusEnum.SUSPEND.getStatus().equals(status)) {
            repositoryService.suspendProcessDefinitionById(procDefId, true, null);
        }
        return Boolean.TRUE;
    }

    /**
     * 删除部署的流程,级联删除流程实例
     *
     * @param deploymentId
     * @return
     */
    @Override
    public Boolean removeProcIns(String deploymentId) {
        repositoryService.deleteDeployment(deploymentId, true);
        return Boolean.TRUE;
    }

    /**
     * 启动流程、更新请假单状态
     *
     * @param leaveId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.clreplaced)
    public Boolean saveStartProcess(Integer leaveId) {
        LeaveBill leaveBill = leaveBillMapper.selectById(leaveId);
        leaveBill.setState("LeaveBill");
        String key = leaveBill.getClreplaced().getSimpleName();
        String businessKey = key + "_" + leaveBill.getLeaveId();
        runtimeService.startProcessInstanceByKeyAndTenantId(key, businessKey, String.valueOf(0));
        leaveBillMapper.updateById(leaveBill);
        return Boolean.TRUE;
    }
}

15 Source : EditorServiceImpl.java
with MIT License
from wligang

@Slf4j
@Service
@AllArgsConstructor
public clreplaced EditorServiceImpl implements EditorService {

    private final RepositoryService repositoryService;

    private final ObjectMapper objectMapper;

    /**
     * 获取设计器页面的json
     *
     * @return
     */
    @Override
    public Object getStencilset() {
        InputStream stencilsetStream = this.getClreplaced().getClreplacedLoader().getResourcereplacedtream("stencilset.json");
        try {
            return IOUtils.toString(stencilsetStream, String.valueOf(StandardCharsets.UTF_8));
        } catch (Exception e) {
            log.error("Error while loading stencil set", e);
            throw new ActivitiException("Error while loading stencil set", e);
        }
    }

    /**
     * 根据modelId获取model
     *
     * @param modelId
     * @return
     */
    @Override
    public Object getEditorJson(String modelId) {
        ObjectNode modelNode;
        Model model = repositoryService.getModel(modelId);
        if (model != null) {
            try {
                if (StringUtils.isNotEmpty(model.getMetaInfo())) {
                    modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
                } else {
                    modelNode = objectMapper.createObjectNode();
                    modelNode.put(MODEL_NAME, model.getName());
                }
                byte[] source = repositoryService.getModelEditorSource(model.getId());
                modelNode.put(MODEL_ID, model.getId());
                String jsonXml = new String(source, StandardCharsets.UTF_8);
                ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(StringEscapeUtils.unescapeHtml4(jsonXml));
                modelNode.set("model", editorJsonNode);
                return modelNode;
            } catch (Exception e) {
                log.error("Error creating model JSON", e);
                throw new ActivitiException("Error creating model JSON", e);
            }
        }
        return null;
    }

    /**
     * 保存model信息
     *
     * @param modelId
     * @param name
     * @param description
     * @param jsonXml
     * @param svgXml
     */
    @Override
    public void saveModel(String modelId, String name, String description, String jsonXml, String svgXml) {
        try {
            Model model = repositoryService.getModel(modelId);
            ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
            modelJson.put(MODEL_NAME, name);
            modelJson.put(MODEL_DESCRIPTION, description);
            model.setMetaInfo(modelJson.toString());
            model.setName(name);
            // todo 暂时注释掉
            // model.setTenantId(String.valueOf(TenantContextHolder.getTenantId()));
            JSONObject jsonObject = JSONUtil.parseObj(StringEscapeUtils.unescapeHtml4(jsonXml));
            JSONObject properties = jsonObject.getJSONObject("properties");
            properties.put("process_id", model.getKey());
            model.setName(properties.getStr("name"));
            repositoryService.saveModel(model);
            jsonObject.put("properties", properties);
            repositoryService.addModelEditorSource(model.getId(), jsonObject.toString().getBytes(StandardCharsets.UTF_8));
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            final byte[] result = outStream.toByteArray();
            repositoryService.addModelEditorSourceExtra(model.getId(), result);
            outStream.close();
            log.info("保存模型成功:{}", JSONUtil.toJsonStr(model));
        } catch (Exception e) {
            log.error("Error saving model", e);
            throw new ActivitiException("Error saving model", e);
        }
    }
}

15 Source : ActivitiModelServiceImpl.java
with Apache License 2.0
from weizhiqiang1995

@Service
public clreplaced ActivitiModelServiceImpl implements ActivitiModelService {

    @Autowired
    private ProcessEngine processEngine;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RepositoryService repositoryService;

    /**
     * @replacedle: insertNewActivitiModel
     * @Description: 新建一个空模型
     * @param @param inputObject
     * @param @param outputObject
     * @param @throws Exception    参数
     * @return void    返回类型
     * @throws
     */
    @SuppressWarnings("deprecation")
    @Override
    public void insertNewActivitiModel(InputObject inputObject, OutputObject outputObject) throws Exception {
        Map<String, Object> map = inputObject.getParams();
        RepositoryService repositoryService = processEngine.getRepositoryService();
        // 初始化一个空模型
        Model model = repositoryService.newModel();
        // 设置一些默认信息
        String name = "new-process";
        String description = "";
        int revision = 1;
        String key = "process";
        ObjectNode modelNode = objectMapper.createObjectNode();
        modelNode.put(ModelDataJsonConstants.MODEL_NAME, name);
        modelNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
        modelNode.put(ModelDataJsonConstants.MODEL_REVISION, revision);
        model.setName(name);
        model.setKey(key);
        model.setMetaInfo(modelNode.toString());
        repositoryService.saveModel(model);
        String id = model.getId();
        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);
        repositoryService.addModelEditorSource(id, editorNode.toString().getBytes("utf-8"));
        map.put("id", model.getId());
        outputObject.setBean(map);
    }

    /**
     * @replacedle: queryActivitiModelList
     * @Description: 获取所有模型
     * @param @param inputObject
     * @param @param outputObject
     * @param @throws Exception    参数
     * @return void    返回类型
     * @throws
     */
    @Override
    public void queryActivitiModelList(InputObject inputObject, OutputObject outputObject) throws Exception {
        Map<String, Object> map = inputObject.getParams();
        RepositoryService repositoryService = processEngine.getRepositoryService();
        List<Model> beans = repositoryService.createModelQuery().listPage(Integer.parseInt(map.get("limit").toString()) * (Integer.parseInt(map.get("page").toString()) - 1), Integer.parseInt(map.get("limit").toString()));
        long count = repositoryService.createModelQuery().count() - repositoryService.createDeploymentQuery().count();
        List<Map<String, Object>> rows = new ArrayList<>();
        for (Model model : beans) {
            if (ToolUtil.isBlank(model.getDeploymentId())) {
                rows.add(ToolUtil.javaBean2Map(model));
            }
        }
        outputObject.setBeans(rows);
        outputObject.settotal(count);
    }

    /**
     * @replacedle: editActivitiModelToDeploy
     * @Description: 发布模型为流程定义
     * @param @param inputObject
     * @param @param outputObject
     * @param @throws Exception    参数
     * @return void    返回类型
     * @throws
     */
    @Override
    public void editActivitiModelToDeploy(InputObject inputObject, OutputObject outputObject) throws Exception {
        Map<String, Object> map = inputObject.getParams();
        String modelId = map.get("modelId").toString();
        // 获取模型
        RepositoryService repositoryService = processEngine.getRepositoryService();
        Model modelData = repositoryService.getModel(modelId);
        byte[] bytes = repositoryService.getModelEditorSource(modelData.getId());
        if (bytes == null) {
            outputObject.setreturnMessage("模型数据为空,请先设计流程并成功保存,再进行发布。");
        } else {
            JsonNode modelNode = new ObjectMapper().readTree(bytes);
            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            if (model.getProcesses().size() == 0) {
                outputObject.setreturnMessage("数据模型不符要求,请至少设计一条主线流程。");
            } else {
                byte[] bpmnBytes = new BpmnXMLConverter().convertToXML(model);
                // 发布流程
                String processName = modelData.getName() + ".bpmn20.xml";
                Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes, "UTF-8")).deploy();
                modelData.setDeploymentId(deployment.getId());
                repositoryService.saveModel(modelData);
            }
        }
    }

    /**
     * @replacedle: editActivitiModelToStartProcess
     * @Description: 启动流程
     * @param @param inputObject
     * @param @param outputObject
     * @param @throws Exception    参数
     * @return void    返回类型
     * @throws
     */
    @Override
    public void editActivitiModelToStartProcess(InputObject inputObject, OutputObject outputObject) throws Exception {
        Map<String, Object> map = inputObject.getParams();
        String keyName = map.get("keyName").toString();
        ProcessInstance process = processEngine.getRuntimeService().startProcessInstanceByKey(keyName);
        map.clear();
        map.put("id", process.getId());
        map.put("processDefinitionId", process.getProcessDefinitionId());
        outputObject.setBean(map);
    }

    /**
     * @replacedle: editActivitiModelToRun
     * @Description: 提交任务
     * @param @param inputObject
     * @param @param outputObject
     * @param @throws Exception    参数
     * @return void    返回类型
     * @throws
     */
    @Override
    public void editActivitiModelToRun(InputObject inputObject, OutputObject outputObject) throws Exception {
        Map<String, Object> map = inputObject.getParams();
        String processInstanceId = map.get("processInstanceId").toString();
        Task task = processEngine.getTaskService().createTaskQuery().processInstanceId(processInstanceId).singleResult();
        processEngine.getTaskService().complete(task.getId());
    }

    /**
     * @replacedle: deleteActivitiModelById
     * @Description: 删除模型
     * @param @param inputObject
     * @param @param outputObject
     * @param @throws Exception    参数
     * @return void    返回类型
     * @throws
     */
    @Override
    public void deleteActivitiModelById(InputObject inputObject, OutputObject outputObject) throws Exception {
        Map<String, Object> map = inputObject.getParams();
        String id = map.get("id").toString();
        repositoryService.deleteModel(id);
    }

    /**
     * @replacedle: queryReleasedActivitiModelList
     * @Description: 获取已经发布的模型
     * @param @param inputObject
     * @param @param outputObject
     * @param @throws Exception    参数
     * @return void    返回类型
     * @throws
     */
    @Override
    public void queryReleasedActivitiModelList(InputObject inputObject, OutputObject outputObject) throws Exception {
        Map<String, Object> map = inputObject.getParams();
        List<Deployment> deployments = repositoryService.createDeploymentQuery().listPage(Integer.parseInt(map.get("limit").toString()) * (Integer.parseInt(map.get("page").toString()) - 1), Integer.parseInt(map.get("limit").toString()));
        long count = repositoryService.createDeploymentQuery().count();
        List<DeploymentResponse> list = new ArrayList<>();
        for (Deployment deployment : deployments) {
            list.add(new DeploymentResponse(deployment));
        }
        List<Map<String, Object>> rows = new ArrayList<>();
        for (DeploymentResponse deploymentResponse : list) {
            rows.add(ToolUtil.javaBean2Map(deploymentResponse));
        }
        outputObject.setBeans(rows);
        outputObject.settotal(count);
    }

    /**
     * @replacedle: deleteReleasedActivitiModelById
     * @Description: 取消发布
     * @param @param inputObject
     * @param @param outputObject
     * @param @throws Exception    参数
     * @return void    返回类型
     * @throws
     */
    @Override
    public void deleteReleasedActivitiModelById(InputObject inputObject, OutputObject outputObject) throws Exception {
        Map<String, Object> map = inputObject.getParams();
        String deploymentId = map.get("deploymentId").toString();
        repositoryService.deleteDeployment(deploymentId);
    }
}

15 Source : ActivitiModelServiceImpl.java
with Apache License 2.0
from weizhiqiang1995

/**
 * @replacedle: insertNewActivitiModel
 * @Description: 新建一个空模型
 * @param @param inputObject
 * @param @param outputObject
 * @param @throws Exception    参数
 * @return void    返回类型
 * @throws
 */
@SuppressWarnings("deprecation")
@Override
public void insertNewActivitiModel(InputObject inputObject, OutputObject outputObject) throws Exception {
    Map<String, Object> map = inputObject.getParams();
    RepositoryService repositoryService = processEngine.getRepositoryService();
    // 初始化一个空模型
    Model model = repositoryService.newModel();
    // 设置一些默认信息
    String name = "new-process";
    String description = "";
    int revision = 1;
    String key = "process";
    ObjectNode modelNode = objectMapper.createObjectNode();
    modelNode.put(ModelDataJsonConstants.MODEL_NAME, name);
    modelNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
    modelNode.put(ModelDataJsonConstants.MODEL_REVISION, revision);
    model.setName(name);
    model.setKey(key);
    model.setMetaInfo(modelNode.toString());
    repositoryService.saveModel(model);
    String id = model.getId();
    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);
    repositoryService.addModelEditorSource(id, editorNode.toString().getBytes("utf-8"));
    map.put("id", model.getId());
    outputObject.setBean(map);
}

See More Examples