### Initialize LoginUser Context Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/README.md Example of setting up a LoginUser object with roles and permissions. ```java LoginUser user = new LoginUser(); user.setUserId(1L); user.setUsername("admin"); user.setRoles(List.of(new RoleDTO(1L, "admin", "admin", "1"))); user.setMenuPermission(Set.of("sys:user:list", "sys:user:edit")); user.setRolePermission(Set.of("admin", "user_manager")); String loginId = user.getLoginId(); // "sys_user:1" ``` -------------------------------- ### Start Workflow Process Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/QUICKSTART.md Initialize a new workflow instance with specific variables. ```java RemoteStartProcess process = new RemoteStartProcess(); process.setProcessKey("leave_approval"); process.setBusinessId("LEAVE_2024_001"); process.setTitle("请假申请"); Map vars = new HashMap<>(); vars.put("days", 3); vars.put("reason", "感冒"); process.setVariable(vars); RemoteStartProcessReturn result = workflowService.startWorkFlow(process); System.out.println("流程实例ID: " + result.getInstanceId()); ``` -------------------------------- ### Example Usage of selectRoleNamesByIds Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-system-services.md Demonstrates how to call the service method and iterate over the resulting map. ```java Map roleNames = remoteRoleService.selectRoleNamesByIds( Arrays.asList(1L, 2L, 3L) ); // Returns: {1="管理员", 2="编辑", 3="查看"} for (Map.Entry entry : roleNames.entrySet()) { System.out.println("Role " + entry.getKey() + ": " + entry.getValue()); } ``` -------------------------------- ### Register New User Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/types.md Example demonstrating how to populate a RemoteUserBo instance and register it via the remote user service. ```java // User registration RemoteUserBo newUser = new RemoteUserBo(); newUser.setUserName("newemployee"); newUser.setNickName("新员工"); newUser.setPassword("hashedPassword..."); // Should be pre-hashed newUser.setEmail("employee@company.com"); newUser.setPhoneNumber("13800138000"); newUser.setDeptId(100L); newUser.setStatus("0"); // Active Boolean registered = remoteUserService.registerUserInfo(newUser); ``` -------------------------------- ### LoginUser Integration Example Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/types.md Demonstrates how to populate and store a LoginUser instance within the Sa-Token session during the login process. ```java @PostMapping("/login") public R login(@RequestBody LoginBody body) { // Fetch user LoginUser user = remoteUserService.getUserInfo(body.getUsername()); // Generate token String token = stpLogin.getTokenValue(); user.setToken(token); user.setLoginTime(System.currentTimeMillis()); user.setExpireTime(System.currentTimeMillis() + tokenExpire); // Store in session (Sa-Token) StpUtil.login(user.getLoginId()); StpUtil.getSession().set("loginUser", user); return R.ok(new TokenVO(token)); } ``` -------------------------------- ### getRolePermission Usage Example Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-system-services.md Demonstrates checking for a specific role key after retrieving the set of roles for a user. ```java Set roles = remotePermissionService.getRolePermission(123L); if (roles.contains("admin")) { // Grant administrative access } ``` -------------------------------- ### startCompleteTask(RemoteStartProcess startProcess) Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-workflow-service.md Starts a workflow and immediately completes the first task, typically used for auto-complete workflows. ```APIDOC ## startCompleteTask(RemoteStartProcess startProcess) ### Description Starts a workflow and immediately completes the first task (used when first task is auto-complete). ### Parameters - **startProcess** (RemoteStartProcess) - Required - Process startup parameters ### Returns - **boolean** - true if process started and first task completed ``` -------------------------------- ### Implement System Constants Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/configuration.md Examples demonstrating the application of global constants for URL validation, status handling, encoding, and system logic. ```java // URL validation String url = "https://example.com"; if (url.startsWith(Constants.HTTPS)) { // Secure URL } // Operation result handling if (Constants.SUCCESS.equals(operationResult)) { System.out.println("操作成功"); } // Encoding conversion String text = "Hello"; byte[] utf8Bytes = text.getBytes(Constants.UTF8); // Department hierarchy - top level if (deptId.equals(Constants.TOP_PARENT_ID)) { // Root organization } // Captcha validation if (System.currentTimeMillis() - captchaTime > Constants.CAPTCHA_EXPIRATION * 60 * 1000) { throw new ServiceException("验证码已过期"); } ``` -------------------------------- ### Throw Service and User Exceptions Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/README.md Examples of throwing business logic and user-specific exceptions. ```java throw new ServiceException("用户已停用"); throw new ServiceException("金额{}超过限制", amount); throw new ServiceException("参数无效", 400); ``` ```java throw new UserException("用户名不存在"); ``` -------------------------------- ### Get Dictionary Options Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/QUICKSTART.md Fetch dictionary data and transform it into a map for UI components. ```java // Get all options for a dictionary type List options = dictService.selectDictDataByType("sys_user_sex"); // Build dropdown list Map selectOptions = options.stream() .collect(Collectors.toMap( RemoteDictDataVo::getDictValue, RemoteDictDataVo::getDictLabel )); // Output: {"0": "男", "1": "女", "2": "未知"} ``` -------------------------------- ### Initiate a workflow process Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-workflow-service.md Use to start a new workflow instance by providing process keys, business IDs, and initial variables. ```java RemoteStartProcess startRequest = new RemoteStartProcess(); startRequest.setProcessKey("leave_application"); // Workflow definition key startRequest.setBusinessId("LEAVE_2024_001"); // Link to business entity startRequest.setTitle("张三的请假申请"); startRequest.setApplicant("zhangsan"); // Set initial variables Map variables = new HashMap<>(); variables.put("leaveType", "病假"); variables.put("days", 3); variables.put("reason", "感冒"); startRequest.setVariable(variables); RemoteStartProcessReturn result = remoteWorkflowService.startWorkFlow(startRequest); System.out.println("流程实例ID: " + result.getInstanceId()); System.out.println("首个任务ID: " + result.getTaskId()); ``` -------------------------------- ### getMenuPermission Usage Example Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-system-services.md Shows how to retrieve menu permissions and use them in conjunction with Spring Security's @PreAuthorize annotation. ```java Set perms = remotePermissionService.getMenuPermission(123L); // Check in annotation processor @PreAuthorize("hasPermission(#id, 'sys:user:edit')") public void editUser(Long id) { // Only users with sys:user:edit permission can access } ``` -------------------------------- ### Get Configuration Values Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/QUICKSTART.md Retrieve configuration settings with support for type conversion and complex object mapping. ```java // Simple value String value = configService.getConfigValue("sys.site.name"); // With type conversion int timeout = configService.getConfigInt("sys.timeout.seconds"); boolean enabled = configService.getConfigBool("sys.feature.enabled"); BigDecimal rate = configService.getConfigDecimal("sys.tax.rate"); // Complex object OssConfig ossConfig = configService.getConfigObject("sys.oss", OssConfig.class); List channels = configService.getConfigArrayMap("notification.channels"); ``` -------------------------------- ### Manage Workflows with RemoteWorkflowService Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/README.md Demonstrates starting a process, completing tasks, and checking business status using the RemoteWorkflowService. ```java @Service public class WorkflowConsumer { @Autowired private RemoteWorkflowService workflowService; // Start process public Long startApproval(String businessId, String title) { RemoteStartProcess request = new RemoteStartProcess(); request.setProcessKey("approval_workflow"); request.setBusinessId(businessId); request.setTitle(title); RemoteStartProcessReturn result = workflowService.startWorkFlow(request); return result.getInstanceId(); } // Complete task public boolean approveTask(Long taskId, String comment) { RemoteCompleteTask completion = new RemoteCompleteTask(); completion.setTaskId(taskId); completion.setApproveOrReject("approve"); completion.setMessage(comment); return workflowService.completeTask(completion); } // Check status public String getProcessStatus(String businessId) { return workflowService.getBusinessStatus(businessId); } } ``` -------------------------------- ### Handle Workflow Initiation Response Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/domain-objects.md Shows how to extract instance and task identifiers from the RemoteStartProcessReturn object after a successful workflow start. ```java RemoteStartProcessReturn result = workflowService.startWorkFlow(request); System.out.println("流程实例ID: " + result.getInstanceId()); System.out.println("首个任务ID: " + result.getTaskId()); // Store for reference processRecord.setInstanceId(result.getInstanceId()); processRecord.setCurrentTaskId(result.getTaskId()); ``` -------------------------------- ### Retrieve Dictionary Data List Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-system-services.md Method signature and usage example for fetching a list of dictionary entries. ```java List selectDictDataByType(String dictType) ``` ```java List sexOptions = remoteDict.selectDictDataByType("sys_user_sex"); // Returns: // [{dictLabel: "男", dictValue: "0", ...}, // {dictLabel: "女", dictValue: "1", ...}, // {dictLabel: "未知", dictValue: "2", ...}] // Render in frontend for (RemoteDictDataVo option : sexOptions) { System.out.println(option.getDictLabel() + ": " + option.getDictValue()); } ``` -------------------------------- ### Use selectUrlByIds for File Downloads Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-resource-services.md Example usage of selectUrlByIds to retrieve and iterate over file URLs. ```java String urls = remoteFileService.selectUrlByIds("100,101,102"); // Returns: "https://oss.example.com/files/file1.pdf,https://oss.example.com/files/file2.jpg,..." String[] urlArray = urls.split(","); for (String url : urlArray) { System.out.println("Download: " + url); } ``` -------------------------------- ### Use selectByIds for Metadata Access Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-resource-services.md Example usage of selectByIds to retrieve and process file metadata. ```java List files = remoteFileService.selectByIds("100,101"); for (RemoteFile file : files) { System.out.println("File: " + file.getOriginalName()); System.out.println("Type: " + file.getFileSuffix()); System.out.println("URL: " + file.getUrl()); } ``` -------------------------------- ### Start and complete a workflow task Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-workflow-service.md Initiates a process and immediately completes the first task, typically used for auto-approval workflows. ```java RemoteStartProcess request = new RemoteStartProcess(); request.setProcessKey("auto_approval"); request.setBusinessId("AUTO_PROCESS_001"); Map vars = new HashMap<>(); vars.put("autoApprove", true); vars.put("approvalTime", System.currentTimeMillis()); request.setVariable(vars); boolean success = remoteWorkflowService.startCompleteTask(request); // Process instance created and first automatic step completed ``` -------------------------------- ### Using HttpStatus in Responses Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/errors.md Examples of creating standardized responses using the R utility class with various status codes. ```java R response = R.ok(user); // code=0 R response = R.fail("Error"); // code=500 R response = R.fail(401, "Unauth"); // code=401 R response = R.warn("Already exists"); // code=301 ``` -------------------------------- ### Retrieve Dictionary Type Metadata Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-system-services.md Method signature and usage example for fetching dictionary type information. ```java RemoteDictTypeVo selectDictTypeByType(String dictType) ``` ```java RemoteDictTypeVo dictType = remoteDict.selectDictTypeByType("sys_user_sex"); // Metadata: {dictName: "用户性别", dictType: "sys_user_sex", ...} ``` -------------------------------- ### Throwing ServiceException in Service Layer Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/errors.md Example of throwing business exceptions within a service class. ```java @Service public class UserService { public User getUserById(Long userId) { User user = userMapper.selectById(userId); if (user == null) { throw new ServiceException("用户不存在", 404); } if ("1".equals(user.getStatus())) { throw new ServiceException("用户已停用,无法操作"); } return user; } public void updateUser(Long userId, UserUpdateDto dto) { // Validation if (dto.getEmail() != null) { User existing = userMapper.selectByEmail(dto.getEmail()); if (existing != null && !existing.getId().equals(userId)) { throw new ServiceException("邮箱{}已被使用", dto.getEmail()); } } // Update User user = getUserById(userId); user.setNickName(dto.getNickName()); userMapper.updateById(user); } } ``` -------------------------------- ### Send SMS with Default Template Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-resource-services.md Method signature and usage example for sending a simple SMS message using the default template. ```java RemoteSms sendMessage(String phone, String message) ``` ```java RemoteSms result = remoteSmService.sendMessage("13800138000", "您的验证码是123456,有效期为5分钟"); if (result.isSuccess()) { System.out.println("短信发送成功: " + result.getMessageId()); } else { System.err.println("发送失败: " + result.getErrorMsg()); } ``` -------------------------------- ### Send SMS with Variable Substitution Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-resource-services.md Method signature and usage example for sending an SMS using a LinkedHashMap to provide template parameters. ```java RemoteSms sendMessage(String phone, LinkedHashMap messages) ``` ```java LinkedHashMap params = new LinkedHashMap<>(); params.put("code", "123456"); params.put("minutes", "5"); params.put("product", "MyApp"); RemoteSms result = remoteSmService.sendMessage("13800138000", params); // SMS template: "尊敬的用户,您在${product}申请的验证码是${code},有效期${minutes}分钟" // Rendered: "尊敬的用户,您在MyApp申请的验证码是123456,有效期5分钟" ``` -------------------------------- ### LoginUser getLoginId Usage Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/types.md Example of generating a composite login identifier from a LoginUser instance. ```java LoginUser user = getUserInfo(); String loginId = user.getLoginId(); // Returns "sys_user:123" ``` -------------------------------- ### Initialize RemoteDictDataVo Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/domain-objects.md Demonstrates creating and configuring a dictionary entry object for UI and database usage. ```java RemoteDictDataVo sex = new RemoteDictDataVo(); sex.setDictLabel("男"); // Shown in UI sex.setDictValue("0"); // Stored in database/code sex.setDictType("sys_user_sex"); sex.setDictSort(1); sex.setIsDefault("Y"); // Default selection in UI // Usage in frontend: // ``` -------------------------------- ### startWorkFlow(RemoteStartProcess startProcess) Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-workflow-service.md Initiates a new workflow process instance using the provided startup parameters. ```APIDOC ## startWorkFlow(RemoteStartProcess startProcess) ### Description Initiates a new workflow process instance. ### Parameters - **startProcess** (RemoteStartProcess) - Required - Process startup parameters ### Returns - **RemoteStartProcessReturn** - Result including instance ID and initial task info ``` -------------------------------- ### Orchestrate Employee Onboarding Service Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/integration-patterns.md Uses multiple remote service clients to perform a multi-step onboarding process, including validation, user creation, role assignment, file uploads, and workflow initiation. ```java @Service public class EmployeeOnboardingService { @Autowired private RemoteUserService userService; @Autowired private RemoteDeptService deptService; @Autowired private RemoteRoleService roleService; @Autowired private RemoteWorkflowService workflowService; @Autowired private RemoteFileService fileService; @Transactional public void onboardNewEmployee(EmployeeOnboardingDto dto) throws Exception { // Step 1: Verify department exists RemoteDeptVo dept = deptService.selectDeptById(dto.getDeptId()); if (dept == null) { throw new ServiceException("部门不存在"); } // Step 2: Create user account via RPC RemoteUserBo newUser = new RemoteUserBo(); newUser.setUserName(dto.getEmail().split("@")[0]); newUser.setNickName(dto.getFullName()); newUser.setEmail(dto.getEmail()); newUser.setPhoneNumber(dto.getPhone()); newUser.setDeptId(dto.getDeptId()); newUser.setPassword(generateTemporaryPassword()); Boolean userCreated = userService.registerUserInfo(newUser); if (!userCreated) { throw new ServiceException("员工账户创建失败"); } // Step 3: Assign roles based on position Map roleNames = roleService.selectRoleNamesByIds( Collections.singletonList(dto.getPositionRoleId()) ); // Step 4: Upload employee documents List uploadedDocs = new ArrayList<>(); for (MultipartFile file : dto.getDocuments()) { RemoteFile doc = fileService.uploadFile(file, "onboarding/" + dto.getEmail()); uploadedDocs.add(doc); } // Step 5: Start onboarding workflow RemoteStartProcess workflow = new RemoteStartProcess(); workflow.setProcessKey("employee_onboarding"); workflow.setBusinessId("ONBOARD_" + dto.getEmail()); workflow.setTitle(dto.getFullName() + "的入职流程"); Map variables = new HashMap<>(); variables.put("employeeName", dto.getFullName()); variables.put("department", dept.getDeptName()); variables.put("position", dto.getPosition()); variables.put("startDate", dto.getStartDate()); variables.put("documentsCount", uploadedDocs.size()); workflow.setVariable(variables); RemoteStartProcessReturn result = workflowService.startWorkFlow(workflow); // Step 6: Persist onboarding record EmployeeOnboarding record = new EmployeeOnboarding(); record.setWorkflowInstanceId(result.getInstanceId()); record.setEmail(dto.getEmail()); record.setStatus("IN_PROGRESS"); onboardingRepository.save(record); logger.info("员工{}的入职流程已启动,实例ID: {}", dto.getEmail(), result.getInstanceId()); } } ``` -------------------------------- ### File and Service Module Configuration Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/configuration.md Configures storage providers (MinIO, Aliyun OSS), SMS services, and email SMTP settings. ```yaml # File storage configuration oss: minio: enabled: true endpoint: http://127.0.0.1:9000 access-key: minioadmin secret-key: minioadmin bucket-name: ruoyi aliyun: enabled: false endpoint: oss-cn-beijing.aliyuncs.com access-key: secret-key: bucket-name: ruoyi # File upload settings upload: max-file-size: 10485760 # 10MB in bytes allowed-extensions: - pdf - doc - docx - xls - xlsx - txt - jpg - jpeg - png - gif # SMS service configuration sms: # Aliyun SMS aliyun: enabled: true region-id: cn-beijing access-key-id: access-key-secret: sign-name: default-template: # Tencent SMS tencent: enabled: false secret-id: secret-key: region: ap-beijing sms-sdk-app-id: sign-name: default-template-id: # Email configuration mail: enabled: true smtp: host: smtp.gmail.com port: 587 username: password: auth: true starttls: enabled: true required: true properties: mail.smtp.timeout: 5000 from: noreply@example.com from-name: RuoYi-Cloud-Plus ``` -------------------------------- ### Retrieve configuration as array of JSON objects Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-system-services.md Fetches a configuration key as a list of Dict objects. Returns an empty list if parsing fails. ```java List dataSourceList = remoteConfigService.getConfigArrayMap("sys.datasources"); // Configuration stored as: [ // {"name": "primary", "url": "jdbc:mysql://localhost/main"}, // {"name": "archive", "url": "jdbc:mysql://localhost/archive"} // ] for (Dict ds : dataSourceList) { System.out.println("数据源: " + ds.getStr("name")); } ``` -------------------------------- ### Application Environment Variables Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/configuration.md Define core application settings including profiles, server ports, database, and Redis connections. ```bash # Active profile (dev, test, prod) SPRING_PROFILES_ACTIVE=dev # Server configuration SERVER_PORT=8080 SERVER_SERVLET_CONTEXT_PATH=/auth # Database SPRING_DATASOURCE_URL=jdbc:mysql://localhost:3306/ruoyi_cloud_plus SPRING_DATASOURCE_USERNAME=root SPRING_DATASOURCE_PASSWORD=password SPRING_DATASOURCE_DRIVER_CLASS_NAME=com.mysql.cj.jdbc.Driver # Redis SPRING_REDIS_HOST=127.0.0.1 SPRING_REDIS_PORT=6379 SPRING_REDIS_PASSWORD= SPRING_REDIS_DATABASE=0 # Logging LOGGING_LEVEL_ROOT=INFO LOGGING_LEVEL_ORG_DROMARA=DEBUG ``` -------------------------------- ### RemoteUserVo Usage in Controller Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/types.md Example of returning a list of RemoteUserVo objects within a paginated REST API response. ```java @GetMapping("/users") public R> listUsers(UserQuery query) { List users = userService.queryUsers(query); return R.ok(PageResult.build(users, users.size())); } ``` -------------------------------- ### Initialize RemoteDictTypeVo Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/domain-objects.md Shows how to define a dictionary type and query its associated values using the remote service. ```java RemoteDictTypeVo genderDict = new RemoteDictTypeVo(); genderDict.setDictType("sys_user_sex"); genderDict.setDictName("用户性别"); genderDict.setRemark("性别分类"); // Query all values for this type List values = remoteDictService .selectDictDataByType("sys_user_sex"); ``` -------------------------------- ### Multi-Service Orchestration Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/QUICKSTART.md Demonstrates coordinating multiple remote services within a single business service method using dependency injection. ```java @Service public class BusinessService { @Autowired private RemoteUserService userService; @Autowired private RemoteDictService dictService; @Autowired private RemoteWorkflowService workflowService; public void complexProcess(Long userId, OrderDto order) { // Step 1: Get user LoginUser user = userService.getUserInfo(userId); // Step 2: Get configuration String orderType = dictService.selectDictDataByType("order_type") .get(0).getDictLabel(); // Step 3: Start workflow RemoteStartProcess process = new RemoteStartProcess(); // ... configure process RemoteStartProcessReturn result = workflowService.startWorkFlow(process); // Step 4: Use result order.setInstanceId(result.getInstanceId()); } } ``` -------------------------------- ### Retrieve Raw Configuration Value Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-system-services.md Fetches a configuration value as a raw string. ```java String getConfigValue(String configKey) ``` ```java String siteName = remoteConfigService.getConfigValue("sys.site.name"); // Returns: "RuoYi-Cloud-Plus" ``` -------------------------------- ### Get Instance ID by Business ID Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-workflow-service.md Looks up the workflow instance ID associated with a business entity ID. ```java Long getInstanceIdByBusinessId(String businessId) ``` ```java Long instanceId = remoteWorkflowService.getInstanceIdByBusinessId("LEAVE_REQUEST_2024_001"); if (instanceId != null) { Map vars = remoteWorkflowService.instanceVariable(instanceId); } ``` -------------------------------- ### Environment-Specific Configuration Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/configuration.md Configures core infrastructure services including database, Redis, and Sa-Token security settings. ```yaml # Server configuration server: port: 8080 servlet: context-path: /auth # Database configuration spring: datasource: dynamic: primary: master datasource: master: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/ruoyi_cloud_plus username: root password: password hikari: minimum-idle: 5 maximum-pool-size: 20 idle-timeout: 600000 max-lifetime: 1800000 jpa: hibernate: ddl-auto: validate format_sql: true show_sql: false # Redis configuration redis: host: 127.0.0.1 port: 6379 password: database: 0 timeout: 10s lettuce: pool: max-active: 10 max-idle: 8 min-idle: 0 # Sa-Token configuration sa-token: # Token configuration token-name: Authorization timeout: 2592000 # 30 days in seconds activity-timeout: -1 # -1 = no activity timeout is-concurrent: true is-share: false # JWT configuration jwt-secret: your-secret-key-here # Session configuration token-style: uuid # Login configuration login: login-url: /login unauthorized-url: /unauthorized # Logging configuration logging: level: root: INFO org.dromara: DEBUG org.springframework: INFO file: name: logs/auth-service.log max-size: 10MB max-history: 10 ``` -------------------------------- ### Get Business Status by Business ID Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-workflow-service.md Retrieves the current process status using a business entity ID. ```java String getBusinessStatus(String businessId) ``` ```java String status = remoteWorkflowService.getBusinessStatus("ORDER_2024_123456"); if ("COMPLETED".equals(status)) { System.out.println("订单流程已完成"); } ``` -------------------------------- ### Project Directory Structure Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/QUICKSTART.md Standard layout for Java source files in the project. ```text src/main/java/ ├── controller/ # REST endpoints │ └── UserController.java ├── service/ # Business logic │ └── UserService.java ├── config/ # Configuration classes │ └── AuthConfig.java └── exception/ # Exception handlers └── GlobalExceptionHandler.java ``` -------------------------------- ### Get Business Status by Task ID Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-workflow-service.md Retrieves the current process status using a specific task ID. ```java String getBusinessStatusByTaskId(Long taskId) ``` ```java String status = remoteWorkflowService.getBusinessStatusByTaskId(1001L); // Returns: "WAITING_APPROVAL" or "APPROVED" etc. ``` -------------------------------- ### Retrieve User Information in Java Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/00-START-HERE.md Demonstrates fetching user details by username and exposing them via a REST controller endpoint. ```java @Autowired private RemoteUserService userService; // By username LoginUser user = userService.getUserInfo("admin"); // REST response @GetMapping("/user/{id}") public R getUser(@PathVariable Long id) { return R.ok(userService.getUserInfo(id)); } ``` -------------------------------- ### Retrieve System Configurations Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/00-START-HERE.md Fetches configuration values from the system service, supporting string, integer, and boolean types. ```java String siteName = configService.getConfigValue("sys.site.name"); int timeout = configService.getConfigInt("sys.timeout.seconds"); boolean enabled = configService.getConfigBool("sys.feature.enabled"); ``` -------------------------------- ### Complete a workflow task in Java Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/domain-objects.md Demonstrates initializing a RemoteCompleteTask object with decision details and variables before invoking the workflow service. ```java RemoteCompleteTask completion = new RemoteCompleteTask(); completion.setTaskId(taskId); completion.setInstanceId(instanceId); completion.setApproveOrReject("approve"); completion.setMessage("符合采购标准,同意采购"); // Set completion context Map variables = new HashMap<>(); variables.put("approver", "li_si"); variables.put("approvalDate", new Date()); variables.put("comment", "符合采购标准,同意采购"); completion.setVariable(variables); boolean completed = workflowService.completeTask(completion); ``` -------------------------------- ### Implement Workflow Service in Business Logic Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-workflow-service.md Demonstrates integrating RemoteWorkflowService to initiate processes, complete tasks, and query status within a service layer. ```java @Service public class LeaveRequestService { @Autowired private RemoteWorkflowService workflowService; public void submitLeaveRequest(LeaveRequestDto dto) { // 1. Create business entity (leave request) LeaveRequest request = new LeaveRequest(); request.setApplicant(dto.getApplicant()); request.setDays(dto.getDays()); request.setReason(dto.getReason()); leaveRequestRepository.save(request); // 2. Start workflow RemoteStartProcess startProcess = new RemoteStartProcess(); startProcess.setProcessKey("leave_approval_process"); startProcess.setBusinessId("LEAVE_" + request.getId()); startProcess.setTitle(dto.getApplicant() + "的请假申请"); Map variables = new HashMap<>(); variables.put("applicant", dto.getApplicant()); variables.put("days", dto.getDays()); variables.put("reason", dto.getReason()); startProcess.setVariable(variables); RemoteStartProcessReturn result = workflowService.startWorkFlow(startProcess); // 3. Store instance ID for tracking request.setInstanceId(result.getInstanceId()); leaveRequestRepository.save(request); } public void approveLeaveRequest(Long taskId, String approver, boolean approved) { RemoteCompleteTask completion = new RemoteCompleteTask(); completion.setTaskId(taskId); completion.setApproveOrReject(approved ? "approve" : "reject"); Map variables = new HashMap<>(); variables.put("approver", approver); variables.put("approvalDate", new Date()); completion.setVariable(variables); workflowService.completeTask(completion); } public String checkLeaveStatus(String businessId) { return workflowService.getBusinessStatus(businessId); } } ``` -------------------------------- ### Implement Batch Operations with Error Handling in Java Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/integration-patterns.md Demonstrates processing records in chunks to prevent service overload and performing individual updates with error collection. ```java @Service public class BulkOperationService { @Autowired private RemoteUserService userService; @Autowired private RemoteSmsService smsService; public BulkSmsResult sendBulkSms(List phones, String templateId, LinkedHashMap params) { BulkSmsResult result = new BulkSmsResult(); List failed = new ArrayList<>(); int successCount = 0; // Process in batches to avoid overwhelming the service for (int i = 0; i < phones.size(); i += 100) { List batch = phones.subList(i, Math.min(i + 100, phones.size())); try { RemoteSms sendResult = smsService.messageTexting( batch, templateId, params ); if (sendResult.isSuccess()) { successCount += batch.size(); } else { failed.addAll(batch); logger.warn("批量短信发送部分失败: {}", sendResult.getErrorMsg()); } } catch (Exception e) { failed.addAll(batch); logger.error("批量短信发送异常", e); } } result.setTotal(phones.size()); result.setSuccessCount(successCount); result.setFailureCount(failed.size()); result.setFailedPhones(failed); return result; } public void reassignUsersToRole(List userIds, Long newRoleId) { List errors = new ArrayList<>(); for (Long userId : userIds) { try { RemoteUserBo user = new RemoteUserBo(userId); user.setRoleId(newRoleId); userService.updateUser(user); } catch (UserException e) { errors.add("用户ID " + userId + ": " + e.getMessage()); } catch (ServiceException e) { errors.add("用户ID " + userId + ": " + e.getMessage()); } } if (!errors.isEmpty()) { logger.warn("部分用户角色分配失败:\n{}", String.join("\n", errors)); throw new ServiceException("{}个用户角色分配失败,请查看日志", errors.size()); } } } ``` -------------------------------- ### Send SMS with Specific Template ID Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-resource-services.md Method signature and usage example for sending an SMS using a specific provider template ID and parameters. ```java RemoteSms sendMessage(String phone, String templateId, LinkedHashMap messages) ``` ```java LinkedHashMap params = new LinkedHashMap<>(); params.put("name", "张三"); params.put("amount", "1000.00"); RemoteSms result = remoteSmService.sendMessage( "13800138000", "aliyun_payment_notification_v1", params ); ``` -------------------------------- ### Implement Workflow-Based Leave Request Service Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/integration-patterns.md Uses RemoteWorkflowService to manage leave request lifecycles, including starting processes and completing approval tasks. Requires transactional support and integration with remote user and workflow services. ```java @Service @Transactional public class LeaveRequestService { @Autowired private RemoteWorkflowService workflowService; @Autowired private RemoteUserService userService; // Submit leave request and start workflow public LeaveRequest submitRequest(LeaveRequestDto dto, LoginUser applicant) { // 1. Create leave request in database LeaveRequest request = new LeaveRequest(); request.setApplicantId(applicant.getUserId()); request.setLeaveType(dto.getLeaveType()); request.setStartDate(dto.getStartDate()); request.setEndDate(dto.getEndDate()); request.setDays(dto.getDays()); request.setReason(dto.getReason()); request.setStatus("SUBMITTED"); LeaveRequest saved = leaveRepository.save(request); // 2. Start workflow process RemoteStartProcess workflow = new RemoteStartProcess(); workflow.setProcessKey("leave_approval"); workflow.setBusinessId("LEAVE_" + saved.getId()); workflow.setTitle(applicant.getNickname() + "的" + dto.getLeaveType() + "请假申请"); workflow.setApplicant(applicant.getUsername()); Map variables = new HashMap<>(); variables.put("applicant", applicant.getUsername()); variables.put("leaveType", dto.getLeaveType()); variables.put("days", dto.getDays()); variables.put("reason", dto.getReason()); variables.put("startDate", dto.getStartDate()); variables.put("deptId", applicant.getDeptId()); workflow.setVariable(variables); RemoteStartProcessReturn result = workflowService.startWorkFlow(workflow); saved.setInstanceId(result.getInstanceId()); saved.setCurrentTaskId(result.getTaskId()); return leaveRepository.save(saved); } // Manager approves/rejects public void approveRequest(Long requestId, boolean approved, String comment, LoginUser approver) { LeaveRequest request = leaveRepository.findById(requestId).orElseThrow(); // Complete task in workflow RemoteCompleteTask completion = new RemoteCompleteTask(); completion.setTaskId(request.getCurrentTaskId()); completion.setInstanceId(request.getInstanceId()); completion.setApproveOrReject(approved ? "approve" : "reject"); Map variables = new HashMap<>(); variables.put("approver", approver.getUsername()); variables.put("approvalDate", new Date()); variables.put("approvalComment", comment); completion.setVariable(variables); workflowService.completeTask(completion); // Update leave request status request.setStatus(approved ? "APPROVED" : "REJECTED"); request.setApproverComment(comment); leaveRepository.save(request); } // Check overall process status public String getRequestStatus(Long requestId) { LeaveRequest request = leaveRepository.findById(requestId).orElseThrow(); String workflowStatus = workflowService.getBusinessStatus("LEAVE_" + requestId); return switch (workflowStatus) { case "APPROVED" -> "已批准"; case "REJECTED" -> "已拒绝"; case "PENDING" -> "待审批"; default -> "处理中"; }; } } ``` -------------------------------- ### Retrieve Integer Configuration Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-system-services.md Fetches and converts a configuration value to an Integer. ```java default Integer getConfigInt(String configKey) ``` ```java Integer maxPassword = remoteConfigService.getConfigInt("sys.password.maxAge"); // Returns: 90 (days before password expiration) ``` -------------------------------- ### Include Context for Debugging Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/errors.md Attach detailed information to exceptions to assist in troubleshooting. ```java try { processData(item); } catch (Exception e) { throw new ServiceException("处理数据失败: " + item.getId()) .setDetailMessage("处理的数据: " + item.toString()) .setDetailMessage("原始错误: " + e.getMessage()); } ``` -------------------------------- ### Working with Dictionary Services Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/README.md Fetch dictionary metadata and data options for use in application logic or frontend components. ```java @Service public class DictConsumer { @Autowired private RemoteDictService dictService; public void useDictionaries() { // Get dictionary type metadata RemoteDictTypeVo sexType = dictService.selectDictTypeByType("sys_user_sex"); // Get all values List sexOptions = dictService.selectDictDataByType("sys_user_sex"); // Returns: [{dictLabel: "男", dictValue: "0"}, {dictLabel: "女", dictValue: "1"}, ...] // Use in frontend selectlist for (RemoteDictDataVo option : sexOptions) { System.out.println(option.getDictLabel()); // "男", "女" } } } ``` -------------------------------- ### Register New User Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-user-service.md Registers a new user account using a RemoteUserBo object, handling registration-specific exceptions. ```java Boolean registerUserInfo(RemoteUserBo remoteUserBo) throws UserException, ServiceException ``` ```java RemoteUserBo newUser = new RemoteUserBo(); newUser.setUserName("newuser"); newUser.setNickName("新用户"); newUser.setPassword("hashedPassword123"); newUser.setEmail("newuser@example.com"); newUser.setPhoneNumber("13900139000"); try { Boolean success = remoteUserService.registerUserInfo(newUser); if (success) { System.out.println("用户注册成功"); } } catch (UserException e) { System.err.println("用户名已存在: " + e.getMessage()); } catch (ServiceException e) { System.err.println("注册失败: " + e.getMessage()); } ``` -------------------------------- ### Initialize RemoteUserBo with ID Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/types.md Constructor usage for creating a user object with a pre-set ID. ```java RemoteUserBo user = new RemoteUserBo(123L); ``` -------------------------------- ### Catching UserException in Controller Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/errors.md Demonstrates handling user-related exceptions during login to return appropriate failure responses. ```java @PostMapping("/login") public R login(@RequestBody LoginBody body) { try { LoginUser user = remoteUserService.getUserInfo(body.getUsername()); // Continue with authentication return R.ok(new TokenVO(token)); } catch (UserException e) { return R.fail(e.getMessage()); } } ``` -------------------------------- ### registerUserInfo(RemoteUserBo remoteUserBo) Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-user-service.md Registers a new user account in the system. ```APIDOC ## registerUserInfo(RemoteUserBo remoteUserBo) ### Description Registers a new user account in the system. ### Signature `Boolean registerUserInfo(RemoteUserBo remoteUserBo) throws UserException, ServiceException` ### Parameters - **remoteUserBo** (RemoteUserBo) - User registration data ### Returns - **Boolean** - true if registration succeeded ### Throws - **UserException** - Username already exists, invalid email, or registration disabled - **ServiceException** - Database or service layer error ``` -------------------------------- ### RemoteConfigService Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-system-services.md Interface for retrieving system configurations with type conversion support. ```APIDOC ## RemoteConfigService ### Description Provides methods to access system configurations by key, with automatic type conversion for various data types. ### Methods #### selectRegisterEnabled() Checks if new user registration is enabled. - **Returns**: boolean - true if allowed, false otherwise. #### getConfigValue(String configKey) Retrieves raw string configuration value. - **Parameters**: configKey (String) - The configuration key. - **Returns**: String - The configuration value or null. #### getConfigBool(String configKey) Retrieves configuration as a boolean. - **Parameters**: configKey (String) - The configuration key. - **Returns**: Boolean - The converted boolean value. #### getConfigInt(String configKey) Retrieves configuration as an integer. - **Parameters**: configKey (String) - The configuration key. - **Returns**: Integer - The converted integer value. #### getConfigLong(String configKey) Retrieves configuration as a long integer. - **Parameters**: configKey (String) - The configuration key. - **Returns**: Long - The converted long value. #### getConfigDecimal(String configKey) Retrieves configuration as a BigDecimal. - **Parameters**: configKey (String) - The configuration key. - **Returns**: BigDecimal - The converted decimal value. #### getConfigMap(String configKey) Retrieves configuration as a JSON object/map. - **Parameters**: configKey (String) - The configuration key. - **Returns**: Dict - A HashMap-like object. ``` -------------------------------- ### Auth Module Configuration Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/configuration.md Settings for JWT authentication, captcha verification, and OAuth2 provider integration. ```yaml # Auth module specific settings auth: jwt: enabled: true secret: your-jwt-secret expiration: 86400 # 1 day in seconds captcha: enabled: true type: redis # or image length: 6 expire-minutes: 2 login: max-retry-count: 5 lock-duration-minutes: 30 oauth2: enabled: false providers: - name: github client-id: client-secret: redirect-uri: http://localhost:8080/auth/oauth2/callback - name: weixin client-id: client-secret: redirect-uri: http://localhost:8080/auth/oauth2/callback ``` -------------------------------- ### Workflow Process Initiation Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/00-START-HERE.md Initializes a new workflow process instance using the RemoteStartProcess object. ```java RemoteStartProcess process = new RemoteStartProcess(); process.setProcessKey("leave_approval"); process.setBusinessId("LEAVE_2024_001"); process.setTitle("请假申请"); RemoteStartProcessReturn result = workflowService.startWorkFlow(process); Long instanceId = result.getInstanceId(); ``` -------------------------------- ### Implement Centralized Configuration Management in Java Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/integration-patterns.md Utilize RemoteConfigService to fetch dynamic limits, feature flags, and complex configuration objects. Ensure configurations are validated before use to prevent runtime errors. ```java @Service public class ConfigurableFeatureService { @Autowired private RemoteConfigService configService; public void processOrderWithDynamicLimits(OrderDto order) { // Fetch config values (cached by default) Integer maxOrderAmount = configService.getConfigInt("order.max.amount"); Boolean requiresApproval = configService.getConfigBool("order.approval.required"); Integer approvalThreshold = configService.getConfigInt("order.approval.threshold"); // Apply configuration if (order.getTotalAmount() > maxOrderAmount) { throw new ServiceException("订单金额{}超过系统限制{}", order.getTotalAmount(), maxOrderAmount); } if (requiresApproval && order.getTotalAmount() > approvalThreshold) { // Trigger approval workflow startApprovalWorkflow(order); } else { // Auto-process processOrder(order); } } public void sendNotificationWithConfig(NotificationRequest request) { // Get notification channels from config List channelConfigs = configService.getConfigArrayMap("notification.channels"); for (Dict channel : channelConfigs) { String type = channel.getStr("type"); boolean enabled = channel.getBool("enabled"); if (!enabled) continue; switch (type) { case "email": sendEmailNotification(request); break; case "sms": sendSmsNotification(request); break; case "push": sendPushNotification(request); break; } } } public OssConfig getStorageConfiguration() { // Deserialize complex config object OssConfig ossConfig = configService.getConfigObject( "sys.oss.config", OssConfig.class ); // Validate configuration if (ossConfig == null || !ossConfig.isEnabled()) { throw new ServiceException("文件存储服务未启用"); } return ossConfig; } } ``` -------------------------------- ### Configure RemoteSocialVo for Login Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/domain-objects.md Sets up social login metadata and retrieves user information based on the platform OpenID. ```java RemoteSocialVo wechat = new RemoteSocialVo(); wechat.setSocialName("weixin"); wechat.setUserOpenid("oZLe40..."); wechat.setClientId("wx123456789"); // Login with WeChat LoginUser user = remoteUserService.getUserInfoByOpenid(wechat.getUserOpenid()); ``` -------------------------------- ### Record Login Information Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/api-reference/remote-user-service.md Logs the user's login activity including IP address. ```java String clientIp = request.getRemoteAddr(); remoteUserService.recordLoginInfo(1L, clientIp); // Updates user's last login IP and current timestamp ``` -------------------------------- ### Query Data with Multi-Tenant Scoping Source: https://github.com/dromara/ruoyi-cloud-plus/blob/6.X/_autodocs/README.md Data access is automatically filtered based on the user's data scope configuration. ```java // Data is automatically filtered by user's data scope List users = userService.queryByDept(deptId); // Respects role.dataScope configuration ```