### Query Process Instance Example Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/QueryService.md Demonstrates retrieving a process instance and accessing its properties. ```java FlwInstance instance = queryService.getInstance(instanceId); if (instance != null) { System.out.println("实例状态: " + instance.getInstanceState()); System.out.println("当前节点: " + instance.getCurrentNodeName()); System.out.println("发起人: " + instance.getCreateBy()); } ``` -------------------------------- ### Query Task Example Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/QueryService.md Demonstrates retrieving a task and accessing its details. ```java FlwTask task = queryService.getTask(taskId); if (task != null) { System.out.println("任务名称: " + task.getTaskName()); System.out.println("任务状态: " + task.getTaskState()); System.out.println("期望完成时间: " + task.getExpireTime()); } ``` -------------------------------- ### Get Start Task Definition Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/QueryService.md Method signature for retrieving the initial task of a process instance. ```java FlwHisTask getStartTaskByInstanceId(Long instanceId) ``` -------------------------------- ### Query Instances by Business Key Example Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/QueryService.md Demonstrates retrieving multiple process instances using a business key. ```java // 根据申请单号查询所有关联的流程实例 Optional> instances = queryService.getInstancesByBusinessKey("APP20240101001"); instances.ifPresent(list -> { System.out.println("找到 " + list.size() + " 个流程实例"); list.forEach(inst -> System.out.println("实例 ID: " + inst.getId())); }); ``` -------------------------------- ### getStartTaskByInstanceId(Long instanceId) Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/QueryService.md Retrieves the starting task (initiator task) for a given process instance. ```APIDOC ## Method: getStartTaskByInstanceId(Long instanceId) ### Description Retrieves the starting task (initiator task) associated with the provided process instance ID. ### Parameters - **instanceId** (Long) - Required - The ID of the process instance. ### Returns - **FlwHisTask** - The starting task object. ``` -------------------------------- ### Execute a complete workflow lifecycle in Java Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/FlowLongEngine.md Demonstrates the end-to-end process of starting a workflow instance, retrieving tasks, performing an approval action, and verifying the updated process state. ```java // 1. 启动流程 FlowCreator creator = new FlowCreator("emp001", "员工张三"); Map args = new HashMap<>(); args.put("days", 3); args.put("reason", "家有急事"); Optional instanceOpt = engine.startInstanceByProcessKey( "leave", creator, args ); if (!instanceOpt.isPresent()) { System.out.println("流程启动失败"); return; } FlwInstance instance = instanceOpt.get(); System.out.println("流程已启动: " + instance.getId()); // 2. 查询当前任务 List tasks = engine.queryService().getTasksByInstanceId(instance.getId()); if (tasks.isEmpty()) { System.out.println("没有待办任务"); return; } FlwTask task = tasks.get(0); // 3. 执行任务(直属主管审批) FlowCreator manager = new FlowCreator("mgr001", "直属主管"); Map approveArgs = new HashMap<>(); approveArgs.put("opinion", "同意"); approveArgs.put("approveTime", new Date()); boolean approved = engine.executeTask(task.getId(), manager, approveArgs); System.out.println("审批结果: " + (approved ? "成功" : "失败")); // 4. 查询流程状态 FlwInstance updated = engine.queryService().getInstance(instance.getId()); System.out.println("流程当前节点: " + updated.getCurrentNodeName()); System.out.println("流程状态: " + updated.getInstanceState()); ``` -------------------------------- ### Get Instances by Business Key Definition Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/QueryService.md Method signature for retrieving a list of process instances associated with a specific business key. ```java Optional> getInstancesByBusinessKey(String businessKey) ``` -------------------------------- ### Get Historical Instances by Business Key Definition Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/QueryService.md Method signature for retrieving historical process instances by business key. ```java Optional> getHisInstancesByBusinessKey(String businessKey) ``` -------------------------------- ### Handle Process Execution Errors in Java Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/errors.md Demonstrates a comprehensive try-catch block for starting a process and completing a task, specifically catching FlowLongException. ```java public void executeProcessFlow(Long processId, FlowCreator creator) { try { // 1. 启动流程 Optional instanceOpt = engine.startInstanceById( processId, creator, null ); if (!instanceOpt.isPresent()) { System.out.println("流程启动失败:流程不存在或已禁用"); return; } FlwInstance instance = instanceOpt.get(); System.out.println("流程已启动,实例ID: " + instance.getId()); // 2. 执行任务 List tasks = queryService.getTasksByInstanceId(instance.getId()); if (tasks.isEmpty()) { System.out.println("没有待办任务"); return; } FlwTask task = tasks.get(0); // 3. 检查权限 FlwTaskActor allowedActor = taskService.isAllowed(task, creator.getCreateId()); if (allowedActor == null) { System.out.println("您无权处理该任务"); return; } // 4. 执行任务 Map args = new HashMap<>(); args.put("approved", true); FlwTask result = taskService.complete(task.getId(), creator, args); System.out.println("任务已完成"); } catch (FlowLongException e) { System.err.println("工作流异常:" + e.getMessage()); e.printStackTrace(); } catch (Exception e) { System.err.println("系统异常:" + e.getMessage()); e.printStackTrace(); } } ``` -------------------------------- ### Get Process Instance Definition Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/QueryService.md Method signature for retrieving an active process instance by its ID. ```java FlwInstance getInstance(Long instanceId) ``` -------------------------------- ### Process Deployment and Lifecycle Management in Java Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/ProcessService.md Demonstrates the full lifecycle of a process including deployment, retrieval, instance initiation, and uninstallation. ```java // 1. 部署流程定义 String processJson = "{\"key\":\"leave\",\"name\":\"请假流程\",...}"; Long processId = processService.deploy( null, processJson, new FlowCreator("admin", "管理员"), false, process -> { System.out.println("流程已部署 - ID: " + process.getId()); System.out.println("流程名称: " + process.getProcessName()); System.out.println("流程版本: " + process.getProcessVersion()); } ); // 2. 查询流程定义 FlwProcess process = processService.getProcessById(processId); System.out.println("流程状态: " + process.getProcessState()); // 3. 启动流程实例 FlowLongEngine engine = getFlowLongEngine(); Optional instanceOpt = engine.startInstanceById( processId, new FlowCreator("user123", "张三"), null ); instanceOpt.ifPresent(instance -> { System.out.println("流程实例已创建: " + instance.getId()); }); // 4. 卸载旧版本流程 processService.undeploy(oldProcessId); System.out.println("旧版本流程已卸载"); ``` -------------------------------- ### Get Task Definition Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/QueryService.md Method signature for retrieving an active task by ID. ```java FlwTask getTask(Long taskId) ``` -------------------------------- ### Process Instance Initialization Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/INDEX.md Methods used to initiate a new process instance. ```text startInstanceById() startInstanceByProcessKey() ``` -------------------------------- ### Get Historical Task Definition Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/QueryService.md Method signature for retrieving a historical task by ID. ```java FlwHisTask getHistTask(Long taskId) ``` -------------------------------- ### Querying Process Instances and Tasks in Java Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/QueryService.md Demonstrates common retrieval patterns for process instances, active tasks, task actors, and historical records using the QueryService. ```java // 1. 查询流程实例 FlwInstance instance = queryService.getInstance(instanceId); System.out.println("实例状态: " + instance.getInstanceState()); // 2. 查询当前待办任务 List activeTasks = queryService.getTasksByInstanceId(instanceId); System.out.println("待办任务数: " + activeTasks.size()); // 3. 查询特定节点的任务 List managerTasks = queryService.getTasksByInstanceIdAndTaskName( instanceId, "经理审批" ); // 4. 查询任务的参与者 if (!activeTasks.isEmpty()) { List actors = queryService.getTaskActorsByTaskId(activeTasks.get(0).getId()); System.out.println("任务参与者数: " + actors.size()); } // 5. 查询历史任务记录 Optional> historyOpt = queryService.getHisTasksByInstanceId(instanceId); historyOpt.ifPresent(history -> { System.out.println("历史任务数: " + history.size()); history.forEach(task -> { System.out.println(task.getTaskName() + " -> " + task.getCreateBy()); }); }); // 6. 查询子流程 Optional> subProcesses = queryService.getSubProcessByInstanceId(instanceId); subProcesses.ifPresent(list -> System.out.println("子流程数: " + list.size())); // 7. 查询业务关联的所有流程实例 Optional> businessInstances = queryService.getInstancesByBusinessKey("APP001"); businessInstances.ifPresent(list -> { System.out.println("关联实例: " + list.size()); }); ``` -------------------------------- ### Revoke process instance Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/RuntimeService.md Used by the process initiator to cancel an incorrectly started process. ```java boolean revoke(Long instanceId, FlwTask currentFlwTask, FlowCreator flowCreator) ``` ```java // 流程发起人撤销流程 boolean success = runtimeService.revoke( instanceId, null, initiator // 必须是流程发起人 ); ``` -------------------------------- ### startInstanceByProcessKey(String processKey, Integer version, FlowCreator flowCreator, ...) Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/FlowLongEngine.md Initiates a new workflow instance using the process definition key and optional version. ```APIDOC ## startInstanceByProcessKey(String processKey, Integer version, FlowCreator flowCreator, ...) ### Description Starts a workflow instance based on the process key. If version is null, the latest version is used. ### Parameters - **processKey** (String) - Required - The process definition key. - **version** (Integer) - Optional - The version number. - **flowCreator** (FlowCreator) - Required - The user initiating the process. - **args** (Map) - Optional - Process parameters. - **saveAsDraft** (boolean) - Optional - Whether to save as a draft. ### Returns - **Optional** - The created workflow instance. ``` -------------------------------- ### Get Extended Process Instance Definition Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/QueryService.md Method signature for retrieving an extended process instance object. ```java FlwExtInstance getExtInstance(Long instanceId) ``` -------------------------------- ### Get Historical Process Instance Definition Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/QueryService.md Method signature for retrieving a historical process instance by ID. ```java FlwHisInstance getHistInstance(Long instanceId) ``` -------------------------------- ### Manage Full Process Lifecycle Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/RuntimeService.md Demonstrates the complete workflow of creating, saving, modifying variables, suspending, activating, and ending a process instance. ```java // 1. 创建流程实例 FlwProcess process = processService.getProcessById(processId); FlowCreator creator = new FlowCreator("emp001", "员工"); Map args = new HashMap<>(); args.put("reason", "年假"); args.put("days", 5); FlwInstance instance = runtimeService.createInstance( process, creator, args, null, false, null ); // 2. 保存实例 runtimeService.saveInstance(instance, process, false, creator); System.out.println("实例已创建: " + instance.getId()); // 3. 添加流程变量 Map vars = new HashMap<>(); vars.put("budget", 10000); runtimeService.addVariable(instance.getId(), vars); // 4. 暂停实例 runtimeService.suspendInstanceById(instance.getId(), FlowCreator.ADMIN); System.out.println("实例已暂停"); // 5. 激活实例 runtimeService.activeInstanceById(instance.getId(), FlowCreator.ADMIN); System.out.println("实例已激活"); // 6. 结束实例 Execution execution = new Execution(); runtimeService.endInstance(execution, instance.getId(), null, InstanceState.complete); System.out.println("实例已完成"); ``` -------------------------------- ### Deploy Process from Resource Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/ProcessService.md Deploys a process definition from a classpath resource file. The repeat parameter controls whether to create a new version if the process already exists. ```java // 从 classpath 部署流程定义 Long processId = processService.deployByResource( "flows/leave_request.json", new FlowCreator("admin", "管理员"), false, // 不重复部署 process -> { System.out.println("流程已部署: " + process.getProcessName()); System.out.println("流程版本: " + process.getProcessVersion()); } ); ``` -------------------------------- ### deployByResource(String resourceName, FlowCreator flowCreator, boolean repeat, Consumer processSave) Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/ProcessService.md Deploys a process definition from a classpath resource file. ```APIDOC ## deployByResource(String resourceName, FlowCreator flowCreator, boolean repeat, Consumer processSave) ### Description Deploys a process definition from a classpath resource file. ### Parameters - **resourceName** (String) - Required - The classpath path to the resource file. - **flowCreator** (FlowCreator) - Required - The deployment creator information. - **repeat** (boolean) - Required - Whether to allow duplicate deployment (true: create new version, false: skip if exists). - **processSave** (Consumer) - Optional - Callback for the deployed process. ### Returns - **Long** - The process definition ID. ``` -------------------------------- ### deploy(InputStream input, FlowCreator flowCreator, boolean repeat, Consumer processSave) Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/ProcessService.md Deploys a process definition from an input stream. ```APIDOC ## deploy(InputStream input, FlowCreator flowCreator, boolean repeat, Consumer processSave) ### Description Deploys a process definition from an input stream containing JSON data. ### Parameters - **input** (InputStream) - Required - The input stream of the process definition JSON. - **flowCreator** (FlowCreator) - Required - The deployment creator information. - **repeat** (boolean) - Required - Whether to allow duplicate deployment. - **processSave** (Consumer) - Optional - Callback for the deployed process. ### Returns - **Long** - The process definition ID. ``` -------------------------------- ### revoke(Long instanceId, FlwTask currentFlwTask, FlowCreator flowCreator) Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/RuntimeService.md Revokes a process instance, intended for use by the process initiator to cancel incorrectly started processes. ```APIDOC ## revoke(Long instanceId, FlwTask currentFlwTask, FlowCreator flowCreator) ### Description Revokes a process instance. ### Parameters - **instanceId** (Long) - Required - 流程实例 ID - **currentFlwTask** (FlwTask) - Optional - 当前任务 - **flowCreator** (FlowCreator) - Required - 操作人 ### Returns - **boolean** - 成功返回 true ``` -------------------------------- ### deploy Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/ProcessService.md Deploys a new process definition into the engine. ```APIDOC ## deploy ### Description Deploys a process definition from a JSON string. ### Method Java Method ### Signature Long deploy(Long id, String processJson, FlowCreator creator, boolean isUpdate, Consumer callback) ### Parameters - **id** (Long) - Optional - The ID of the process to update. - **processJson** (String) - Required - The JSON representation of the process definition. - **creator** (FlowCreator) - Required - The user creating the process. - **isUpdate** (boolean) - Required - Flag indicating if this is an update to an existing process. - **callback** (Consumer) - Optional - Callback function executed after successful deployment. ``` -------------------------------- ### Execute Workflow Task in Java Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/TaskService.md Demonstrates the complete lifecycle of querying a task, marking it as viewed, and executing an approval action. ```java // 1. 查询待办任务 List tasks = queryService.getTasksByInstanceId(instanceId); if (tasks.isEmpty()) { System.out.println("没有待办任务"); return; } FlwTask task = tasks.get(0); FlowCreator operator = new FlowCreator("user456", "李四"); // 2. 标记任务为已阅 taskService.viewTask(task.getId(), operator); // 3. 执行审批 Map approveArgs = new HashMap<>(); approveArgs.put("opinion", "同意"); approveArgs.put("comment", "审批意见"); boolean executeSuccess = taskService.executeTask( task.getId(), operator, approveArgs, TaskState.complete, TaskEventType.complete ); if (executeSuccess) { System.out.println("任务执行成功"); } else { System.out.println("任务执行失败"); } ``` -------------------------------- ### Deploy Process from InputStream Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/ProcessService.md Deploys a process definition using an InputStream containing the JSON definition. Useful for dynamic deployment from byte streams. ```java // 从字节流部署流程 ByteArrayInputStream input = new ByteArrayInputStream(jsonBytes); Long processId = processService.deploy( input, new FlowCreator("admin", "管理员"), true, // 允许重复部署,创建新版本 null ); ``` -------------------------------- ### 启动流程实例 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/README.md 使用 FlowCreator 初始化发起人并调用 engine.startInstanceById 启动流程。 ```java // 创建流程发起人 FlowCreator creator = new FlowCreator("user123", "张三"); // 启动流程 Optional instanceOpt = engine.startInstanceById( processId, creator, null // 流程参数 ); instanceOpt.ifPresent(instance -> { System.out.println("流程已启动: " + instance.getId()); }); ``` -------------------------------- ### Recommended Logging Levels in Java Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/errors.md Standardized logging practices for different severity levels during process execution. ```java // DEBUG:详细的流程执行步骤 logger.debug("开始执行任务 taskId=" + taskId); // INFO:业务关键操作 logger.info("流程实例已启动 instanceId=" + instanceId); // WARN:可恢复的异常 logger.warn("任务处理失败,准备重试 taskId=" + taskId); // ERROR:不可恢复的异常 logger.error("流程执行失败,无法恢复", exception); ``` -------------------------------- ### Process Query Methods Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/INDEX.md Methods for retrieving process instances, active tasks, and historical task data. ```text getInstance() // 获取实例 getTask() // 获取任务 getHisTasksByInstanceId() // 获取历史 ``` -------------------------------- ### getInstancesByBusinessKey(String businessKey) Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/QueryService.md Retrieves a list of process instances associated with a specific business key. ```APIDOC ## Method: getInstancesByBusinessKey(String businessKey) ### Description Retrieves a list of active process instances associated with the provided business key. ### Parameters - **businessKey** (String) - Required - The business key associated with the processes. ### Returns - **Optional>** - A list of process instances. ``` -------------------------------- ### Deploy Process from JSON String Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/ProcessService.md Deploys or updates a process definition using a JSON string. If processId is null, a new process is created. ```java // 从设计器导出的 JSON 部署流程 String processJson = "{" + "\"key\": \"expense_approval\"," + "\"name\": \"费用报销审批\"," + "\"nodeConfig\": {...}" + "}"; Long processId = processService.deploy( null, processJson, new FlowCreator("admin", "管理员"), false, process -> System.out.println("流程已创建: " + process.getId()) ); ``` -------------------------------- ### InstanceState - 流程实例状态 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/types.md 定义整个流程实例的运行状态,如处理中、已完成或 AI 处理状态。 ```java public enum InstanceState { destroy(-3), // 作废 suspend(-2), // 暂停 saveAsDraft(-1), // 暂存草稿 active(0), // 处理中 complete(1), // 已完成 reject(2), // 已驳回 revoke(3), // 已撤销 timeout(4), // 已超时 terminate(5), // 已终止 autoPass(6), // 自动通过 autoReject(7), // 自动拒绝 aiProcessing(8), // AI处理中 aiManualReview(9) // AI人工复核 } ``` -------------------------------- ### deploy(Long processId, String jsonString, FlowCreator flowCreator, boolean repeat, Consumer processSave) Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/ProcessService.md Deploys a process definition from a JSON string. ```APIDOC ## deploy(Long processId, String jsonString, FlowCreator flowCreator, boolean repeat, Consumer processSave) ### Description Deploys a process definition from a JSON string. ### Parameters - **processId** (Long) - Optional - The process definition ID (null for new, existing ID for update). - **jsonString** (String) - Required - The process definition JSON string. - **flowCreator** (FlowCreator) - Required - The deployment creator information. - **repeat** (boolean) - Required - Whether to allow duplicate deployment. - **processSave** (Consumer) - Optional - Callback for the deployed process. ### Returns - **Long** - The process definition ID. ``` -------------------------------- ### Query Process Definition by Version Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/ProcessService.md Retrieves a process definition based on the process key and version. Passing null for the version retrieves the latest version. ```java // 获取最新版本的流程 FlwProcess latestProcess = processService.getProcessByVersion( null, "leave_request", null ); // 获取指定版本的流程 FlwProcess v2Process = processService.getProcessByVersion( "tenant1", "leave_request", 2 ); ``` -------------------------------- ### 执行节点跳转任务方法定义 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/TaskService.md 执行节点跳转任务,支持普通跳转、驳回跳转和路由跳转。 ```java Optional> executeJumpTask(Long taskId, String nodeKey, FlowCreator flowCreator, Map args, Function executionFunction, TaskType taskType) ``` -------------------------------- ### 校验任务处理权限 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/errors.md 在执行任务前检查当前用户是否为任务参与者。 ```java // 检查用户是否为任务参与者 FlwTask task = queryService.getTask(taskId); FlwTaskActor allowedActor = taskService.isAllowed(task, userId); if (allowedActor == null) { System.out.println("您无权处理该任务"); return; } // 执行任务 taskService.executeTask(taskId, new FlowCreator(userId, userName), args); ``` -------------------------------- ### FlwInstance 常用方法 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/types.md 用于创建流程实例及管理流程变量的辅助方法。 ```java FlwInstance.of(String businessKey) // 创建实例 variableToMap() // 将变量转为Map putAllVariable(Map args) // 添加变量 clone() // 克隆实例 ``` -------------------------------- ### Task Execution Methods Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/INDEX.md Core methods for completing, rejecting, or jumping between tasks. ```text complete() / executeTask() executeRejectTask() executeJumpTask() ``` -------------------------------- ### startInstanceById(Long id, FlowCreator flowCreator, ...) Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/FlowLongEngine.md Initiates a new workflow instance based on the specified process definition ID. ```APIDOC ## startInstanceById(Long id, FlowCreator flowCreator, ...) ### Description Starts a workflow instance using the process definition ID and the specified creator information. ### Parameters - **id** (Long) - Required - Process definition ID. - **flowCreator** (FlowCreator) - Required - The user initiating the process. - **args** (Map) - Optional - Process parameters. - **saveAsDraft** (boolean) - Optional - Whether to save as a draft. - **checkNodeModel** (Consumer) - Optional - Node validation logic. - **supplier** (Supplier) - Optional - Instance initialization provider. ### Returns - **Optional** - The created workflow instance, or empty if creation fails. ``` -------------------------------- ### Manage FlowCreator Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/types.md Handles process creation metadata including tenant and user information. ```java public class FlowCreator implements Serializable { private String tenantId; // 租户ID private String createId; // 创建人ID private String createBy; // 创建人名称 public static final FlowCreator ADMIN; // 管理员常量 public static FlowCreator of(String createId, String createBy) public static FlowCreator of(String tenantId, String createId, String createBy) public static FlowCreator of(FlwTaskActor fta) } ``` ```java // 创建流程创建者 FlowCreator creator = new FlowCreator("user123", "张三"); creator.tenantId("tenant1"); // 或使用工厂方法 FlowCreator creator = FlowCreator.of("user123", "张三"); // 从任务参与者创建 FlowCreator creator = FlowCreator.of(taskActor); // 使用管理员 FlowCreator admin = FlowCreator.ADMIN; ``` -------------------------------- ### Resume Workflow Instance Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/TaskService.md Allows the original initiator to wake up a withdrawn or rejected historical task instance. ```java boolean resume(Long instanceId, FlowCreator flowCreator, BiFunction execFunc) ``` -------------------------------- ### resume(Long instanceId, FlowCreator flowCreator, BiFunction execFunc) Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/TaskService.md Resumes a withdrawn or rejected historical task instance. ```APIDOC ## resume(Long instanceId, FlowCreator flowCreator, BiFunction execFunc) ### Description Resumes a withdrawn or rejected historical task instance. Must be called by the instance initiator. ### Parameters - **instanceId** (Long) - Required - Historical instance ID - **flowCreator** (FlowCreator) - Required - The initiator - **execFunc** (BiFunction) - Required - Execution function ### Returns - **boolean** - Returns true if successful ``` -------------------------------- ### Update Model and Instance Schema Changes Source: https://github.com/aizuda/flowlong/blob/main/changelog.md Describes the transition from nodeName to nodeKey for unique identification and the corresponding updates to task and instance fields. ```text 1,模型新增 nodeKey 替代 nodeName 唯一条件,任务 displayName 修改为 taskKey 2,流程实例 currentNode 分为 currentNodeName currentNodeKey ``` -------------------------------- ### 执行触发器任务方法定义 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/TaskService.md 执行触发器任务。 ```java boolean executeTaskTrigger(Execution execution, FlwTask flwTask) ``` -------------------------------- ### 处理任务重复执行错误 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/errors.md 捕获因任务已被他人处理而导致的异常。 ```java // 错误:任务已完成 try { taskService.executeTask(taskId, creator, args); taskService.executeTask(taskId, otherCreator, args); // 错误!任务已完成 } catch (FlowLongException e) { System.err.println("任务已处理: " + e.getMessage()); } ``` -------------------------------- ### 校验任务是否存在 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/errors.md 在执行任务操作前确认任务是否有效。 ```java FlwTask task = queryService.getTask(taskId); if (task == null) { System.out.println("任务不存在或已完成"); return; } ``` -------------------------------- ### 启动流程实例(按 ProcessKey) Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/FlowLongEngine.md 根据流程定义 KEY 和版本号启动流程实例,传入 null 版本号将自动使用最新版本。 ```java // 启动最新版本的流程 Optional instance = engine.startInstanceByProcessKey( "leave", // 流程 KEY null, // 使用最新版本 new FlowCreator("user123", "李四"), null ); ``` -------------------------------- ### createInstance Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/RuntimeService.md Creates a new workflow instance based on the provided process definition and creator. ```APIDOC ## createInstance(FlwProcess flwProcess, FlowCreator flowCreator, Map args, NodeModel nodeModel, boolean saveAsDraft, Supplier supplier) ### Description Creates a new workflow instance based on the provided process definition and creator. ### Parameters - **flwProcess** (FlwProcess) - Required - The process definition object. - **flowCreator** (FlowCreator) - Required - The creator of the flow. - **args** (Map) - Optional - Process parameters. - **nodeModel** (NodeModel) - Optional - The current node model. - **saveAsDraft** (boolean) - Required - Whether to save as a draft. - **supplier** (Supplier) - Optional - Provider for instance initialization. ### Returns - **FlwInstance** - The created workflow instance object. ``` -------------------------------- ### Reject process instance Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/RuntimeService.md Defines the signature for forcing a process instance rejection. ```java boolean reject(Long instanceId, FlwTask currentFlwTask, FlowCreator flowCreator) ``` -------------------------------- ### 执行任务 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/README.md 使用 engine.executeTask 提交任务执行结果,支持传入自定义参数。 ```java // 执行任务,驱动流程继续 FlowCreator executor = new FlowCreator("user456", "李四"); Map args = new HashMap<>(); args.put("opinion", "同意"); boolean success = engine.executeTask(taskId, executor, args); System.out.println("任务执行: " + (success ? "成功" : "失败")); ``` -------------------------------- ### 检查流程实例是否存在 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/errors.md 在操作前校验流程实例是否有效。 ```java FlwInstance instance = queryService.getInstance(invalidInstanceId); if (instance == null) { System.out.println("流程实例不存在"); } ``` -------------------------------- ### 结束流程实例 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/RuntimeService.md 结束流程实例,用于审批通过、驳回、终止或超时处理。 ```java boolean endInstance(Execution execution, Long instanceId, NodeModel endNode, InstanceState instanceState) ``` -------------------------------- ### FlwInstance 实体类定义 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/types.md 定义流程实例的核心属性,用于跟踪流程执行状态和业务关联。 ```java public class FlwInstance extends FlowEntity { protected Long processId; // 流程定义ID protected Long parentInstanceId; // 父流程实例ID protected Integer priority; // 优先级(0:同步 1:异步) protected String instanceNo; // 流程实例编号 protected String businessKey; // 业务KEY(关联业务实现) protected String variable; // 变量JSON protected String currentNodeName; // 当前节点名称 protected String currentNodeKey; // 当前节点KEY protected Date expireTime; // 期望完成时间 protected String lastUpdateBy; // 上次更新人 protected Date lastUpdateTime; // 上次更新时间 } ``` -------------------------------- ### Configure MyBatis Plus and HikariCP Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/configuration.md Set up MyBatis Plus enum handlers and tune HikariCP connection pool parameters for database performance. ```properties # MyBatis Plus 分页配置 mybatis-plus.configuration.default-enum-type-handler=com.baomidou.mybatisplus.core.handlers.MybatisEnumTypeHandler # 连接池配置 spring.datasource.hikari.maximum-pool-size=20 spring.datasource.hikari.minimum-idle=5 spring.datasource.hikari.connection-timeout=30000 ``` -------------------------------- ### 激活流程实例 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/RuntimeService.md 激活处于暂停状态的流程实例。 ```java boolean activeInstanceById(Long instanceId, FlowCreator flowCreator) ``` -------------------------------- ### 更新流程实例 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/RuntimeService.md 更新流程实例,要求实例 ID 不能为空。 ```java void updateInstance(FlwInstance flwInstance) ``` -------------------------------- ### Implement InstanceListener interface Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/configuration.md Handle lifecycle events for workflow instances. ```java public interface InstanceListener ``` ```java public class CustomInstanceListener implements InstanceListener { @Override public void instanceEvent(InstanceEventType eventType, FlwInstance instance) { // 处理实例事件 switch(eventType) { case start: System.out.println("实例已启动: " + instance.getId()); break; case complete: System.out.println("实例已完成: " + instance.getId()); break; } } } ``` -------------------------------- ### 校验流程实例状态 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/errors.md 确保实例处于活跃状态后再执行操作,防止对已完成或终止的实例进行操作。 ```java // 检查实例状态 FlwInstance instance = queryService.getInstance(instanceId); if (instance.getInstanceState() != InstanceState.active.getValue()) { System.out.println("实例不在处理中,无法执行操作"); return; } ``` -------------------------------- ### 处理流程未找到错误 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/errors.md 在启动流程前校验流程是否存在及状态,避免因流程不存在或禁用导致的错误。 ```java // 错误:流程不存在 Optional instance = engine.startInstanceById(999999L, creator); if (!instance.isPresent()) { System.out.println("流程定义不存在"); } ``` ```java // 先查询流程是否存在 FlwProcess process = processService.getProcessById(processId); if (process == null || process.getProcessState() != 1) { System.out.println("流程不存在或已禁用"); return; } // 再启动流程 Optional instance = engine.startInstanceById(processId, creator); ``` -------------------------------- ### getProcessByVersion(String tenantId, String processKey, Integer version) Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/ProcessService.md Retrieves a process definition based on the process key and version number. ```APIDOC ## getProcessByVersion(String tenantId, String processKey, Integer version) ### Description Retrieves a process definition based on the process key and version number. ### Parameters - **tenantId** (String) - Optional - The tenant ID. - **processKey** (String) - Required - The process definition key. - **version** (Integer) - Optional - The version number; null retrieves the latest version. ### Returns - **FlwProcess** - The process definition object. ``` -------------------------------- ### configure(FlowLongContext config) Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/FlowLongEngine.md Configures the FlowLong engine with a global context object, returning the engine instance for method chaining. ```APIDOC ## configure(FlowLongContext config) ### Description Configures the engine instance using the provided global configuration object. ### Parameters - **config** (FlowLongContext) - Required - Global configuration object. ### Returns - **FlowLongEngine** - The configured engine instance. ``` -------------------------------- ### 处理事务执行异常 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/errors.md 在事务中执行流程操作,并在失败时进行回滚处理。 ```java try { // 在事务中执行流程操作 taskService.executeTask(taskId, creator, args); } catch (Exception e) { // 回滚操作 System.err.println("任务执行失败,请重试: " + e.getMessage()); } ``` -------------------------------- ### 暂停流程实例 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/RuntimeService.md 暂停指定的流程实例。 ```java boolean suspendInstanceById(Long instanceId, FlowCreator flowCreator) ``` ```java // 暂停流程实例 boolean success = runtimeService.suspendInstanceById( instanceId, new FlowCreator("manager", "经理") ); System.out.println("暂停结果: " + (success ? "成功" : "失败")); ``` -------------------------------- ### 获取节点模型 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/RuntimeService.md 通过实例 ID 和节点 KEY 获取节点模型。 ```java default NodeModel getNodeModel(Long instanceId, String nodeKey) ``` -------------------------------- ### Create a CC task Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/FlowLongEngine.md Creates a copy of a task for notification purposes. Requires the current task and a list of CC actors. ```java // 创建抄送任务(不校验重复) List ccActors = new ArrayList<>(); FlwTaskActor ccActor = new FlwTaskActor(); ccActor.setActorId("supervisor"); ccActor.setActorName("主管"); ccActors.add(ccActor); boolean success = engine.createCcTask( currentTask, // 当前任务列表中的任意任务 ccActors, new FlowCreator("user456", "赵八") ); ``` -------------------------------- ### getProcessByKey(String tenantId, String processKey) Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/ProcessService.md Retrieves the latest version of a process definition by its key. ```APIDOC ## getProcessByKey(String tenantId, String processKey) ### Description Retrieves the latest version of a process definition by its key. ### Parameters - **tenantId** (String) - Optional - The tenant ID. - **processKey** (String) - Required - The process definition key. ### Returns - **FlwProcess** - The process definition object. ``` -------------------------------- ### Configure Spring Datasource with Environment Variables Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/configuration.md Use placeholders to inject database credentials and connection details from environment variables into Spring properties. ```properties spring.datasource.url=jdbc:mysql://${DB_HOST}:${DB_PORT}/${DB_NAME} spring.datasource.username=${DB_USER} spring.datasource.password=${DB_PASSWORD} ``` -------------------------------- ### 创建流程实例 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/RuntimeService.md 根据流程定义创建流程实例。 ```java FlwInstance createInstance(FlwProcess flwProcess, FlowCreator flowCreator, Map args, NodeModel nodeModel, boolean saveAsDraft, Supplier supplier) ``` -------------------------------- ### FlwProcess 实体类定义 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/types.md 定义流程定义的元数据,包括版本控制、模型JSON及使用范围。 ```java public class FlwProcess extends FlowEntity { protected String processKey; // 流程KEY(唯一标识) protected String processName; // 流程名称 protected String processIcon; // 流程图标URL protected String processType; // 流程分类 protected Integer processVersion; // 流程版本 protected String instanceUrl; // 流程申请URL protected String remark; // 备注说明 protected Integer useScope; // 使用范围(0:全员 1:指定人 2:禁用) protected Integer processState; // 流程状态(0:禁用 1:启用 2:历史版本) protected String processModel; // 流程模型JSON } ``` -------------------------------- ### Configure application.properties Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/configuration.md Define data source, MyBatis Plus, and optional FlowLong engine settings in your application properties file. ```properties # 数据源配置 spring.datasource.url=jdbc:mysql://localhost:3306/flowlong?useUnicode=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # MyBatis Plus 配置 mybatis-plus.mapper-locations=classpath*:/mapper/**/*.xml mybatis-plus.type-aliases-package=com.aizuda.bpm.engine.entity # FlowLong 配置(可选) # flowlong.cache-type=simple # 缓存类型:simple 或 redis # flowlong.id-generator=default # ID生成器类型 ``` -------------------------------- ### Check Process Instance Status in Java Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/errors.md Uses a switch statement to evaluate the current state of a process instance and handle potential query exceptions. ```java public boolean checkInstanceStatus(Long instanceId) { try { FlwInstance instance = queryService.getInstance(instanceId); if (instance == null) { System.out.println("实例不存在"); return false; } // 检查实例状态 InstanceState state = InstanceState.get(instance.getInstanceState()); switch(state) { case active: System.out.println("流程处理中"); return true; case complete: System.out.println("流程已完成"); return false; case reject: System.out.println("流程已驳回"); return false; case revoke: System.out.println("流程已撤销"); return false; case timeout: System.out.println("流程已超时"); return false; case terminate: System.out.println("流程已终止"); return false; default: System.out.println("未知状态"); return false; } } catch (Exception e) { System.err.println("查询异常:" + e.getMessage()); return false; } } ``` -------------------------------- ### createNewTask Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/FlowLongEngine.md Creates a new task based on an existing task, useful for transfers, delegations, or additions. ```APIDOC ## createNewTask(Long taskId, TaskType taskType, PerformType performType, List taskActors, FlowCreator flowCreator, Map args) ### Description Creates a new task based on an existing task, suitable for transfers, delegations, or additions. ### Parameters - **taskId** (Long) - Required - Main task ID - **taskType** (TaskType) - Required - Task type - **performType** (PerformType) - Required - Participation type - **taskActors** (List) - Required - List of participants - **flowCreator** (FlowCreator) - Required - Executor - **args** (Map) - Optional - Task parameters ### Returns - **List** - List of created tasks ``` -------------------------------- ### 执行任务方法定义 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/TaskService.md 根据指定的任务状态和事件类型执行任务。 ```java FlwTask executeTask(Long taskId, FlowCreator flowCreator, Map args, TaskState taskState, TaskEventType eventType) ``` -------------------------------- ### getHisInstancesByBusinessKey(String businessKey) Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/QueryService.md Retrieves a list of historical process instances associated with a specific business key. ```APIDOC ## Method: getHisInstancesByBusinessKey(String businessKey) ### Description Retrieves a list of historical process instances associated with the provided business key. ### Parameters - **businessKey** (String) - Required - The business key associated with the processes. ### Returns - **Optional>** - A list of historical process instances. ``` -------------------------------- ### 防止重复提交 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/errors.md 通过业务 KEY 确保流程实例的唯一性,防止重复提交。 ```java // 使用业务 KEY 防止重复 String businessKey = "APP_" + System.currentTimeMillis(); Optional instanceOpt = engine.startInstanceById( processId, creator, args, false, () -> FlwInstance.of(businessKey) ); // 检查是否已存在相同的流程 if (instanceOpt.isPresent()) { System.out.println("流程已创建,实例ID: " + instanceOpt.get().getId()); } ``` -------------------------------- ### 强制完成指定任务方法定义 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/TaskService.md 强制完成指定的任务。 ```java boolean forceCompleteTask(FlwTask flwTask, FlowCreator flowCreator, TaskState taskState, TaskEventType eventType) ``` -------------------------------- ### 完成任务示例 Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/TaskService.md 仅结束活动任务,不驱动流程继续执行。如果需要驱动流程继续,请使用 executeTask 方法。 ```java default FlwTask complete(Long taskId, FlowCreator flowCreator, Map args) ``` ```java FlowCreator user = new FlowCreator("user123", "张三"); Map args = new HashMap<>(); args.put("approveResult", "pass"); args.put("comment", "审批通过"); FlwTask completedTask = taskService.complete(taskId, user, args); System.out.println("任务已完成: " + completedTask.getTaskName()); ``` -------------------------------- ### Retrieve sub-processes by instance ID Source: https://github.com/aizuda/flowlong/blob/main/_autodocs/api-reference/QueryService.md Fetches all sub-process instances associated with a parent process. ```java Optional> getSubProcessByInstanceId(Long instanceId) ``` ```java // 获取父流程的所有子流程 Optional> subProcesses = queryService.getSubProcessByInstanceId(parentInstanceId); subProcesses.ifPresent(list -> { System.out.println("子流程数量: " + list.size()); list.forEach(sub -> System.out.println("子流程ID: " + sub.getId())); }); ```