### User API Controller for User Management (Java) Source: https://context7.com/power4j/fckit-v3/llms.txt A Spring Boot REST controller for managing user data. It handles GET and POST requests for users, retrieving tenant information from gateway headers and enforcing permissions. ```java @RestController @RequestMapping("/api/users") public class UserController { @GetMapping("/{id}") public ResponseEntity getUser(@PathVariable Long id) { // X-User-Id and X-Tenant-Id available from gateway String userId = request.getHeader("X-User-Id"); String tenantId = request.getHeader("X-Tenant-Id"); // Load user with tenant isolation return ResponseEntity.ok(userService.getUser(id, tenantId)); } @PostMapping public ResponseEntity createUser(@RequestBody User user) { // Requires USER_WRITE permission return ResponseEntity.ok(userService.createUser(user)); } } ``` -------------------------------- ### Configure Redis Queue Writer with Redisson in Java Source: https://context7.com/power4j/fckit-v3/llms.txt Configures the QueueWriter bean using RedissonClient for blocking queue operations. It utilizes a DefaultNameGenerator for queue naming conventions. This setup is essential for enabling distributed task queues. ```java import org.redisson.api.RedissonClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class QueueConfig { @Bean public QueueWriter queueWriter(RedissonClient redissonClient) { return new BlockQueueWriter(redissonClient, new DefaultNameGenerator()); } } ``` -------------------------------- ### GET /api/users/{id} Source: https://context7.com/power4j/fckit-v3/llms.txt Retrieves a specific user by their ID. The request is authenticated and tenant-isolated via gateway headers. ```APIDOC ## GET /api/users/{id} ### Description Retrieves a specific user by their ID. The request is authenticated and tenant-isolated via gateway headers (X-User-Id and X-Tenant-Id). ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (Long) - Required - The unique identifier of the user to retrieve. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **User** (Object) - The user object containing user details. #### Response Example ```json { "id": 1, "username": "john_doe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Product Management API Source: https://context7.com/power4j/fckit-v3/llms.txt APIs for managing products, including retrieval, creation, search, and deletion. ```APIDOC ## GET /api/products/{id} ### Description Retrieves a product by its unique identifier. ### Method GET ### Endpoint /api/products/{id} ### Parameters #### Path Parameters - **id** (Long) - Required - The unique identifier of the product. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **Product** (Product) - Details of the found product. #### Response Example ```json { "id": 12345, "name": "Wireless Mouse", "description": "Ergonomic wireless mouse" } ``` ## POST /api/products ### Description Creates a new product. ### Method POST ### Endpoint /api/products ### Parameters #### Request Body - **request** (ProductRequest) - Required - The details of the product to create. - **name** (String) - Required - The name of the product. - **description** (String) - Optional - The description of the product. ### Request Example ```json { "name": "Wireless Keyboard", "description": "Mechanical wireless keyboard" } ``` ### Response #### Success Response (201) - **Product** (Product) - The newly created product details. #### Response Example ```json { "id": 67890, "name": "Wireless Keyboard", "description": "Mechanical wireless keyboard" } ``` ## GET /api/products/search ### Description Searches for products based on provided criteria. ### Method GET ### Endpoint /api/products/search ### Parameters #### Query Parameters - **keyword** (String) - Optional - A keyword to search for in product names or descriptions. - **category** (String) - Optional - The category to filter products by. - **page** (int) - Optional - The page number for pagination (defaults to 0). - **size** (int) - Optional - The number of items per page (defaults to 20). ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **PagedModel** (PagedModel) - A paged model containing the search results. #### Response Example ```json { "content": [ { "id": 12345, "name": "Wireless Mouse", "description": "Ergonomic wireless mouse" } ], "pageable": { "pageNumber": 0, "pageSize": 20 }, "totalElements": 1 } ``` ## DELETE /api/products/{id} ### Description Soft deletes a product by its identifier. ### Method DELETE ### Endpoint /api/products/{id} ### Parameters #### Path Parameters - **id** (Long) - Required - The unique identifier of the product to delete. ### Request Example (No request body for DELETE requests) ### Response #### Success Response (204) - No content returned on successful deletion. #### Response Example (No response body) ``` -------------------------------- ### POST /api/users Source: https://context7.com/power4j/fckit-v3/llms.txt Creates a new user. Requires the USER_WRITE permission. ```APIDOC ## POST /api/users ### Description Creates a new user. This operation requires the USER_WRITE permission. ### Method POST ### Endpoint /api/users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **user** (User) - Required - The user object containing details for the new user. ### Request Example ```json { "username": "jane_doe", "email": "jane.doe@example.com" } ``` ### Response #### Success Response (200) - **User** (Object) - The newly created user object. #### Response Example ```json { "id": 2, "username": "jane_doe", "email": "jane.doe@example.com" } ``` ``` -------------------------------- ### Product Creation Request Model - Java Source: https://context7.com/power4j/fckit-v3/llms.txt Represents the data model for creating a new product request. It includes required fields such as name, price, and category, along with optional fields like description and stock quantity. Annotations like @NotBlank, @NotNull, @DecimalMin, and @Min are used for validation. ```java @Schema(description = "Product creation request") @Data public class ProductRequest { @NotBlank @Schema(required = true) private String name; private String description; @NotNull @DecimalMin("0.0") @Schema(required = true) private BigDecimal price; @NotBlank @Schema(required = true) private String category; @Min(0) private Integer stockQuantity; } ``` -------------------------------- ### Configure Redisson Client and Topic Publisher Source: https://context7.com/power4j/fckit-v3/llms.txt Sets up the Redisson client for connecting to Redis and configures the TopicPublisher bean. It requires Redis to be running and accessible at the specified address with the provided password. ```java import org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.config.Config; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @EnableConfigurationProperties(TopicProperties.class) public class MessagingConfig { @Bean public RedissonClient redissonClient() { Config config = new Config(); config.useSingleServer() .setAddress("redis://localhost:6379") .setPassword("redis-password") .setDatabase(0); return Redisson.create(config); } @Bean public TopicPublisher topicPublisher(RedissonClient redissonClient) { return new DefaultTopicPublisher(redissonClient, new DefaultNameGenerator()); } } ``` -------------------------------- ### Dispatch Tasks and Notifications using QueueWriter in Java Source: https://context7.com/power4j/fckit-v3/llms.txt Provides services to schedule individual tasks and bulk tasks to a Redis queue using the QueueWriter. It also includes functionality to send notifications to a dedicated queue. Error handling for full queues and task scheduling logic are demonstrated. ```java import org.springframework.stereotype.Service; import lombok.RequiredArgsConstructor; import java.util.UUID; import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.io.Serializable; import lombok.Data; import lombok.Builder; // Assuming Task and Notification classes are defined as below: @Data public class Task implements Serializable { private String taskId; private String taskType; private String status; private Map parameters; private LocalDateTime createdAt; } @Data @Builder public class Notification implements Serializable { private String recipient; private String message; private String channel; private Long timestamp; } @Service @RequiredArgsConstructor public class TaskDispatcherService { private final QueueWriter queueWriter; public boolean scheduleTask(Task task) { task.setTaskId(UUID.randomUUID().toString()); task.setCreatedAt(LocalDateTime.now()); task.setStatus("PENDING"); boolean success = queueWriter.write("task:processing", task); if (!success) { System.err.println("Queue is full, task rejected: " + task.getTaskId()); return false; } System.out.println("Task queued: " + task.getTaskId()); return true; } public void bulkScheduleTasks(List tasks) { for (Task task : tasks) { boolean queued = scheduleTask(task); if (!queued) { // Handle queue full scenario - retry or store for later System.err.println("Failed to queue task, retrying..."); } } } public void sendNotification(String recipient, String message) { Notification notification = Notification.builder() .recipient(recipient) .message(message) .channel("EMAIL") .timestamp(System.currentTimeMillis()) .build(); queueWriter.write("notification:queue", notification); } } ``` -------------------------------- ### Authentication API Source: https://context7.com/power4j/fckit-v3/llms.txt Details on how to authenticate with the API using JWT. ```APIDOC ## Authentication ### Description This API uses JWT (JSON Web Token) for authentication. Include the token in the `Authorization` header as a Bearer token. ### Method N/A (Applies to all endpoints requiring authentication) ### Endpoint N/A ### Parameters #### Request Headers - **Authorization** (String) - Required - The JWT token in the format `Bearer `. ### Request Example ``` Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ``` ### Response #### Error Response (401) - **Unauthorized** - Returned if the token is missing or invalid. ``` -------------------------------- ### Product Data Model - Java Source: https://context7.com/power4j/fckit-v3/llms.txt Defines the data structure for a product, including fields like name, description, price, category, stock quantity, and creation timestamp. It utilizes annotations from the Schema and DecimalMin libraries for validation and documentation. ```java public class Product { private String description; @Schema(description = "Price in USD", example = "29.99", minimum = "0") @DecimalMin("0.0") private BigDecimal price; @Schema(description = "Product category", example = "Electronics") private String category; @Schema(description = "Stock quantity", example = "100") private Integer stockQuantity; @Schema(description = "Creation timestamp") private LocalDateTime createdAt; } ``` -------------------------------- ### Publish Events using TopicPublisher Source: https://context7.com/power4j/fckit-v3/llms.txt Demonstrates how to publish messages to Redis channels using the TopicPublisher service. This is typically done within business logic services to notify other parts of the system about state changes, such as order creation or completion. ```java import com.fckit.messaging.TopicPublisher; import com.fckit.model.OrderEvent; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.UUID; @Service @RequiredArgsConstructor public class OrderService { private final TopicPublisher topicPublisher; public void createOrder(OrderRequest request) { // Create order logic Order order = new Order(); order.setOrderId(UUID.randomUUID().toString()); order.setCustomerId(request.getCustomerId()); order.setTotalAmount(request.getAmount()); // Publish order created event OrderEvent event = OrderEvent.builder() .orderId(order.getOrderId()) .eventType("ORDER_CREATED") .timestamp(System.currentTimeMillis()) .payload(order) .build(); topicPublisher.publish("order:events", event); // Publish user notification String notification = String.format( "Order %s has been created successfully", order.getOrderId() ); topicPublisher.publish("user:notifications", notification); } public void completeOrder(String orderId) { // Complete order logic OrderEvent event = OrderEvent.builder() .orderId(orderId) .eventType("ORDER_COMPLETED") .timestamp(System.currentTimeMillis()) .build(); topicPublisher.publish("order:events", event); } } ``` -------------------------------- ### Document Product Management API Endpoints with Springdoc Annotations Source: https://context7.com/power4j/fckit-v3/llms.txt This Java code defines a REST controller for product management, using Springdoc annotations to document CRUD operations. It includes details on parameters, request bodies, responses, and security requirements for each endpoint. ```java // Controller with API documentation @RestController @RequestMapping("/api/products") @Tag(name = "Product Management", description = "Product CRUD operations") public class ProductController { @Operation( summary = "Get product by ID", description = "Retrieves a product by its unique identifier" ) @ApiResponses({ @ApiResponse(responseCode = "200", description = "Product found", content = @Content(schema = @Schema(implementation = Product.class))), @ApiResponse(responseCode = "404", description = "Product not found"), @ApiResponse(responseCode = "401", description = "Unauthorized") }) @GetMapping("/{id}") @ApiTrait(internal = false, authenticated = true) public ResponseEntity getProduct( @Parameter(description = "Product ID", required = true) @PathVariable Long id) { return ResponseEntity.ok(productService.findById(id)); } @Operation(summary = "Create new product") @ApiResponses({ @ApiResponse(responseCode = "201", description = "Product created"), @ApiResponse(responseCode = "400", description = "Invalid input") }) @PostMapping @ApiTrait(internal = false, authenticated = true, requiredPermission = "PRODUCT_CREATE") public ResponseEntity createProduct( @RequestBody @Valid ProductRequest request) { Product created = productService.create(request); return ResponseEntity.status(HttpStatus.CREATED).body(created); } @Operation(summary = "Search products") @GetMapping("/search") public ResponseEntity> searchProducts( @Parameter(description = "Search keyword") @RequestParam(required = false) String keyword, @Parameter(description = "Category filter") @RequestParam(required = false) String category, @Parameter(description = "Page number", example = "0") @RequestParam(defaultValue = "0") int page, @Parameter(description = "Page size", example = "20") @RequestParam(defaultValue = "20") int size) { Pageable pageable = Pageable.of(page, size); Paged results = productService.search(keyword, category, pageable); return ResponseEntity.ok(toPagedModel(results)); } @Operation(summary = "Delete product", description = "Soft delete a product") @DeleteMapping("/{id}") @ApiTrait(internal = true, authenticated = true) public ResponseEntity deleteProduct(@PathVariable Long id) { productService.delete(id); return ResponseEntity.noContent().build(); } } ``` -------------------------------- ### Define Product Schema with Springdoc Annotations Source: https://context7.com/power4j/fckit-v3/llms.txt This Java code defines a 'Product' data model using Lombok's '@Data' annotation and Springdoc's '@Schema' annotation for API documentation. It specifies fields like ID, name, and description, with validation constraints. ```java // API models with documentation @Schema(description = "Product information") @Data public class Product { @Schema(description = "Product unique identifier", example = "12345") private Long id; @Schema(description = "Product name", example = "Wireless Mouse", required = true) @NotBlank private String name; @Schema(description = "Product description") ``` -------------------------------- ### Configure OAuth2 Authorization Server and Custom Claims (Java) Source: https://context7.com/power4j/fckit-v3/llms.txt Sets up the OAuth2 Authorization Server with custom JWT claims for user properties like username and authorities. It also includes a custom authentication failure handler and a scoped user details service. ```java // Enable OAuth2 Authorization Server @Configuration @Oauth2AuthorizationServer public class SecurityConfig { // Custom user properties exporter for JWT claims @Bean public OauthUserPropExporter userInfoExporter() { return (authentication, tokenType) -> { Map claims = new HashMap<>(); if (authentication.getPrincipal() instanceof UserDetails) { UserDetails user = (UserDetails) authentication.getPrincipal(); claims.put("username", user.getUsername()); claims.put("authorities", user.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.toList())); claims.put("tenant_id", "tenant_001"); } return claims; }; } // Custom authentication failure handler @Bean public AuthenticationFailureHandler authFailureHandler() { return (request, response, exception) -> { response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); Map error = Map.of( "error", "authentication_failed", "message", exception.getMessage(), "timestamp", System.currentTimeMillis() ); ObjectMapper mapper = new ObjectMapper(); response.getWriter().write(mapper.writeValueAsString(error)); }; } // Custom user details service with scope support @Bean public ScopedUserDetailsService userDetailsService() { return new ScopedUserDetailsService() { @Override public UserDetails loadUserByUsername(String username) { // Load user from database return User.builder() .username(username) .password("{bcrypt}$2a$10$...") .authorities("ROLE_USER", "ROLE_ADMIN") .build(); } @Override public UserDetails loadUserByUsername(String username, String scope) { // Load user with specific scope validation return loadUserByUsername(username); } }; } } ``` -------------------------------- ### Service Demonstrating AuditEntity Features in Java Source: https://context7.com/power4j/fckit-v3/llms.txt This Java service class demonstrates the usage of the AuditEntity base class and its associated audit features. It shows how to save, update, and check data classification markers for entities, along with accessing the auto-populated audit fields (createBy, createAt, updateBy, updateAt). This requires MyBatis-Plus and Spring Data repositories. ```java // Service demonstrating audit features @Service @RequiredArgsConstructor public class DepartmentService { private final BaseRepository, Department, Long> deptRepository; public void auditEntityDemo() { Department dept = new Department(); dept.setDeptName("Engineering"); dept.markSysAttr(); // Mark as system data (lowAttr = 1) // On insert: createBy, createAt, updateBy, updateAt auto-filled Department saved = deptRepository.saveOne(dept); assert saved.getCreateBy() != null; assert saved.getCreateAt() != null; // On update: updateBy and updateAt auto-updated saved.setDeptName("Engineering Department"); deptRepository.updateOneById(saved); // Check data classification if (saved.checkSysAttr()) { System.out.println("System data - restricted operations"); } // Mark as user data dept.markUserAttr(); // lowAttr = 0 if (dept.checkUserAttr()) { System.out.println("User data - normal operations"); } // Access audit fields System.out.println("Created by: " + saved.getCreateBy()); System.out.println("Created at: " + saved.getCreateAt()); System.out.println("Last updated by: " + saved.getUpdateBy()); System.out.println("Last updated at: " + saved.getUpdateAt()); } } ``` -------------------------------- ### Gateway Security Configuration with Custom Handlers Source: https://context7.com/power4j/fckit-v3/llms.txt Configures security properties for the gateway, including public and internal paths, and defines custom handlers for access denied and access permitted scenarios. The access denied handler returns a 403 Forbidden with JSON payload, while the access permitted handler adds custom headers like X-User-Id and X-Tenant-Id. ```java // Gateway route guard configuration @Configuration @EnableRouteGuard public class GatewaySecurityConfig { @Bean public GatewaySecurityProperties securityProperties() { GatewaySecurityProperties props = new GatewaySecurityProperties(); props.setSafeMode(false); props.setEnableIpWhitelist(true); props.setPublicPaths(Arrays.asList("/public/**", "/health", "/actuator/**")); props.setInternalPaths(Arrays.asList("/internal/**")); return props; } @Bean public AccessDeniedHandler accessDeniedHandler() { return new DefaultAccessDeniedHandler() { @Override public Mono handleAccessDenied( ServerWebExchange exchange, AuthProblem problem) { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.FORBIDDEN); response.getHeaders().setContentType(MediaType.APPLICATION_JSON); Map body = Map.of( "code", problem.getCode(), "message", problem.description(), "path", exchange.getRequest().getPath().value(), "timestamp", System.currentTimeMillis() ); DataBuffer buffer = response.bufferFactory() .wrap(new ObjectMapper().writeValueAsBytes(body)); return response.writeWith(Mono.just(buffer)); } }; } @Bean public AccessPermittedHandler accessPermittedHandler() { return new DefaultAccessPermittedHandler() { @Override public Mono handleAccessPermitted(AuthContext context) { // Add custom headers for downstream services ServerHttpRequest request = context.getExchange().getRequest() .mutate() .header("X-User-Id", context.getAuthState().getUserId()) .header("X-Tenant-Id", context.getAuthState().getTenantId()) .header("X-Request-Id", UUID.randomUUID().toString()) .build(); return Mono.just(context.getExchange().mutate() .request(request).build()); } }; } } ``` -------------------------------- ### Gateway Route Configuration with Filters Source: https://context7.com/power4j/fckit-v3/llms.txt Defines custom routes for the Spring Cloud Gateway. This configuration uses RouteLocatorBuilder to define routes for 'user-service' and 'order-service', applying filters like stripPrefix and adding request headers. ```java // Gateway route configuration with filters @Configuration public class RouteConfiguration { @Bean public RouteLocator customRoutes(RouteLocatorBuilder builder) { return builder.routes() .route("user-service", r -> r .path("/api/users/**") .filters(f -> f .stripPrefix(1) .addRequestHeader("X-Service", "user-service")) .uri("lb://user-service")) .route("order-service", r -> r .path("/api/orders/**") .filters(f -> f.stripPrefix(1)) ``` -------------------------------- ### Custom Permission Definition Service Source: https://context7.com/power4j/fckit-v3/llms.txt Defines API permissions by loading them from a database or configuration. This service extends AbstractPermissionDefinitionService and defines permissions like USER_READ, USER_WRITE, and ADMIN_ONLY with specific paths, HTTP methods, and resource levels. ```java // Custom permission definition service @Service public class CustomPermissionService extends AbstractPermissionDefinitionService { @Override protected List doLoadPermissions() { // Load from database or configuration List permissions = new ArrayList<>(); permissions.add(ApiPermDefinition.builder() .code("USER_READ") .name("Read User") .path("/api/users/**") .method("GET") .resourceLevel(ResourceLevel.PROTECTED) .build()); permissions.add(ApiPermDefinition.builder() .code("USER_WRITE") .name("Write User") .path("/api/users/**") .method("POST,PUT,DELETE") .resourceLevel(ResourceLevel.PROTECTED) .build()); permissions.add(ApiPermDefinition.builder() .code("ADMIN_ONLY") .name("Admin Operations") .path("/api/admin/**") .method("*") .resourceLevel(ResourceLevel.PROTECTED) .requiredRole("ADMIN") .build()); return permissions; } } ``` -------------------------------- ### Spring Cloud Gateway Routing Configuration Source: https://context7.com/power4j/fckit-v3/llms.txt Configures routes for microservices like order-service and public-service using Spring Cloud Gateway. It defines path-based routing and load balancing to different services. ```java .uri("lb://order-service")) .route("public-api", r -> r .path("/public/**") .filters(f -> f.stripPrefix(1)) .uri("lb://public-service")) .build(); } } ``` -------------------------------- ### Configure OpenAPI 3.0 with JWT Security for Spring Boot Source: https://context7.com/power4j/fckit-v3/llms.txt This Java code configures OpenAPI 3.0 documentation generation for a Spring Boot application. It defines API information, servers, and JWT bearer token security schemes. It also groups API endpoints into 'public' and 'admin' categories. ```java // Enable SpringDoc with custom configuration @Configuration public class ApiDocConfig { @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .info(new Info() .title("Fist Kit API Documentation") .version("3.10.1") .description("Enterprise Spring Boot Application API") .contact(new Contact() .name("Development Team") .email("dev@example.com')) .license(new License() .name("LGPL 3.0") .url("https://www.gnu.org/licenses/lgpl-3.0.txt"))) .servers(Arrays.asList( new Server().url("https://api.example.com").description("Production"), new Server().url("https://staging-api.example.com").description("Staging"), new Server().url("http://localhost:8080").description("Local"))) .addSecurityItem(new SecurityRequirement().addList("bearer-jwt")) .components(new Components() .addSecuritySchemes("bearer-jwt", new SecurityScheme() .type(SecurityScheme.Type.HTTP) .scheme("bearer") .bearerFormat("JWT") .description("JWT token authentication"))); } @Bean public GroupedOpenApi publicApi() { return GroupedOpenApi.builder() .group("public") .pathsToMatch("/api/public/**") .build(); } @Bean public GroupedOpenApi adminApi() { return GroupedOpenApi.builder() .group("admin") .pathsToMatch("/api/admin/**") .build(); } } ``` -------------------------------- ### Generic CRUD Operations with BaseRepository in Java Source: https://context7.com/power4j/fckit-v3/llms.txt The BaseRepository class extends MyBatis-Plus CrudRepository to offer a comprehensive set of CRUD operations, including advanced querying, pagination, and optimistic locking. It leverages MyBatis-Plus for ORM and provides fluent APIs for common database interactions. ```java import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.Version; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.fkit.common.audit.AuditEntity; import com.fkit.common.base.BaseRepository; import com.fkit.common.base.Pageable; import com.fkit.common.base.Paged; import com.fkit.common.base.Sort; import com.fkit.common.base.lambda.Eq; import lombok.Getter; import lombok.Setter; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.Arrays; import java.util.List; import java.util.Optional; // Entity class with audit fields @Getter @Setter @TableName("sys_user") public class User extends AuditEntity { @TableId(type = IdType.AUTO) private Long id; @TableField("username") private String username; @TableField("email") private String email; @TableField("status") private String status; @Version @TableField("version") private Integer version; public void markUserAttr() { // Placeholder for audit field population } } // MyBatis Mapper interface @Mapper public interface UserMapper extends BaseMapper { } // Repository implementation @Repository public class UserRepository extends BaseRepository { // Find active users with lambda query public List findActiveUsers() { return querying() .eq(User::getStatus, "ACTIVE") .orderByDesc(User::getCreateAt) .list(); } // Count users by email excluding specific ID public long countByEmail(String email, Long excludeId) { return lambdaCount(new Eq<>(User::getEmail, email), excludeId); } } // Service usage example @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public void demonstrateRepositoryOperations() { // Save single entity - audit fields auto-populated User newUser = new User(); newUser.setUsername("john_doe"); newUser.setEmail("john@example.com"); newUser.setStatus("ACTIVE"); newUser.markUserAttr(); User saved = userRepository.saveOne(newUser); // Find by ID with Optional Optional found = userRepository.findOneById(saved.getId()); // Paginated query Pageable pageable = Pageable.of(0, 10, Sort.by("createAt", Sort.Direction.DESC)); Paged page = userRepository.findAll(pageable); System.out.println("Total: " + page.getTotalElements()); // Advanced lambda query List activeUsers = userRepository.querying() .eq(User::getStatus, "ACTIVE") .like(User::getUsername, "john") .between(User::getCreateAt, LocalDateTime.now().minusDays(7), LocalDateTime.now()) .list(); // Optimistic locking update User userToUpdate = found.get(); userRepository.fetchVersion(userToUpdate, true); // Load current version userToUpdate.setEmail("newemail@example.com"); userRepository.updateOneById(userToUpdate); // Version checked automatically // Batch operations List users = Arrays.asList(newUser, new User(), new User()); userRepository.saveAll(users, 100); // Batch size 100 // Custom wrapper query QueryWrapper wrapper = new QueryWrapper<>(); wrapper.eq("status", "ACTIVE") .orderByDesc("create_at"); List results = userRepository.findAllBy(wrapper); // Delete operations userRepository.deleteOneById(saved.getId()); userRepository.deleteAllById(Arrays.asList(1L, 2L, 3L)); } } ``` -------------------------------- ### OAuth2 Client Requests for Different Grant Types (Java) Source: https://context7.com/power4j/fckit-v3/llms.txt Demonstrates how to make client requests to an OAuth2 Authorization Server for password, SMS, and refresh token grant types using Spring RestTemplate. Requires client credentials and appropriate grant type parameters. ```java // OAuth2 client usage examples @RestController @RequestMapping("/api/auth") public class AuthController { // Password grant request public void passwordGrantExample() throws Exception { String tokenUrl = "http://localhost:8080/oauth2/token"; RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.setBasicAuth("client-id", "client-secret"); MultiValueMap params = new LinkedMultiValueMap<>(); params.add("grant_type", "password"); params.add("username", "john_doe"); params.add("password", "secret123"); params.add("scope", "read write"); HttpEntity> request = new HttpEntity<>(params, headers); ResponseEntity response = restTemplate.postForEntity( tokenUrl, request, Map.class); String accessToken = (String) response.getBody().get("access_token"); String refreshToken = (String) response.getBody().get("refresh_token"); } // SMS grant request public void smsGrantExample() throws Exception { MultiValueMap params = new LinkedMultiValueMap<>(); params.add("grant_type", "sms"); params.add("mobile", "+1234567890"); params.add("sms_code", "123456"); params.add("scope", "read"); // Similar to password grant... } // Refresh token request public void refreshTokenExample() throws Exception { MultiValueMap params = new LinkedMultiValueMap<>(); params.add("grant_type", "refresh_token"); params.add("refresh_token", "existing-refresh-token"); // Similar to password grant... } } ``` -------------------------------- ### Configure MyBatis-Plus Audit Field Auto-fill in Java Source: https://context7.com/power4j/fckit-v3/llms.txt This Java configuration sets up the AuditInfoSupplier to retrieve user IDs from the security context and the AuditFiller to automatically populate audit fields during MyBatis-Plus operations. It requires Spring Boot and MyBatis-Plus dependencies. ```java // Configure audit field auto-fill @Configuration public class MybatisConfig { @Bean public AuditInfoSupplier auditInfoSupplier() { return new AuditInfoSupplier() { @Override public Long getUserId() { // Get from SecurityContext or request context Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null && auth.getPrincipal() instanceof UserDetails) { return Long.parseLong(auth.getName()); } return null; } }; } @Bean public AuditFiller auditFiller(AuditInfoSupplier supplier) { return new AuditFiller(supplier); } } ``` -------------------------------- ### Define Task Model for Redis Queues in Java Source: https://context7.com/power4j/fckit-v3/llms.txt Defines the Task data model used for messages in the Redis queue. It includes fields for task identification, type, status, parameters, and creation timestamp, ensuring serializability for inter-process communication. ```java import java.io.Serializable; import java.time.LocalDateTime; import java.util.Map; import lombok.Data; @Data public class Task implements Serializable { private String taskId; private String taskType; private String status; private Map parameters; private LocalDateTime createdAt; } ``` -------------------------------- ### User Permission Resolver Service Source: https://context7.com/power4j/fckit-v3/llms.txt Resolves user permissions by loading them from a database. This component returns a set of permission strings for a given user ID. It includes logic to grant all permissions to 'admin' users. ```java // Custom user permission resolver @Component public class UserPermissionResolver { public Mono> resolveUserPermissions(String userId) { // Load user permissions from database return Mono.fromCallable(() -> { Set permissions = new HashSet<>(); permissions.add("USER_READ"); permissions.add("USER_WRITE"); // Admin users get all permissions if ("admin".equals(userId)) { permissions.add("ADMIN_ONLY"); } return permissions; }); } } ``` -------------------------------- ### Handle Redis Topic Messages with @TopicListener Source: https://context7.com/power4j/fckit-v3/llms.txt Defines event listeners that subscribe to specific Redis channels. It uses the @TopicListener annotation to specify the channel and codec for message deserialization. These listeners process incoming messages, such as order events or user notifications. ```java import com.fckit.messaging.TopicListener; import com.fckit.messaging.TopicMessage; import com.fckit.messaging.codecs.JsonJacksonCodec; import com.fckit.model.OrderEvent; import org.springframework.stereotype.Component; @Component public class OrderEventListener { @TopicListener(channel = "order:events", codec = JsonJacksonCodec.class) public void handleOrderEvent(TopicMessage message) { OrderEvent event = message.getData(); System.out.println("Received order event: " + event.getOrderId()); System.out.println("Event type: " + event.getEventType()); // Process event if ("ORDER_CREATED".equals(event.getEventType())) { // Handle order creation } else if ("ORDER_COMPLETED".equals(event.getEventType())) { // Handle order completion } } @TopicListener(channel = "user:notifications") public void handleUserNotification(TopicMessage message) { String notification = message.getData(); System.out.println("User notification: " + notification); } } ``` -------------------------------- ### Define Notification Model for Redis Queues in Java Source: https://context7.com/power4j/fckit-v3/llms.txt Defines the Notification data model for messages sent to the notification queue. It includes recipient, message content, channel, and timestamp, designed for serialization and reliable delivery across distributed systems. ```java import java.io.Serializable; import lombok.Data; import lombok.Builder; @Data @Builder public class Notification implements Serializable { private String recipient; private String message; private String channel; private Long timestamp; } ``` -------------------------------- ### Define Order Event Model Source: https://context7.com/power4j/fckit-v3/llms.txt Defines the data structure for order-related events. This model is used for serializing and deserializing event payloads when publishing and subscribing to topics. It includes fields for order ID, event type, timestamp, and a generic payload. ```java import lombok.Builder; import lombok.Data; import java.io.Serializable; @Data @Builder public class OrderEvent implements Serializable { private String orderId; private String eventType; private Long timestamp; private Object payload; } ``` -------------------------------- ### Process Tasks from Redis Queue with Java Source: https://context7.com/power4j/fckit-v3/llms.txt Implements a task consumer using the @QueueConsumer annotation to process messages from a 'task:processing' Redis queue. It supports multiple threads and JSON message decoding. The processor handles different task types like EMAIL, REPORT, and EXPORT, including basic error handling. ```java import org.springframework.stereotype.Component; import com.power4j.fckit.queue.annotation.QueueConsumer; import com.power4j.fckit.queue.codec.JsonJacksonCodec; import java.util.UUID; import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.io.Serializable; import lombok.Data; import lombok.Builder; // Assuming Task and Notification classes are defined as below: @Data public class Task implements Serializable { private String taskId; private String taskType; private String status; private Map parameters; private LocalDateTime createdAt; } @Data @Builder public class Notification implements Serializable { private String recipient; private String message; private String channel; private Long timestamp; } @Component public class TaskProcessor { @QueueConsumer( channel = "task:processing", threads = 5, codec = JsonJacksonCodec.class ) public void processTask(Task task) { System.out.println("Processing task: " + task.getTaskId()); try { // Simulate task processing Thread.sleep(1000); // Execute task logic switch (task.getTaskType()) { case "EMAIL": sendEmail(task); break; case "REPORT": generateReport(task); break; case "EXPORT": exportData(task); break; } System.out.println("Task completed: " + task.getTaskId()); } catch (Exception e) { System.err.println("Task failed: " + task.getTaskId()); throw new RuntimeException("Task processing failed", e); } } @QueueConsumer(channel = "notification:queue", threads = 3) public void processNotification(Notification notification) { // Send notification via email/SMS/push System.out.println("Sending notification to: " + notification.getRecipient()); } private void sendEmail(Task task) { // Email sending logic } private void generateReport(Task task) { // Report generation logic } private void exportData(Task task) { // Data export logic } } ``` -------------------------------- ### Entity with AuditEntity and MyBatis-Plus Annotations in Java Source: https://context7.com/power4j/fckit-v3/llms.txt This Java code defines a Department entity that extends AuditEntity, inheriting automatic audit field population. It uses MyBatis-Plus annotations (@TableName, @TableId, @TableField) to map the entity to the database and specify field fill strategies for auditing and data classification. ```java // Entity inheriting audit capabilities @Getter @Setter @TableName("sys_department") public class Department extends AuditEntity { @TableId(type = IdType.AUTO) private Long id; @TableField("dept_name") private String deptName; @TableField(value = "del_flag", fill = FieldFill.INSERT) private Integer delFlag; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.