From 676555db2406a73ee5ff6b2889fdfaae081ef699 Mon Sep 17 00:00:00 2001 From: Raja Kolli Date: Thu, 5 Oct 2023 13:45:38 +0000 Subject: [PATCH] #876 - preparation for upgrading to Java 21 we need to change to spotless 1.17.0 to work with java 21 --- batch-boot-jpa-sample/pom.xml | 7 +- .../config/ApplicationProperties.java | 3 +- .../bootbatchjpa/config/BatchConfig.java | 37 ++-- .../config/GlobalExceptionHandler.java | 28 +-- .../bootbatchjpa/config/Initializer.java | 10 +- .../bootbatchjpa/config/SwaggerConfig.java | 4 +- .../config/logging/LoggingAspect.java | 12 +- .../services/CustomerService.java | 10 +- .../web/controllers/CustomerController.java | 47 +++-- .../web/controllers/JobInvokerController.java | 12 +- .../batch/SpringBatchIntegrationTest.java | 9 +- .../common/AbstractIntegrationTest.java | 6 +- .../repository/SchemaValidationTest.java | 3 +- .../services/CustomerServiceTest.java | 6 +- .../web/controllers/CustomerControllerIT.java | 34 ++-- .../controllers/CustomerControllerTest.java | 51 +++--- boot-rest-docs-sample/pom.xml | 7 +- .../config/ApplicationProperties.java | 3 +- .../config/GlobalExceptionHandler.java | 28 +-- .../restdocs/config/SwaggerConfig.java | 4 +- .../config/logging/LoggingAspect.java | 12 +- .../restdocs/services/UserService.java | 7 +- .../web/controllers/UserController.java | 38 ++-- .../restdocs/ApplicationIntegrationTest.java | 3 +- .../common/AbstractIntegrationTest.java | 6 +- .../restdocs/services/UserServiceTest.java | 25 +-- .../web/controllers/UserControllerIT.java | 30 ++-- .../web/controllers/UserControllerTest.java | 167 +++++++++++------- boot-togglz-sample/pom.xml | 2 +- jpa/boot-data-multipledatasources/pom.xml | 2 +- r2dbc/boot-r2dbc-sample/pom.xml | 7 +- .../config/ApplicationProperties.java | 3 +- .../config/AuditingDatabaseConfig.java | 13 +- .../config/GlobalExceptionHandler.java | 28 +-- .../bootr2dbc/config/SecurityConfig.java | 50 +++--- .../config/logging/LoggingAspect.java | 12 +- .../mapper/ReactivePostCommentMapper.java | 3 +- .../ReactiveCommentsRepository.java | 3 +- .../repositories/ReactivePostRepository.java | 3 +- .../services/ReactiveCommentsService.java | 16 +- .../services/ReactivePostService.java | 23 ++- .../ReactiveCommentsController.java | 49 +++-- .../controllers/ReactivePostController.java | 77 ++++---- .../common/AbstractIntegrationTest.java | 3 +- .../services/ReactiveCommentsServiceTest.java | 77 ++++---- .../services/ReactivePostServiceTest.java | 66 ++++--- .../ReactiveCommentsControllerIT.java | 166 +++++++++-------- .../ReactiveCommentsControllerTest.java | 110 +++++++----- .../controllers/ReactivePostControllerIT.java | 80 +++++---- .../ReactivePostControllerTest.java | 39 ++-- 50 files changed, 831 insertions(+), 610 deletions(-) diff --git a/batch-boot-jpa-sample/pom.xml b/batch-boot-jpa-sample/pom.xml index cfb7ce436..b9688aa90 100644 --- a/batch-boot-jpa-sample/pom.xml +++ b/batch-boot-jpa-sample/pom.xml @@ -246,9 +246,10 @@ ${spotless.version} - - 2.30.0 - + + 1.17.0 + + diff --git a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/ApplicationProperties.java b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/ApplicationProperties.java index 38ea876e1..d4e207692 100644 --- a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/ApplicationProperties.java +++ b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/ApplicationProperties.java @@ -8,8 +8,7 @@ @ConfigurationProperties("application") public class ApplicationProperties { - @NestedConfigurationProperty - private Cors cors = new Cors(); + @NestedConfigurationProperty private Cors cors = new Cors(); @Data public static class Cors { diff --git a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/BatchConfig.java b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/BatchConfig.java index 024ef9fa2..3bd9af18f 100644 --- a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/BatchConfig.java +++ b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/BatchConfig.java @@ -35,17 +35,29 @@ Job allCustomersJob( JpaPagingItemReader jpaPagingItemReader, JobRepository jobRepository, PlatformTransactionManager transactionManager) { - Step step = new StepBuilder("all-customers-step", jobRepository) - .allowStartIfComplete(true) - .chunk(10, transactionManager) - .reader(jpaPagingItemReader) - .processor(customer -> new CustomerDTO(customer.getName(), customer.getAddress(), customer.getGender())) - .writer(items -> { - log.info("Writing chunk of size {} at :{}", items.size(), LocalDateTime.now()); - items.forEach(customerDTO -> log.info("Read customer: {}", customerDTO)); - }) - .faultTolerant() - .build(); + Step step = + new StepBuilder("all-customers-step", jobRepository) + .allowStartIfComplete(true) + .chunk(10, transactionManager) + .reader(jpaPagingItemReader) + .processor( + customer -> + new CustomerDTO( + customer.getName(), + customer.getAddress(), + customer.getGender())) + .writer( + items -> { + log.info( + "Writing chunk of size {} at :{}", + items.size(), + LocalDateTime.now()); + items.forEach( + customerDTO -> + log.info("Read customer: {}", customerDTO)); + }) + .faultTolerant() + .build(); return new JobBuilder("all-customers-job", jobRepository) .start(step) @@ -66,7 +78,8 @@ JpaPagingItemReader jpaPagingItemReader( return new JpaPagingItemReaderBuilder() .name("jpaPagingItemReader") .entityManagerFactory(entityManagerFactory) - .queryString("SELECT c FROM Customer c WHERE c.id BETWEEN :minId AND :maxId ORDER BY c.id") + .queryString( + "SELECT c FROM Customer c WHERE c.id BETWEEN :minId AND :maxId ORDER BY c.id") .parameterValues(parameterValuesMap) .pageSize(10) .build(); diff --git a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/GlobalExceptionHandler.java b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/GlobalExceptionHandler.java index 2a767d515..f76e9998f 100644 --- a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/GlobalExceptionHandler.java +++ b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/GlobalExceptionHandler.java @@ -19,19 +19,23 @@ public class GlobalExceptionHandler { @ResponseStatus(HttpStatus.BAD_REQUEST) ProblemDetail onException(MethodArgumentNotValidException methodArgumentNotValidException) { ProblemDetail problemDetail = - ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(400), "Invalid request content."); + ProblemDetail.forStatusAndDetail( + HttpStatusCode.valueOf(400), "Invalid request content."); problemDetail.setTitle("Constraint Violation"); - List validationErrorsList = methodArgumentNotValidException.getAllErrors().stream() - .map(objectError -> { - FieldError fieldError = (FieldError) objectError; - return new ApiValidationError( - fieldError.getObjectName(), - fieldError.getField(), - fieldError.getRejectedValue(), - Objects.requireNonNull(fieldError.getDefaultMessage(), "")); - }) - .sorted(Comparator.comparing(ApiValidationError::field)) - .toList(); + List validationErrorsList = + methodArgumentNotValidException.getAllErrors().stream() + .map( + objectError -> { + FieldError fieldError = (FieldError) objectError; + return new ApiValidationError( + fieldError.getObjectName(), + fieldError.getField(), + fieldError.getRejectedValue(), + Objects.requireNonNull( + fieldError.getDefaultMessage(), "")); + }) + .sorted(Comparator.comparing(ApiValidationError::field)) + .toList(); problemDetail.setProperty("violations", validationErrorsList); return problemDetail; } diff --git a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/Initializer.java b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/Initializer.java index 1f98431e3..a481a6dde 100644 --- a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/Initializer.java +++ b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/Initializer.java @@ -21,10 +21,12 @@ public class Initializer implements CommandLineRunner { @Override public void run(String... args) { log.info("Running Initializer....."); - List customerList = Instancio.ofList(Customer.class) - .size(1000) - .generate(field(Customer.class, "gender"), gen -> gen.oneOf("male", "female")) - .create(); + List customerList = + Instancio.ofList(Customer.class) + .size(1000) + .generate( + field(Customer.class, "gender"), gen -> gen.oneOf("male", "female")) + .create(); log.info("Saving Customers of size :{}", customerList.size()); customerList = customerRepository.saveAll(customerList); log.info("Inserted customers of size :{}", customerList.size()); diff --git a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/SwaggerConfig.java b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/SwaggerConfig.java index 5a262a776..46dc46766 100644 --- a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/SwaggerConfig.java +++ b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/SwaggerConfig.java @@ -6,5 +6,7 @@ import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) -@OpenAPIDefinition(info = @Info(title = "batch-boot-jpa", version = "v1"), servers = @Server(url = "/")) +@OpenAPIDefinition( + info = @Info(title = "batch-boot-jpa", version = "v1"), + servers = @Server(url = "/")) public class SwaggerConfig {} diff --git a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/logging/LoggingAspect.java b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/logging/LoggingAspect.java index 197a42b17..da88e61a5 100644 --- a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/logging/LoggingAspect.java +++ b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/config/logging/LoggingAspect.java @@ -25,15 +25,17 @@ public LoggingAspect(Environment env) { this.env = env; } - @Pointcut("within(@org.springframework.stereotype.Repository *)" - + " || within(@org.springframework.stereotype.Service *)" - + " || within(@org.springframework.web.bind.annotation.RestController *)") + @Pointcut( + "within(@org.springframework.stereotype.Repository *)" + + " || within(@org.springframework.stereotype.Service *)" + + " || within(@org.springframework.web.bind.annotation.RestController *)") public void springBeanPointcut() { // pointcut definition } - @Pointcut("@within(com.example.bootbatchjpa.config.logging.Loggable) || " - + "@annotation(com.example.bootbatchjpa.config.logging.Loggable)") + @Pointcut( + "@within(com.example.bootbatchjpa.config.logging.Loggable) || " + + "@annotation(com.example.bootbatchjpa.config.logging.Loggable)") public void applicationPackagePointcut() { // pointcut definition } diff --git a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/services/CustomerService.java b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/services/CustomerService.java index 1724f38ac..bb4e067ad 100644 --- a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/services/CustomerService.java +++ b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/services/CustomerService.java @@ -22,10 +22,12 @@ public class CustomerService { private final CustomerRepository customerRepository; @Transactional(readOnly = true) - public PagedResult findAllCustomers(int pageNo, int pageSize, String sortBy, String sortDir) { - Sort sort = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name()) - ? Sort.by(sortBy).ascending() - : Sort.by(sortBy).descending(); + public PagedResult findAllCustomers( + int pageNo, int pageSize, String sortBy, String sortDir) { + Sort sort = + sortDir.equalsIgnoreCase(Sort.Direction.ASC.name()) + ? Sort.by(sortBy).ascending() + : Sort.by(sortBy).descending(); // create Pageable instance Pageable pageable = PageRequest.of(pageNo, pageSize, sort); diff --git a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/web/controllers/CustomerController.java b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/web/controllers/CustomerController.java index cbc9ad77c..dd9693cf5 100644 --- a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/web/controllers/CustomerController.java +++ b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/web/controllers/CustomerController.java @@ -28,21 +28,35 @@ public class CustomerController { @GetMapping public PagedResult getAllCustomers( - @RequestParam(value = "pageNo", defaultValue = AppConstants.DEFAULT_PAGE_NUMBER, required = false) + @RequestParam( + value = "pageNo", + defaultValue = AppConstants.DEFAULT_PAGE_NUMBER, + required = false) int pageNo, - @RequestParam(value = "pageSize", defaultValue = AppConstants.DEFAULT_PAGE_SIZE, required = false) + @RequestParam( + value = "pageSize", + defaultValue = AppConstants.DEFAULT_PAGE_SIZE, + required = false) int pageSize, - @RequestParam(value = "sortBy", defaultValue = AppConstants.DEFAULT_SORT_BY, required = false) + @RequestParam( + value = "sortBy", + defaultValue = AppConstants.DEFAULT_SORT_BY, + required = false) String sortBy, - @RequestParam(value = "sortDir", defaultValue = AppConstants.DEFAULT_SORT_DIRECTION, required = false) + @RequestParam( + value = "sortDir", + defaultValue = AppConstants.DEFAULT_SORT_DIRECTION, + required = false) String sortDir) { return customerService.findAllCustomers(pageNo, pageSize, sortBy, sortDir); } @GetMapping("/{id}") public ResponseEntity getCustomerById(@PathVariable Long id) { - return customerService.findCustomerById(id).map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound() - .build()); + return customerService + .findCustomerById(id) + .map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.notFound().build()); } @PostMapping @@ -52,13 +66,15 @@ public Customer createCustomer(@RequestBody @Validated Customer customer) { } @PutMapping("/{id}") - public ResponseEntity updateCustomer(@PathVariable Long id, @RequestBody Customer customer) { + public ResponseEntity updateCustomer( + @PathVariable Long id, @RequestBody Customer customer) { return customerService .findCustomerById(id) - .map(customerObj -> { - customer.setId(id); - return ResponseEntity.ok(customerService.saveCustomer(customer)); - }) + .map( + customerObj -> { + customer.setId(id); + return ResponseEntity.ok(customerService.saveCustomer(customer)); + }) .orElseGet(() -> ResponseEntity.notFound().build()); } @@ -66,10 +82,11 @@ public ResponseEntity updateCustomer(@PathVariable Long id, @RequestBo public ResponseEntity deleteCustomer(@PathVariable Long id) { return customerService .findCustomerById(id) - .map(customer -> { - customerService.deleteCustomerById(id); - return ResponseEntity.ok(customer); - }) + .map( + customer -> { + customerService.deleteCustomerById(id); + return ResponseEntity.ok(customer); + }) .orElseGet(() -> ResponseEntity.notFound().build()); } } diff --git a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/web/controllers/JobInvokerController.java b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/web/controllers/JobInvokerController.java index d9a13adf4..6d2ef1f73 100644 --- a/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/web/controllers/JobInvokerController.java +++ b/batch-boot-jpa-sample/src/main/java/com/example/bootbatchjpa/web/controllers/JobInvokerController.java @@ -22,12 +22,14 @@ public class JobInvokerController { private final Job allCustomersJob; @GetMapping("/run-allCustomers-job") - public String allCustomersJobHandle(@RequestParam Long minId, @RequestParam Long maxId) throws Exception { + public String allCustomersJobHandle(@RequestParam Long minId, @RequestParam Long maxId) + throws Exception { - JobParameters jobParameters = new JobParametersBuilder() - .addLong("minId", minId) - .addLong("maxId", maxId) - .toJobParameters(); + JobParameters jobParameters = + new JobParametersBuilder() + .addLong("minId", minId) + .addLong("maxId", maxId) + .toJobParameters(); JobExecution jobExecution = this.jobLauncher.run(this.allCustomersJob, jobParameters); return "Batch job has been invoked as " + jobExecution.getJobId(); diff --git a/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/batch/SpringBatchIntegrationTest.java b/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/batch/SpringBatchIntegrationTest.java index d0b0cfb91..e488cdef8 100644 --- a/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/batch/SpringBatchIntegrationTest.java +++ b/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/batch/SpringBatchIntegrationTest.java @@ -16,14 +16,11 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) class SpringBatchIntegrationTest extends AbstractIntegrationTest { - @Autowired - private JobLauncherTestUtils jobLauncherTestUtils; + @Autowired private JobLauncherTestUtils jobLauncherTestUtils; - @Autowired - private JobRepositoryTestUtils jobRepositoryTestUtils; + @Autowired private JobRepositoryTestUtils jobRepositoryTestUtils; - @Autowired - private Job jobUnderTest; + @Autowired private Job jobUnderTest; @BeforeEach void setup() { diff --git a/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/common/AbstractIntegrationTest.java b/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/common/AbstractIntegrationTest.java index 07a5c78cf..daa6a1746 100644 --- a/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/common/AbstractIntegrationTest.java +++ b/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/common/AbstractIntegrationTest.java @@ -18,9 +18,7 @@ @AutoConfigureMockMvc public abstract class AbstractIntegrationTest { - @Autowired - protected MockMvc mockMvc; + @Autowired protected MockMvc mockMvc; - @Autowired - protected ObjectMapper objectMapper; + @Autowired protected ObjectMapper objectMapper; } diff --git a/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/repository/SchemaValidationTest.java b/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/repository/SchemaValidationTest.java index 81415d0ff..107602cb2 100644 --- a/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/repository/SchemaValidationTest.java +++ b/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/repository/SchemaValidationTest.java @@ -16,8 +16,7 @@ @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) class SchemaValidationTest { - @Autowired - private DataSource dataSource; + @Autowired private DataSource dataSource; @Test void contextLoads() { diff --git a/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/services/CustomerServiceTest.java b/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/services/CustomerServiceTest.java index 66803933e..fcc57fdbf 100644 --- a/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/services/CustomerServiceTest.java +++ b/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/services/CustomerServiceTest.java @@ -25,11 +25,9 @@ @ExtendWith(MockitoExtension.class) class CustomerServiceTest { - @Mock - private CustomerRepository customerRepository; + @Mock private CustomerRepository customerRepository; - @InjectMocks - private CustomerService customerService; + @InjectMocks private CustomerService customerService; @Test void findAllCustomers() { diff --git a/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/web/controllers/CustomerControllerIT.java b/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/web/controllers/CustomerControllerIT.java index ad70dd345..60fa78645 100644 --- a/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/web/controllers/CustomerControllerIT.java +++ b/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/web/controllers/CustomerControllerIT.java @@ -24,8 +24,7 @@ class CustomerControllerIT extends AbstractIntegrationTest { - @Autowired - private CustomerRepository customerRepository; + @Autowired private CustomerRepository customerRepository; private List customerList = null; @@ -33,10 +32,12 @@ class CustomerControllerIT extends AbstractIntegrationTest { void setUp() { customerRepository.deleteAllInBatch(); - customerList = Instancio.ofList(Customer.class) - .size(3) - .generate(field(Customer.class, "gender"), gen -> gen.oneOf("male", "female")) - .create(); + customerList = + Instancio.ofList(Customer.class) + .size(3) + .generate( + field(Customer.class, "gender"), gen -> gen.oneOf("male", "female")) + .create(); customerList = customerRepository.saveAll(customerList); } @@ -72,9 +73,10 @@ void shouldFindCustomerById() throws Exception { void shouldCreateNewCustomer() throws Exception { Customer customer = Instancio.create(Customer.class); this.mockMvc - .perform(post("/api/customers") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(customer))) + .perform( + post("/api/customers") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(customer))) .andExpect(status().isCreated()) .andExpect(jsonPath("$.id", notNullValue())) .andExpect(jsonPath("$.name", is(customer.getName()))); @@ -85,9 +87,10 @@ void shouldReturn400WhenCreateNewCustomerWithoutText() throws Exception { Customer customer = new Customer(null, null, null, null); this.mockMvc - .perform(post("/api/customers") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(customer))) + .perform( + post("/api/customers") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(customer))) .andExpect(status().isBadRequest()) .andExpect(header().string("Content-Type", is("application/problem+json"))) .andExpect(jsonPath("$.type", is("about:blank"))) @@ -107,9 +110,10 @@ void shouldUpdateCustomer() throws Exception { customer.setName("Updated Customer"); this.mockMvc - .perform(put("/api/customers/{id}", customer.getId()) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(customer))) + .perform( + put("/api/customers/{id}", customer.getId()) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(customer))) .andExpect(status().isOk()) .andExpect(jsonPath("$.id", is(customer.getId()), Long.class)) .andExpect(jsonPath("$.name", is("Updated Customer"))); diff --git a/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/web/controllers/CustomerControllerTest.java b/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/web/controllers/CustomerControllerTest.java index 94f58a6c6..22cc0c9fd 100644 --- a/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/web/controllers/CustomerControllerTest.java +++ b/batch-boot-jpa-sample/src/test/java/com/example/bootbatchjpa/web/controllers/CustomerControllerTest.java @@ -37,14 +37,11 @@ @ActiveProfiles(PROFILE_TEST) class CustomerControllerTest { - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; - @MockBean - private CustomerService customerService; + @MockBean private CustomerService customerService; - @Autowired - private ObjectMapper objectMapper; + @Autowired private ObjectMapper objectMapper; private List customerList; @@ -90,18 +87,22 @@ void shouldReturn404WhenFetchingNonExistingCustomer() throws Exception { Long customerId = 1L; given(customerService.findCustomerById(customerId)).willReturn(Optional.empty()); - this.mockMvc.perform(get("/api/customers/{id}", customerId)).andExpect(status().isNotFound()); + this.mockMvc + .perform(get("/api/customers/{id}", customerId)) + .andExpect(status().isNotFound()); } @Test void shouldCreateNewCustomer() throws Exception { - given(customerService.saveCustomer(any(Customer.class))).willAnswer((invocation) -> invocation.getArgument(0)); + given(customerService.saveCustomer(any(Customer.class))) + .willAnswer((invocation) -> invocation.getArgument(0)); Customer customer = Instancio.create(Customer.class); this.mockMvc - .perform(post("/api/customers") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(customer))) + .perform( + post("/api/customers") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(customer))) .andExpect(status().isCreated()) .andExpect(jsonPath("$.id", notNullValue())) .andExpect(jsonPath("$.name", is(customer.getName()))); @@ -112,9 +113,10 @@ void shouldReturn400WhenCreateNewCustomerWithoutText() throws Exception { Customer customer = new Customer(null, null, null, null); this.mockMvc - .perform(post("/api/customers") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(customer))) + .perform( + post("/api/customers") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(customer))) .andExpect(status().isBadRequest()) .andExpect(header().string("Content-Type", is("application/problem+json"))) .andExpect(jsonPath("$.type", is("about:blank"))) @@ -135,12 +137,14 @@ void shouldUpdateCustomer() throws Exception { customer.setId(customerId); customer.setName("Updated Name"); given(customerService.findCustomerById(customerId)).willReturn(Optional.of(customer)); - given(customerService.saveCustomer(any(Customer.class))).willAnswer((invocation) -> invocation.getArgument(0)); + given(customerService.saveCustomer(any(Customer.class))) + .willAnswer((invocation) -> invocation.getArgument(0)); this.mockMvc - .perform(put("/api/customers/{id}", customer.getId()) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(customer))) + .perform( + put("/api/customers/{id}", customer.getId()) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(customer))) .andExpect(status().isOk()) .andExpect(jsonPath("$.name", is("Updated Name"))); } @@ -152,9 +156,10 @@ void shouldReturn404WhenUpdatingNonExistingCustomer() throws Exception { Customer customer = Instancio.create(Customer.class); this.mockMvc - .perform(put("/api/customers/{id}", customerId) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(customer))) + .perform( + put("/api/customers/{id}", customerId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(customer))) .andExpect(status().isNotFound()); } @@ -177,6 +182,8 @@ void shouldReturn404WhenDeletingNonExistingCustomer() throws Exception { Long customerId = 1L; given(customerService.findCustomerById(customerId)).willReturn(Optional.empty()); - this.mockMvc.perform(delete("/api/customers/{id}", customerId)).andExpect(status().isNotFound()); + this.mockMvc + .perform(delete("/api/customers/{id}", customerId)) + .andExpect(status().isNotFound()); } } diff --git a/boot-rest-docs-sample/pom.xml b/boot-rest-docs-sample/pom.xml index 29e65b7aa..2d22d5889 100644 --- a/boot-rest-docs-sample/pom.xml +++ b/boot-rest-docs-sample/pom.xml @@ -268,9 +268,10 @@ ${spotless.version} - - 2.30.0 - + + 1.17.0 + + diff --git a/boot-rest-docs-sample/src/main/java/com/example/restdocs/config/ApplicationProperties.java b/boot-rest-docs-sample/src/main/java/com/example/restdocs/config/ApplicationProperties.java index fa48369bc..b77d2a8e0 100644 --- a/boot-rest-docs-sample/src/main/java/com/example/restdocs/config/ApplicationProperties.java +++ b/boot-rest-docs-sample/src/main/java/com/example/restdocs/config/ApplicationProperties.java @@ -8,8 +8,7 @@ @ConfigurationProperties("application") public class ApplicationProperties { - @NestedConfigurationProperty - private Cors cors = new Cors(); + @NestedConfigurationProperty private Cors cors = new Cors(); @Data public static class Cors { diff --git a/boot-rest-docs-sample/src/main/java/com/example/restdocs/config/GlobalExceptionHandler.java b/boot-rest-docs-sample/src/main/java/com/example/restdocs/config/GlobalExceptionHandler.java index ffdf381fa..ede47e9cd 100644 --- a/boot-rest-docs-sample/src/main/java/com/example/restdocs/config/GlobalExceptionHandler.java +++ b/boot-rest-docs-sample/src/main/java/com/example/restdocs/config/GlobalExceptionHandler.java @@ -19,19 +19,23 @@ public class GlobalExceptionHandler { @ResponseStatus(HttpStatus.BAD_REQUEST) ProblemDetail onException(MethodArgumentNotValidException methodArgumentNotValidException) { ProblemDetail problemDetail = - ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(400), "Invalid request content."); + ProblemDetail.forStatusAndDetail( + HttpStatusCode.valueOf(400), "Invalid request content."); problemDetail.setTitle("Constraint Violation"); - List validationErrorsList = methodArgumentNotValidException.getAllErrors().stream() - .map(objectError -> { - FieldError fieldError = (FieldError) objectError; - return new ApiValidationError( - fieldError.getObjectName(), - fieldError.getField(), - fieldError.getRejectedValue(), - Objects.requireNonNull(fieldError.getDefaultMessage(), "")); - }) - .sorted(Comparator.comparing(ApiValidationError::field)) - .toList(); + List validationErrorsList = + methodArgumentNotValidException.getAllErrors().stream() + .map( + objectError -> { + FieldError fieldError = (FieldError) objectError; + return new ApiValidationError( + fieldError.getObjectName(), + fieldError.getField(), + fieldError.getRejectedValue(), + Objects.requireNonNull( + fieldError.getDefaultMessage(), "")); + }) + .sorted(Comparator.comparing(ApiValidationError::field)) + .toList(); problemDetail.setProperty("violations", validationErrorsList); return problemDetail; } diff --git a/boot-rest-docs-sample/src/main/java/com/example/restdocs/config/SwaggerConfig.java b/boot-rest-docs-sample/src/main/java/com/example/restdocs/config/SwaggerConfig.java index e436a710b..74af62620 100644 --- a/boot-rest-docs-sample/src/main/java/com/example/restdocs/config/SwaggerConfig.java +++ b/boot-rest-docs-sample/src/main/java/com/example/restdocs/config/SwaggerConfig.java @@ -6,5 +6,7 @@ import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) -@OpenAPIDefinition(info = @Info(title = "boot-rest-docs-sample", version = "v1"), servers = @Server(url = "/")) +@OpenAPIDefinition( + info = @Info(title = "boot-rest-docs-sample", version = "v1"), + servers = @Server(url = "/")) public class SwaggerConfig {} diff --git a/boot-rest-docs-sample/src/main/java/com/example/restdocs/config/logging/LoggingAspect.java b/boot-rest-docs-sample/src/main/java/com/example/restdocs/config/logging/LoggingAspect.java index 5aeb60e9d..ce04ea62c 100644 --- a/boot-rest-docs-sample/src/main/java/com/example/restdocs/config/logging/LoggingAspect.java +++ b/boot-rest-docs-sample/src/main/java/com/example/restdocs/config/logging/LoggingAspect.java @@ -25,15 +25,17 @@ public LoggingAspect(Environment env) { this.env = env; } - @Pointcut("within(@org.springframework.stereotype.Repository *)" - + " || within(@org.springframework.stereotype.Service *)" - + " || within(@org.springframework.web.bind.annotation.RestController *)") + @Pointcut( + "within(@org.springframework.stereotype.Repository *)" + + " || within(@org.springframework.stereotype.Service *)" + + " || within(@org.springframework.web.bind.annotation.RestController *)") public void springBeanPointcut() { // pointcut definition } - @Pointcut("@within(com.example.restdocs.config.logging.Loggable) || " - + "@annotation(com.example.restdocs.config.logging.Loggable)") + @Pointcut( + "@within(com.example.restdocs.config.logging.Loggable) || " + + "@annotation(com.example.restdocs.config.logging.Loggable)") public void applicationPackagePointcut() { // pointcut definition } diff --git a/boot-rest-docs-sample/src/main/java/com/example/restdocs/services/UserService.java b/boot-rest-docs-sample/src/main/java/com/example/restdocs/services/UserService.java index 3eb2af354..5bce623f2 100644 --- a/boot-rest-docs-sample/src/main/java/com/example/restdocs/services/UserService.java +++ b/boot-rest-docs-sample/src/main/java/com/example/restdocs/services/UserService.java @@ -22,9 +22,10 @@ public class UserService { @Transactional(readOnly = true) public PagedResult findAllUsers(int pageNo, int pageSize, String sortBy, String sortDir) { - Sort sort = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name()) - ? Sort.by(sortBy).ascending() - : Sort.by(sortBy).descending(); + Sort sort = + sortDir.equalsIgnoreCase(Sort.Direction.ASC.name()) + ? Sort.by(sortBy).ascending() + : Sort.by(sortBy).descending(); // create Pageable instance Pageable pageable = PageRequest.of(pageNo, pageSize, sort); diff --git a/boot-rest-docs-sample/src/main/java/com/example/restdocs/web/controllers/UserController.java b/boot-rest-docs-sample/src/main/java/com/example/restdocs/web/controllers/UserController.java index 3dcba9abf..7a5b68dfe 100644 --- a/boot-rest-docs-sample/src/main/java/com/example/restdocs/web/controllers/UserController.java +++ b/boot-rest-docs-sample/src/main/java/com/example/restdocs/web/controllers/UserController.java @@ -29,21 +29,35 @@ public class UserController { @GetMapping public PagedResult getAllUsers( - @RequestParam(value = "pageNo", defaultValue = AppConstants.DEFAULT_PAGE_NUMBER, required = false) + @RequestParam( + value = "pageNo", + defaultValue = AppConstants.DEFAULT_PAGE_NUMBER, + required = false) int pageNo, - @RequestParam(value = "pageSize", defaultValue = AppConstants.DEFAULT_PAGE_SIZE, required = false) + @RequestParam( + value = "pageSize", + defaultValue = AppConstants.DEFAULT_PAGE_SIZE, + required = false) int pageSize, - @RequestParam(value = "sortBy", defaultValue = AppConstants.DEFAULT_SORT_BY, required = false) + @RequestParam( + value = "sortBy", + defaultValue = AppConstants.DEFAULT_SORT_BY, + required = false) String sortBy, - @RequestParam(value = "sortDir", defaultValue = AppConstants.DEFAULT_SORT_DIRECTION, required = false) + @RequestParam( + value = "sortDir", + defaultValue = AppConstants.DEFAULT_SORT_DIRECTION, + required = false) String sortDir) { return userService.findAllUsers(pageNo, pageSize, sortBy, sortDir); } @GetMapping("/{id}") public ResponseEntity getUserById(@PathVariable Long id) { - return userService.findUserById(id).map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound() - .build()); + return userService + .findUserById(id) + .map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.notFound().build()); } @PostMapping @@ -53,7 +67,8 @@ public User createUser(@RequestBody @Validated UserRequest userRequest) { } @PutMapping("/{id}") - public ResponseEntity updateUser(@PathVariable Long id, @RequestBody UserRequest userRequest) { + public ResponseEntity updateUser( + @PathVariable Long id, @RequestBody UserRequest userRequest) { return userService .findUserById(id) .map(userObj -> ResponseEntity.ok(userService.updateUser(userObj, userRequest))) @@ -64,10 +79,11 @@ public ResponseEntity updateUser(@PathVariable Long id, @RequestBody UserR public ResponseEntity deleteUser(@PathVariable Long id) { return userService .findUserById(id) - .map(user -> { - userService.deleteUserById(id); - return ResponseEntity.ok(user); - }) + .map( + user -> { + userService.deleteUserById(id); + return ResponseEntity.ok(user); + }) .orElseGet(() -> ResponseEntity.notFound().build()); } } diff --git a/boot-rest-docs-sample/src/test/java/com/example/restdocs/ApplicationIntegrationTest.java b/boot-rest-docs-sample/src/test/java/com/example/restdocs/ApplicationIntegrationTest.java index 2510c5093..79e13aba9 100644 --- a/boot-rest-docs-sample/src/test/java/com/example/restdocs/ApplicationIntegrationTest.java +++ b/boot-rest-docs-sample/src/test/java/com/example/restdocs/ApplicationIntegrationTest.java @@ -12,8 +12,7 @@ @TestPropertySource(properties = {"spring.jpa.hibernate.ddl-auto=validate"}) class ApplicationIntegrationTest extends AbstractIntegrationTest { - @Autowired - private DataSource dataSource; + @Autowired private DataSource dataSource; @Test void contextLoads() { diff --git a/boot-rest-docs-sample/src/test/java/com/example/restdocs/common/AbstractIntegrationTest.java b/boot-rest-docs-sample/src/test/java/com/example/restdocs/common/AbstractIntegrationTest.java index 99a7bf7e0..ad13c9806 100644 --- a/boot-rest-docs-sample/src/test/java/com/example/restdocs/common/AbstractIntegrationTest.java +++ b/boot-rest-docs-sample/src/test/java/com/example/restdocs/common/AbstractIntegrationTest.java @@ -18,9 +18,7 @@ @AutoConfigureMockMvc public abstract class AbstractIntegrationTest { - @Autowired - protected MockMvc mockMvc; + @Autowired protected MockMvc mockMvc; - @Autowired - protected ObjectMapper objectMapper; + @Autowired protected ObjectMapper objectMapper; } diff --git a/boot-rest-docs-sample/src/test/java/com/example/restdocs/services/UserServiceTest.java b/boot-rest-docs-sample/src/test/java/com/example/restdocs/services/UserServiceTest.java index d3ce58db2..e1d4669dd 100644 --- a/boot-rest-docs-sample/src/test/java/com/example/restdocs/services/UserServiceTest.java +++ b/boot-rest-docs-sample/src/test/java/com/example/restdocs/services/UserServiceTest.java @@ -28,11 +28,9 @@ @ExtendWith(MockitoExtension.class) class UserServiceTest { - @Mock - private UserRepository userRepository; + @Mock private UserRepository userRepository; - @InjectMocks - private UserService userService; + @InjectMocks private UserService userService; @Test void findAllUsers() { @@ -72,14 +70,17 @@ void findUserById() { @Test void saveUser() { // given - given(userRepository.save(any(User.class))).willAnswer((invocationOnMock) -> { - if (invocationOnMock.getArguments().length > 0 - && invocationOnMock.getArguments()[0] instanceof User mockUser) { - mockUser.setId(34L); - return mockUser; - } - return null; - }); + given(userRepository.save(any(User.class))) + .willAnswer( + (invocationOnMock) -> { + if (invocationOnMock.getArguments().length > 0 + && invocationOnMock.getArguments()[0] + instanceof User mockUser) { + mockUser.setId(34L); + return mockUser; + } + return null; + }); // when User persistedUser = userService.saveUser(getUserRequest()); // then diff --git a/boot-rest-docs-sample/src/test/java/com/example/restdocs/web/controllers/UserControllerIT.java b/boot-rest-docs-sample/src/test/java/com/example/restdocs/web/controllers/UserControllerIT.java index c3df0ab22..28d78437e 100644 --- a/boot-rest-docs-sample/src/test/java/com/example/restdocs/web/controllers/UserControllerIT.java +++ b/boot-rest-docs-sample/src/test/java/com/example/restdocs/web/controllers/UserControllerIT.java @@ -25,8 +25,7 @@ class UserControllerIT extends AbstractIntegrationTest { - @Autowired - private UserRepository userRepository; + @Autowired private UserRepository userRepository; private List userList = null; @@ -74,11 +73,13 @@ void shouldFindUserById() throws Exception { @Test void shouldCreateNewUser() throws Exception { - UserRequest userRequest = new UserRequest("New User", "Last Name", 30, Gender.FEMALE, "9848022334"); + UserRequest userRequest = + new UserRequest("New User", "Last Name", 30, Gender.FEMALE, "9848022334"); this.mockMvc - .perform(post("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(userRequest))) + .perform( + post("/api/users") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(userRequest))) .andExpect(status().isCreated()) .andExpect(jsonPath("$.id", notNullValue())) .andExpect(jsonPath("$.firstName", is(userRequest.firstName()))) @@ -93,9 +94,10 @@ void shouldReturn400WhenCreateNewUserWithoutFirstName() throws Exception { UserRequest userRequest = new UserRequest(null, "Last Name", 0, Gender.MALE, "9848022334"); this.mockMvc - .perform(post("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(userRequest))) + .perform( + post("/api/users") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(userRequest))) .andExpect(status().isBadRequest()) .andExpect(header().string("Content-Type", is("application/problem+json"))) .andExpect(jsonPath("$.type", is("about:blank"))) @@ -114,12 +116,14 @@ void shouldReturn400WhenCreateNewUserWithoutFirstName() throws Exception { @Test void shouldUpdateUser() throws Exception { User user = userList.get(0); - UserRequest userRequest = new UserRequest("Updated User", "Last Name", 50, Gender.FEMALE, "9848022334"); + UserRequest userRequest = + new UserRequest("Updated User", "Last Name", 50, Gender.FEMALE, "9848022334"); this.mockMvc - .perform(put("/api/users/{id}", user.getId()) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(userRequest))) + .perform( + put("/api/users/{id}", user.getId()) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(userRequest))) .andExpect(status().isOk()) .andExpect(jsonPath("$.id", is(user.getId()), Long.class)) .andExpect(jsonPath("$.firstName", is(userRequest.firstName()))) diff --git a/boot-rest-docs-sample/src/test/java/com/example/restdocs/web/controllers/UserControllerTest.java b/boot-rest-docs-sample/src/test/java/com/example/restdocs/web/controllers/UserControllerTest.java index bd52dd7b6..0a6679fbe 100644 --- a/boot-rest-docs-sample/src/test/java/com/example/restdocs/web/controllers/UserControllerTest.java +++ b/boot-rest-docs-sample/src/test/java/com/example/restdocs/web/controllers/UserControllerTest.java @@ -51,14 +51,11 @@ @AutoConfigureRestDocs class UserControllerTest { - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; - @MockBean - private UserService userService; + @MockBean private UserService userService; - @Autowired - private ObjectMapper objectMapper; + @Autowired private ObjectMapper objectMapper; private List userList; @@ -87,23 +84,26 @@ void shouldFetchAllUsers() throws Exception { .andExpect(jsonPath("$.isLast", is(true))) .andExpect(jsonPath("$.hasNext", is(false))) .andExpect(jsonPath("$.hasPrevious", is(false))) - .andDo(document( - "find-all", - preprocessResponse(prettyPrint()), - queryParameters( - parameterWithName("pageNo") - .description("Page you want to retrieve, 0 indexed and defaults to 0.") - .optional(), - parameterWithName("pageSize") - .description("Size of the page you want to retrieve, defaults to 10.") - .optional(), - parameterWithName("sortBy") - .description("Property name for sorting") - .optional(), - parameterWithName("sortDir") - .description("Sort direction ('asc' or 'desc')") - .optional()), - responseFields(getPaginatedResponse()))); + .andDo( + document( + "find-all", + preprocessResponse(prettyPrint()), + queryParameters( + parameterWithName("pageNo") + .description( + "Page you want to retrieve, 0 indexed and defaults to 0.") + .optional(), + parameterWithName("pageSize") + .description( + "Size of the page you want to retrieve, defaults to 10.") + .optional(), + parameterWithName("sortBy") + .description("Property name for sorting") + .optional(), + parameterWithName("sortDir") + .description("Sort direction ('asc' or 'desc')") + .optional()), + responseFields(getPaginatedResponse()))); } @Test @@ -120,11 +120,14 @@ void shouldFindUserById() throws Exception { .andExpect(jsonPath("$.age", is(user.getAge()))) .andExpect(jsonPath("$.gender", is(user.getGender().name()))) .andExpect(jsonPath("$.phoneNumber", is(user.getPhoneNumber()))) - .andDo(document( - "find-by-id", - preprocessResponse(prettyPrint()), - pathParameters(parameterWithName("id").description("The id of the user to retrieve")), - responseFields(getUserFieldDescriptor()))); + .andDo( + document( + "find-by-id", + preprocessResponse(prettyPrint()), + pathParameters( + parameterWithName("id") + .description("The id of the user to retrieve")), + responseFields(getUserFieldDescriptor()))); ; } @@ -140,12 +143,14 @@ void shouldReturn404WhenFetchingNonExistingUser() throws Exception { void shouldCreateNewUser() throws Exception { User user = new User(34L, "some text", "Last Name", 30, Gender.MALE, "9848022334"); - UserRequest userRequest = new UserRequest("some text", "Last Name", 30, Gender.MALE, "9848022334"); + UserRequest userRequest = + new UserRequest("some text", "Last Name", 30, Gender.MALE, "9848022334"); given(userService.saveUser(userRequest)).willReturn(user); this.mockMvc - .perform(post("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(userRequest))) + .perform( + post("/api/users") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(userRequest))) .andExpect(status().isCreated()) .andExpect(jsonPath("$.id", is(34))) .andExpect(jsonPath("$.firstName", is(user.getFirstName()))) @@ -153,12 +158,13 @@ void shouldCreateNewUser() throws Exception { .andExpect(jsonPath("$.age", is(user.getAge()))) .andExpect(jsonPath("$.gender", is(user.getGender().name()))) .andExpect(jsonPath("$.phoneNumber", is(user.getPhoneNumber()))) - .andDo(document( - "create-user", - preprocessRequest(prettyPrint()), - preprocessResponse(prettyPrint()), - requestFields(getUserRequestFieldDescriptor()), - responseFields(getUserFieldDescriptor()))); + .andDo( + document( + "create-user", + preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + requestFields(getUserRequestFieldDescriptor()), + responseFields(getUserFieldDescriptor()))); ; } @@ -167,9 +173,10 @@ void shouldReturn400WhenCreateNewUserWithoutFirstNameAndAge() throws Exception { UserRequest userRequest = new UserRequest(null, "Last Name", 90, Gender.MALE, "9848022334"); this.mockMvc - .perform(post("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(userRequest))) + .perform( + post("/api/users") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(userRequest))) .andExpect(status().isBadRequest()) .andExpect(header().string("Content-Type", is("application/problem+json"))) .andExpect(jsonPath("$.type", is("about:blank"))) @@ -187,39 +194,46 @@ void shouldReturn400WhenCreateNewUserWithoutFirstNameAndAge() throws Exception { void shouldUpdateUser() throws Exception { Long userId = 1L; User user = new User(userId, "some text", "Last Name", 30, Gender.MALE, "9848022334"); - UserRequest userRequest = new UserRequest("some text", "Last Name", 30, Gender.MALE, "9848022334"); + UserRequest userRequest = + new UserRequest("some text", "Last Name", 30, Gender.MALE, "9848022334"); given(userService.findUserById(userId)).willReturn(Optional.of(user)); given(userService.updateUser(user, userRequest)).willReturn(user); this.mockMvc - .perform(put("/api/users/{id}", user.getId()) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(userRequest))) + .perform( + put("/api/users/{id}", user.getId()) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(userRequest))) .andExpect(status().isOk()) .andExpect(jsonPath("$.firstName", is(user.getFirstName()))) .andExpect(jsonPath("$.lastName", is(user.getLastName()))) .andExpect(jsonPath("$.age", is(user.getAge()))) .andExpect(jsonPath("$.gender", is(user.getGender().name()))) .andExpect(jsonPath("$.phoneNumber", is(user.getPhoneNumber()))) - .andDo(document( - "update-user", - preprocessRequest(prettyPrint()), - preprocessResponse(prettyPrint()), - pathParameters(parameterWithName("id").description("The id of the user to update")), - requestFields(getUserRequestFieldDescriptor()), - responseFields(getUserFieldDescriptor()))); + .andDo( + document( + "update-user", + preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + pathParameters( + parameterWithName("id") + .description("The id of the user to update")), + requestFields(getUserRequestFieldDescriptor()), + responseFields(getUserFieldDescriptor()))); } @Test void shouldReturn404WhenUpdatingNonExistingUser() throws Exception { Long userId = 1L; given(userService.findUserById(userId)).willReturn(Optional.empty()); - UserRequest userRequest = new UserRequest("Updated text", "Last Name", 30, Gender.MALE, "9848022334"); + UserRequest userRequest = + new UserRequest("Updated text", "Last Name", 30, Gender.MALE, "9848022334"); this.mockMvc - .perform(put("/api/users/{id}", userId) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(userRequest))) + .perform( + put("/api/users/{id}", userId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(userRequest))) .andExpect(status().isNotFound()); } @@ -238,11 +252,14 @@ void shouldDeleteUser() throws Exception { .andExpect(jsonPath("$.age", is(user.getAge()))) .andExpect(jsonPath("$.gender", is(user.getGender().name()))) .andExpect(jsonPath("$.phoneNumber", is(user.getPhoneNumber()))) - .andDo(document( - "delete-user", - preprocessResponse(prettyPrint()), - pathParameters(parameterWithName("id").description("The id of the user to delete")), - responseFields(getUserFieldDescriptor()))); + .andDo( + document( + "delete-user", + preprocessResponse(prettyPrint()), + pathParameters( + parameterWithName("id") + .description("The id of the user to delete")), + responseFields(getUserFieldDescriptor()))); } @Test @@ -255,7 +272,9 @@ void shouldReturn404WhenDeletingNonExistingUser() throws Exception { private FieldDescriptor[] getUserFieldDescriptor() { return new FieldDescriptor[] { - fieldWithPath("age").description("The age of the customer").type(Integer.class.getSimpleName()), + fieldWithPath("age") + .description("The age of the customer") + .type(Integer.class.getSimpleName()), fieldWithPath("firstName") .description("The first name of the customer") .type(String.class.getSimpleName()), @@ -311,21 +330,33 @@ private FieldDescriptor[] getPaginatedResponse() { fieldWithPath("data[].lastName") .description("Last name of the user") .type(String.class.getSimpleName()), - fieldWithPath("data[].age").description("Age of the user").type(Integer.class.getSimpleName()), - fieldWithPath("data[].gender").description("Gender of the user").type(String.class.getSimpleName()), + fieldWithPath("data[].age") + .description("Age of the user") + .type(Integer.class.getSimpleName()), + fieldWithPath("data[].gender") + .description("Gender of the user") + .type(String.class.getSimpleName()), fieldWithPath("data[].phoneNumber") .description("Phone number of the user") .type(String.class.getSimpleName()), - fieldWithPath("totalElements").description("Total count.").type(Integer.class.getSimpleName()), + fieldWithPath("totalElements") + .description("Total count.") + .type(Integer.class.getSimpleName()), fieldWithPath("totalPages") .description("Total pages with current page size.") .type(Integer.class.getSimpleName()), - fieldWithPath("pageNumber").description("Page number.").type(Integer.class.getSimpleName()), + fieldWithPath("pageNumber") + .description("Page number.") + .type(Integer.class.getSimpleName()), fieldWithPath("isFirst") .description("If this page is the first one.") .type(Boolean.class.getSimpleName()), - fieldWithPath("isLast").description("If this page is the last one.").type(Boolean.class.getSimpleName()), - fieldWithPath("hasNext").description("Does next page exists.").type(Boolean.class.getSimpleName()), + fieldWithPath("isLast") + .description("If this page is the last one.") + .type(Boolean.class.getSimpleName()), + fieldWithPath("hasNext") + .description("Does next page exists.") + .type(Boolean.class.getSimpleName()), fieldWithPath("hasPrevious") .description("Does previous page exists.") .type(Boolean.class.getSimpleName()) diff --git a/boot-togglz-sample/pom.xml b/boot-togglz-sample/pom.xml index f2fe7e20f..cc5a55db4 100644 --- a/boot-togglz-sample/pom.xml +++ b/boot-togglz-sample/pom.xml @@ -239,7 +239,7 @@ - 1.15.0 + 1.17.0 diff --git a/jpa/boot-data-multipledatasources/pom.xml b/jpa/boot-data-multipledatasources/pom.xml index 39f1e3f74..10abbd398 100644 --- a/jpa/boot-data-multipledatasources/pom.xml +++ b/jpa/boot-data-multipledatasources/pom.xml @@ -220,7 +220,7 @@ - 1.15.0 + 1.17.0 diff --git a/r2dbc/boot-r2dbc-sample/pom.xml b/r2dbc/boot-r2dbc-sample/pom.xml index 7bede42f7..16892addb 100644 --- a/r2dbc/boot-r2dbc-sample/pom.xml +++ b/r2dbc/boot-r2dbc-sample/pom.xml @@ -305,9 +305,10 @@ ${spotless.version} - - 2.30.0 - + + 1.17.0 + + diff --git a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/ApplicationProperties.java b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/ApplicationProperties.java index 411c05c8a..37d0ebc05 100644 --- a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/ApplicationProperties.java +++ b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/ApplicationProperties.java @@ -8,8 +8,7 @@ @ConfigurationProperties("application") public class ApplicationProperties { - @NestedConfigurationProperty - private Cors cors = new Cors(); + @NestedConfigurationProperty private Cors cors = new Cors(); @Data public static class Cors { diff --git a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/AuditingDatabaseConfig.java b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/AuditingDatabaseConfig.java index 0ac0f45d4..c1b7a0261 100644 --- a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/AuditingDatabaseConfig.java +++ b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/AuditingDatabaseConfig.java @@ -15,11 +15,12 @@ public class AuditingDatabaseConfig { @Bean ReactiveAuditorAware auditorAware() { - return () -> ReactiveSecurityContextHolder.getContext() - .map(SecurityContext::getAuthentication) - .filter(Authentication::isAuthenticated) - .map(Authentication::getPrincipal) - .map(User.class::cast) - .map(User::getUsername); + return () -> + ReactiveSecurityContextHolder.getContext() + .map(SecurityContext::getAuthentication) + .filter(Authentication::isAuthenticated) + .map(Authentication::getPrincipal) + .map(User.class::cast) + .map(User::getUsername); } } diff --git a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/GlobalExceptionHandler.java b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/GlobalExceptionHandler.java index 851ab9978..179241b2c 100644 --- a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/GlobalExceptionHandler.java +++ b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/GlobalExceptionHandler.java @@ -22,19 +22,23 @@ public class GlobalExceptionHandler { @ResponseStatus(HttpStatus.BAD_REQUEST) ProblemDetail onException(WebExchangeBindException webExchangeBindException) { ProblemDetail problemDetail = - ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(400), "Invalid request content."); + ProblemDetail.forStatusAndDetail( + HttpStatusCode.valueOf(400), "Invalid request content."); problemDetail.setTitle("Constraint Violation"); - List validationErrorsList = webExchangeBindException.getAllErrors().stream() - .map(objectError -> { - FieldError fieldError = (FieldError) objectError; - return new ApiValidationError( - fieldError.getObjectName(), - fieldError.getField(), - fieldError.getRejectedValue(), - Objects.requireNonNull(fieldError.getDefaultMessage(), "")); - }) - .sorted(Comparator.comparing(ApiValidationError::field)) - .toList(); + List validationErrorsList = + webExchangeBindException.getAllErrors().stream() + .map( + objectError -> { + FieldError fieldError = (FieldError) objectError; + return new ApiValidationError( + fieldError.getObjectName(), + fieldError.getField(), + fieldError.getRejectedValue(), + Objects.requireNonNull( + fieldError.getDefaultMessage(), "")); + }) + .sorted(Comparator.comparing(ApiValidationError::field)) + .toList(); problemDetail.setProperty("violations", validationErrorsList); return problemDetail; } diff --git a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/SecurityConfig.java b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/SecurityConfig.java index f69a43fe4..37db19497 100644 --- a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/SecurityConfig.java +++ b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/SecurityConfig.java @@ -27,16 +27,21 @@ SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) { return http.csrf(ServerHttpSecurity.CsrfSpec::disable) .httpBasic(Customizer.withDefaults()) .authorizeExchange( - it -> it.pathMatchers("/webjars/**", "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**") - .permitAll() // Allow Springdoc OpenAPI resources - .pathMatchers(HttpMethod.DELETE, postPath) - .hasRole("ADMIN") - .pathMatchers(postPath) - .hasRole("USER") - .pathMatchers("/users/{user}/**") - .access(this::currentUserMatchesPath) - .anyExchange() - .authenticated()) + it -> + it.pathMatchers( + "/webjars/**", + "/swagger-ui.html", + "/swagger-ui/**", + "/v3/api-docs/**") + .permitAll() // Allow Springdoc OpenAPI resources + .pathMatchers(HttpMethod.DELETE, postPath) + .hasRole("ADMIN") + .pathMatchers(postPath) + .hasRole("USER") + .pathMatchers("/users/{user}/**") + .access(this::currentUserMatchesPath) + .anyExchange() + .authenticated()) .build(); } @@ -53,17 +58,20 @@ PasswordEncoder passwordEncoder() { } @Bean(name = "userDetailsService") - public MapReactiveUserDetailsService userDetailsServiceWithPasswordEncoder(PasswordEncoder passwordEncoder) { - UserDetails user = User.withUsername("user") - .passwordEncoder(passwordEncoder::encode) - .password("password") - .roles("USER") - .build(); - UserDetails admin = User.withUsername("admin") - .passwordEncoder(passwordEncoder::encode) - .password("password") - .roles("USER", "ADMIN") - .build(); + public MapReactiveUserDetailsService userDetailsServiceWithPasswordEncoder( + PasswordEncoder passwordEncoder) { + UserDetails user = + User.withUsername("user") + .passwordEncoder(passwordEncoder::encode) + .password("password") + .roles("USER") + .build(); + UserDetails admin = + User.withUsername("admin") + .passwordEncoder(passwordEncoder::encode) + .password("password") + .roles("USER", "ADMIN") + .build(); return new MapReactiveUserDetailsService(user, admin); } } diff --git a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/logging/LoggingAspect.java b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/logging/LoggingAspect.java index 39d384682..a26e11599 100644 --- a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/logging/LoggingAspect.java +++ b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/config/logging/LoggingAspect.java @@ -25,15 +25,17 @@ public LoggingAspect(Environment env) { this.env = env; } - @Pointcut("within(@org.springframework.stereotype.Repository *)" - + " || within(@org.springframework.stereotype.Service *)" - + " || within(@org.springframework.web.bind.annotation.RestController *)") + @Pointcut( + "within(@org.springframework.stereotype.Repository *)" + + " || within(@org.springframework.stereotype.Service *)" + + " || within(@org.springframework.web.bind.annotation.RestController *)") public void springBeanPointcut() { // pointcut definition } - @Pointcut("@within(com.example.bootr2dbc.config.logging.Loggable) || " - + "@annotation(com.example.bootr2dbc.config.logging.Loggable)") + @Pointcut( + "@within(com.example.bootr2dbc.config.logging.Loggable) || " + + "@annotation(com.example.bootr2dbc.config.logging.Loggable)") public void applicationPackagePointcut() { // pointcut definition } diff --git a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/mapper/ReactivePostCommentMapper.java b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/mapper/ReactivePostCommentMapper.java index d11667050..b90090454 100644 --- a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/mapper/ReactivePostCommentMapper.java +++ b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/mapper/ReactivePostCommentMapper.java @@ -17,5 +17,6 @@ public interface ReactivePostCommentMapper { ReactiveComments mapToReactivePostComments(ReactiveCommentRequest reactiveCommentRequest); void updateReactiveCommentRequestFromReactiveComments( - ReactiveCommentRequest reactiveCommentRequest, @MappingTarget ReactiveComments reactiveComments); + ReactiveCommentRequest reactiveCommentRequest, + @MappingTarget ReactiveComments reactiveComments); } diff --git a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/repositories/ReactiveCommentsRepository.java b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/repositories/ReactiveCommentsRepository.java index d047ff284..8183ac01f 100644 --- a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/repositories/ReactiveCommentsRepository.java +++ b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/repositories/ReactiveCommentsRepository.java @@ -9,7 +9,8 @@ import reactor.core.publisher.Mono; public interface ReactiveCommentsRepository - extends ReactiveCrudRepository, ReactiveSortingRepository { + extends ReactiveCrudRepository, + ReactiveSortingRepository { Flux findAllByPostId(Long postId, Sort sort); diff --git a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/repositories/ReactivePostRepository.java b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/repositories/ReactivePostRepository.java index d3f953359..de9edd9e3 100644 --- a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/repositories/ReactivePostRepository.java +++ b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/repositories/ReactivePostRepository.java @@ -5,4 +5,5 @@ import org.springframework.data.repository.reactive.ReactiveSortingRepository; public interface ReactivePostRepository - extends ReactiveCrudRepository, ReactiveSortingRepository {} + extends ReactiveCrudRepository, + ReactiveSortingRepository {} diff --git a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/services/ReactiveCommentsService.java b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/services/ReactiveCommentsService.java index f430ba77e..f63defeeb 100644 --- a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/services/ReactiveCommentsService.java +++ b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/services/ReactiveCommentsService.java @@ -20,10 +20,12 @@ public class ReactiveCommentsService { private final ReactiveCommentsRepository reactiveCommentsRepository; private final ReactivePostCommentMapper reactivePostCommentMapper; - public Flux findAllReactiveCommentsByPostId(Long postId, String sortBy, String sortDir) { - Sort sort = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name()) - ? Sort.by(sortBy).ascending() - : Sort.by(sortBy).descending(); + public Flux findAllReactiveCommentsByPostId( + Long postId, String sortBy, String sortDir) { + Sort sort = + sortDir.equalsIgnoreCase(Sort.Direction.ASC.name()) + ? Sort.by(sortBy).ascending() + : Sort.by(sortBy).descending(); return reactiveCommentsRepository.findAllByPostId(postId, sort); } @@ -32,8 +34,10 @@ public Mono findReactiveCommentById(UUID id) { return reactiveCommentsRepository.findById(id); } - public Mono saveReactiveCommentByPostId(ReactiveCommentRequest reactiveCommentRequest) { - ReactiveComments reactiveComments = reactivePostCommentMapper.mapToReactivePostComments(reactiveCommentRequest); + public Mono saveReactiveCommentByPostId( + ReactiveCommentRequest reactiveCommentRequest) { + ReactiveComments reactiveComments = + reactivePostCommentMapper.mapToReactivePostComments(reactiveCommentRequest); return reactiveCommentsRepository.save(reactiveComments); } diff --git a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/services/ReactivePostService.java b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/services/ReactivePostService.java index de7e2ed20..7d015bb01 100644 --- a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/services/ReactivePostService.java +++ b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/services/ReactivePostService.java @@ -25,9 +25,10 @@ public class ReactivePostService { @Transactional(readOnly = true) public Flux findAllReactivePosts(String sortBy, String sortDir) { - Sort sort = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name()) - ? Sort.by(sortBy).ascending() - : Sort.by(sortBy).descending(); + Sort sort = + sortDir.equalsIgnoreCase(Sort.Direction.ASC.name()) + ? Sort.by(sortBy).ascending() + : Sort.by(sortBy).descending(); return reactivePostRepository.findAll(sort); } @@ -47,8 +48,10 @@ public Mono saveReactivePost(ReactivePostRequest reactivePostReque return reactivePostRepository.save(reactivePost); } - public Mono updateReactivePost(ReactivePostRequest reactivePostRequest, ReactivePost reactivePost) { - this.reactivePostMapper.updateReactivePostFromReactivePostRequest(reactivePostRequest, reactivePost); + public Mono updateReactivePost( + ReactivePostRequest reactivePostRequest, ReactivePost reactivePost) { + this.reactivePostMapper.updateReactivePostFromReactivePostRequest( + reactivePostRequest, reactivePost); return reactivePostRepository.save(reactivePost); } @@ -58,10 +61,12 @@ public Mono deleteReactivePostById(Long id) { public Mono> deleteReactivePostAndCommentsById(Long id) { return findReactivePostById(id) - .flatMap(reactivePost -> reactiveCommentsRepository - .deleteAllByPostId(reactivePost.getId()) - .then(deleteReactivePostById(reactivePost.getId())) - .then(Mono.just(ResponseEntity.noContent().build()))) + .flatMap( + reactivePost -> + reactiveCommentsRepository + .deleteAllByPostId(reactivePost.getId()) + .then(deleteReactivePostById(reactivePost.getId())) + .then(Mono.just(ResponseEntity.noContent().build()))) .switchIfEmpty(Mono.just(ResponseEntity.notFound().build())); } } diff --git a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/web/controllers/ReactiveCommentsController.java b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/web/controllers/ReactiveCommentsController.java index 52b28e0b7..2d7ab04dd 100644 --- a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/web/controllers/ReactiveCommentsController.java +++ b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/web/controllers/ReactiveCommentsController.java @@ -32,9 +32,15 @@ public class ReactiveCommentsController { @GetMapping("/") public Flux getAllReactiveComments( @RequestParam(value = "postId") Long postId, - @RequestParam(value = "sortBy", defaultValue = AppConstants.DEFAULT_SORT_BY, required = false) + @RequestParam( + value = "sortBy", + defaultValue = AppConstants.DEFAULT_SORT_BY, + required = false) String sortBy, - @RequestParam(value = "sortDir", defaultValue = AppConstants.DEFAULT_SORT_DIRECTION, required = false) + @RequestParam( + value = "sortDir", + defaultValue = AppConstants.DEFAULT_SORT_DIRECTION, + required = false) String sortDir) { return reactiveCommentsService.findAllReactiveCommentsByPostId(postId, sortBy, sortDir); } @@ -53,16 +59,20 @@ public Mono> createReactiveComment( UriComponentsBuilder uriComponentsBuilder) { return reactiveCommentsService .saveReactiveCommentByPostId(reactiveCommentRequest) - .map(savedPostComment -> { - // Build the location URI - String location = uriComponentsBuilder - .path("/api/post/comments/{id}") - .buildAndExpand(savedPostComment.getId()) - .toUriString(); + .map( + savedPostComment -> { + // Build the location URI + String location = + uriComponentsBuilder + .path("/api/post/comments/{id}") + .buildAndExpand(savedPostComment.getId()) + .toUriString(); - // Create a ResponseEntity with the Location header and the saved ReactivePost - return ResponseEntity.created(URI.create(location)).body(savedPostComment); - }); + // Create a ResponseEntity with the Location header and the saved + // ReactivePost + return ResponseEntity.created(URI.create(location)) + .body(savedPostComment); + }); } @PutMapping("/{id}") @@ -70,9 +80,12 @@ public Mono> updateReactiveComment( @PathVariable UUID id, @RequestBody ReactiveCommentRequest reactiveCommentRequest) { return reactiveCommentsService .findReactiveCommentById(id) - .flatMap(existingPostComment -> reactiveCommentsService - .updateReactivePostComment(reactiveCommentRequest, existingPostComment) - .map(ResponseEntity::ok)) + .flatMap( + existingPostComment -> + reactiveCommentsService + .updateReactivePostComment( + reactiveCommentRequest, existingPostComment) + .map(ResponseEntity::ok)) .switchIfEmpty(Mono.just(ResponseEntity.notFound().build())); } @@ -80,9 +93,11 @@ public Mono> updateReactiveComment( public Mono> deleteReactiveComment(@PathVariable UUID id) { return reactiveCommentsService .findReactiveCommentById(id) - .flatMap(reactivePostComment -> reactiveCommentsService - .deleteReactiveCommentById(id) - .then(Mono.just(ResponseEntity.noContent().build()))) + .flatMap( + reactivePostComment -> + reactiveCommentsService + .deleteReactiveCommentById(id) + .then(Mono.just(ResponseEntity.noContent().build()))) .switchIfEmpty(Mono.just(ResponseEntity.notFound().build())); } } diff --git a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/web/controllers/ReactivePostController.java b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/web/controllers/ReactivePostController.java index 7b8db495e..6fc5c00b9 100644 --- a/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/web/controllers/ReactivePostController.java +++ b/r2dbc/boot-r2dbc-sample/src/main/java/com/example/bootr2dbc/web/controllers/ReactivePostController.java @@ -31,20 +31,27 @@ public class ReactivePostController { @GetMapping("/") public Mono>> getAllReactivePosts( - @RequestParam(value = "sortBy", defaultValue = AppConstants.DEFAULT_SORT_BY, required = false) + @RequestParam( + value = "sortBy", + defaultValue = AppConstants.DEFAULT_SORT_BY, + required = false) String sortBy, - @RequestParam(value = "sortDir", defaultValue = AppConstants.DEFAULT_SORT_DIRECTION, required = false) + @RequestParam( + value = "sortDir", + defaultValue = AppConstants.DEFAULT_SORT_DIRECTION, + required = false) String sortDir) { return reactivePostService .findAllReactivePosts(sortBy, sortDir) .collectList() - .flatMap(posts -> { - if (posts.isEmpty()) { - return Mono.just(ResponseEntity.noContent().build()); - } else { - return Mono.just(ResponseEntity.ok(posts)); - } - }); + .flatMap( + posts -> { + if (posts.isEmpty()) { + return Mono.just(ResponseEntity.noContent().build()); + } else { + return Mono.just(ResponseEntity.ok(posts)); + } + }); } @GetMapping("/{id}") @@ -56,43 +63,53 @@ public Mono> getReactivePostById(@PathVariable Long } @GetMapping("/{postId}/comments") - public Mono>> getCommentsForReactivePost(@PathVariable Long postId) { + public Mono>> getCommentsForReactivePost( + @PathVariable Long postId) { return reactivePostService .findCommentsForReactivePost(postId) .collectList() - .flatMap(comments -> { - if (comments.isEmpty()) { - return Mono.just(ResponseEntity.noContent().build()); - } else { - return Mono.just(ResponseEntity.ok(comments)); - } - }); + .flatMap( + comments -> { + if (comments.isEmpty()) { + return Mono.just(ResponseEntity.noContent().build()); + } else { + return Mono.just(ResponseEntity.ok(comments)); + } + }); } @PostMapping("/") public Mono> createReactivePost( @RequestBody @Validated ReactivePostRequest reactivePostRequest, UriComponentsBuilder uriComponentsBuilder) { - return reactivePostService.saveReactivePost(reactivePostRequest).map(savedPost -> { - // Build the location URI - String location = uriComponentsBuilder - .path("/api/posts/{id}") - .buildAndExpand(savedPost.getId()) - .toUriString(); + return reactivePostService + .saveReactivePost(reactivePostRequest) + .map( + savedPost -> { + // Build the location URI + String location = + uriComponentsBuilder + .path("/api/posts/{id}") + .buildAndExpand(savedPost.getId()) + .toUriString(); - // Create a ResponseEntity with the Location header and the saved ReactivePost - return ResponseEntity.created(URI.create(location)).body(savedPost); - }); + // Create a ResponseEntity with the Location header and the saved + // ReactivePost + return ResponseEntity.created(URI.create(location)).body(savedPost); + }); } @PutMapping("/{id}") public Mono> updateReactivePost( - @PathVariable Long id, @Validated @RequestBody ReactivePostRequest reactivePostRequest) { + @PathVariable Long id, + @Validated @RequestBody ReactivePostRequest reactivePostRequest) { return reactivePostService .findReactivePostById(id) - .flatMap(existingPost -> reactivePostService - .updateReactivePost(reactivePostRequest, existingPost) - .map(ResponseEntity::ok)) + .flatMap( + existingPost -> + reactivePostService + .updateReactivePost(reactivePostRequest, existingPost) + .map(ResponseEntity::ok)) .switchIfEmpty(Mono.just(ResponseEntity.notFound().build())); } diff --git a/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/common/AbstractIntegrationTest.java b/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/common/AbstractIntegrationTest.java index 1d1db1b24..43dd5598e 100644 --- a/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/common/AbstractIntegrationTest.java +++ b/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/common/AbstractIntegrationTest.java @@ -17,6 +17,5 @@ @AutoConfigureWebTestClient public abstract class AbstractIntegrationTest { - @Autowired - protected WebTestClient webTestClient; + @Autowired protected WebTestClient webTestClient; } diff --git a/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/services/ReactiveCommentsServiceTest.java b/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/services/ReactiveCommentsServiceTest.java index bd805b4ea..e1a491489 100644 --- a/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/services/ReactiveCommentsServiceTest.java +++ b/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/services/ReactiveCommentsServiceTest.java @@ -23,33 +23,34 @@ @ExtendWith(MockitoExtension.class) class ReactiveCommentsServiceTest { - @Mock - private ReactiveCommentsRepository reactiveCommentsRepository; + @Mock private ReactiveCommentsRepository reactiveCommentsRepository; - @Mock - private ReactivePostCommentMapper reactivePostCommentMapper; + @Mock private ReactivePostCommentMapper reactivePostCommentMapper; - @InjectMocks - private ReactiveCommentsService reactiveCommentsService; + @InjectMocks private ReactiveCommentsService reactiveCommentsService; @Test void findAllReactiveComments() { // given Sort sort = Sort.by(Sort.Direction.ASC, "id"); - given(reactiveCommentsRepository.findAllByPostId(1L, sort)).willReturn(Flux.just(getReactiveComments())); + given(reactiveCommentsRepository.findAllByPostId(1L, sort)) + .willReturn(Flux.just(getReactiveComments())); // when - Flux pagedResult = reactiveCommentsService.findAllReactiveCommentsByPostId(1L, "id", "asc"); + Flux pagedResult = + reactiveCommentsService.findAllReactiveCommentsByPostId(1L, "id", "asc"); // then assertThat(pagedResult).isNotNull(); StepVerifier.create(pagedResult) - .expectNextMatches(reactivePostComment -> reactivePostComment - .getPostId() - .equals(getReactiveComments().getPostId()) - && reactivePostComment - .getContent() - .equals(getReactiveComments().getContent())) + .expectNextMatches( + reactivePostComment -> + reactivePostComment + .getPostId() + .equals(getReactiveComments().getPostId()) + && reactivePostComment + .getContent() + .equals(getReactiveComments().getContent())) .expectComplete() .verify(); } @@ -58,17 +59,21 @@ void findAllReactiveComments() { void findReactiveCommentsById() { // given UUID postCommentId = UUID.randomUUID(); - given(reactiveCommentsRepository.findById(postCommentId)).willReturn(Mono.just(getReactiveComments())); + given(reactiveCommentsRepository.findById(postCommentId)) + .willReturn(Mono.just(getReactiveComments())); // when - Mono reactiveCommentsMono = reactiveCommentsService.findReactiveCommentById(postCommentId); + Mono reactiveCommentsMono = + reactiveCommentsService.findReactiveCommentById(postCommentId); // then StepVerifier.create(reactiveCommentsMono) - .expectNextMatches(reactivePostComment -> reactivePostComment - .getPostId() - .equals(getReactiveComments().getPostId()) - && reactivePostComment - .getContent() - .equals(getReactiveComments().getContent())) + .expectNextMatches( + reactivePostComment -> + reactivePostComment + .getPostId() + .equals(getReactiveComments().getPostId()) + && reactivePostComment + .getContent() + .equals(getReactiveComments().getContent())) .expectComplete() .verify(); } @@ -77,25 +82,29 @@ void findReactiveCommentsById() { void saveReactiveComments() { // given ReactiveCommentRequest reactivePostCommentsRequest = getReactiveCommentRequest(); - ReactiveComments mappedReactivePostComments = ReactiveComments.builder() - .content(reactivePostCommentsRequest.content()) - .title(reactivePostCommentsRequest.title()) - .postId(reactivePostCommentsRequest.postId()) - .build(); + ReactiveComments mappedReactivePostComments = + ReactiveComments.builder() + .content(reactivePostCommentsRequest.content()) + .title(reactivePostCommentsRequest.title()) + .postId(reactivePostCommentsRequest.postId()) + .build(); given(reactivePostCommentMapper.mapToReactivePostComments(reactivePostCommentsRequest)) .willReturn(mappedReactivePostComments); - given(reactiveCommentsRepository.save(mappedReactivePostComments)).willReturn(Mono.just(getReactiveComments())); + given(reactiveCommentsRepository.save(mappedReactivePostComments)) + .willReturn(Mono.just(getReactiveComments())); // when Mono persistedReactiveComments = reactiveCommentsService.saveReactiveCommentByPostId(reactivePostCommentsRequest); // then StepVerifier.create(persistedReactiveComments) - .expectNextMatches(reactivePostComment -> reactivePostComment - .getPostId() - .equals(getReactiveComments().getPostId()) - && reactivePostComment - .getContent() - .equals(getReactiveComments().getContent())) + .expectNextMatches( + reactivePostComment -> + reactivePostComment + .getPostId() + .equals(getReactiveComments().getPostId()) + && reactivePostComment + .getContent() + .equals(getReactiveComments().getContent())) .expectComplete() .verify(); } diff --git a/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/services/ReactivePostServiceTest.java b/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/services/ReactivePostServiceTest.java index b665988c1..429d15310 100644 --- a/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/services/ReactivePostServiceTest.java +++ b/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/services/ReactivePostServiceTest.java @@ -23,17 +23,13 @@ @ExtendWith(MockitoExtension.class) class ReactivePostServiceTest { - @Mock - private ReactivePostRepository reactivePostRepository; + @Mock private ReactivePostRepository reactivePostRepository; - @Mock - private ReactiveCommentsRepository reactiveCommentsRepository; + @Mock private ReactiveCommentsRepository reactiveCommentsRepository; - @Mock - private ReactivePostMapper reactivePostMapper; + @Mock private ReactivePostMapper reactivePostMapper; - @InjectMocks - private ReactivePostService reactivePostService; + @InjectMocks private ReactivePostService reactivePostService; @Test void findAllReactivePosts() { @@ -46,10 +42,15 @@ void findAllReactivePosts() { // then StepVerifier.create(pagedResult) - .expectNextMatches(reactivePost -> Objects.equals( - reactivePost.getId(), getReactivePost().getId()) - && reactivePost.getTitle().equals(getReactivePost().getTitle()) - && reactivePost.getContent().equals(getReactivePost().getContent())) + .expectNextMatches( + reactivePost -> + Objects.equals(reactivePost.getId(), getReactivePost().getId()) + && reactivePost + .getTitle() + .equals(getReactivePost().getTitle()) + && reactivePost + .getContent() + .equals(getReactivePost().getContent())) .expectComplete() .verify(); } @@ -62,10 +63,15 @@ void findReactivePostById() { Mono reactivePostMono = reactivePostService.findReactivePostById(1L); // then StepVerifier.create(reactivePostMono) - .expectNextMatches(reactivePost -> Objects.equals( - reactivePost.getId(), getReactivePost().getId()) - && reactivePost.getTitle().equals(getReactivePost().getTitle()) - && reactivePost.getContent().equals(getReactivePost().getContent())) + .expectNextMatches( + reactivePost -> + Objects.equals(reactivePost.getId(), getReactivePost().getId()) + && reactivePost + .getTitle() + .equals(getReactivePost().getTitle()) + && reactivePost + .getContent() + .equals(getReactivePost().getContent())) .expectComplete() .verify(); } @@ -74,20 +80,26 @@ void findReactivePostById() { void saveReactivePost() { // given ReactivePostRequest reactivePostRequest = getReactivePostRequest(); - ReactivePost mappedReactivePost = ReactivePost.builder() - .content(reactivePostRequest.content()) - .title(reactivePostRequest.title()) - .build(); - given(reactivePostMapper.mapToReactivePost(reactivePostRequest)).willReturn(mappedReactivePost); - given(reactivePostRepository.save(mappedReactivePost)).willReturn(Mono.just(getReactivePost())); + ReactivePost mappedReactivePost = + ReactivePost.builder() + .content(reactivePostRequest.content()) + .title(reactivePostRequest.title()) + .build(); + given(reactivePostMapper.mapToReactivePost(reactivePostRequest)) + .willReturn(mappedReactivePost); + given(reactivePostRepository.save(mappedReactivePost)) + .willReturn(Mono.just(getReactivePost())); // when - Mono persistedReactivePost = reactivePostService.saveReactivePost(reactivePostRequest); + Mono persistedReactivePost = + reactivePostService.saveReactivePost(reactivePostRequest); // then StepVerifier.create(persistedReactivePost) - .expectNextMatches(reactivePost -> reactivePost - .getTitle() - .equals(getReactivePost().getTitle()) - && reactivePost.getContent().equals(getReactivePost().getContent())) + .expectNextMatches( + reactivePost -> + reactivePost.getTitle().equals(getReactivePost().getTitle()) + && reactivePost + .getContent() + .equals(getReactivePost().getContent())) .expectComplete() .verify(); } diff --git a/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/web/controllers/ReactiveCommentsControllerIT.java b/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/web/controllers/ReactiveCommentsControllerIT.java index 01e3060b0..eaff513a8 100644 --- a/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/web/controllers/ReactiveCommentsControllerIT.java +++ b/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/web/controllers/ReactiveCommentsControllerIT.java @@ -22,69 +22,81 @@ class ReactiveCommentsControllerIT extends AbstractIntegrationTest { - @Autowired - private ReactiveCommentsRepository reactiveCommentsRepository; + @Autowired private ReactiveCommentsRepository reactiveCommentsRepository; - @Autowired - private ReactivePostRepository reactivePostRepository; + @Autowired private ReactivePostRepository reactivePostRepository; private Flux reactiveCommentsFlux; @BeforeEach void setUp() { - reactiveCommentsFlux = reactiveCommentsRepository - .deleteAll() - .then(reactivePostRepository.deleteAll()) - .then(reactivePostRepository - .save(ReactivePost.builder() - .title("title 1") - .content("content 1") - .build()) - .flatMap(reactivePost -> { - ReactiveComments comment1 = ReactiveComments.builder() - .title("First Title") - .content("First Content") - .postId(reactivePost.getId()) - .build(); - ReactiveComments comment2 = ReactiveComments.builder() - .title("Second Title") - .content("Second Content") - .postId(reactivePost.getId()) - .published(true) - .publishedAt(LocalDateTime.now()) - .build(); - ReactiveComments comment3 = ReactiveComments.builder() - .title("Third Title") - .content("Third Content") - .postId(reactivePost.getId()) - .build(); + reactiveCommentsFlux = + reactiveCommentsRepository + .deleteAll() + .then(reactivePostRepository.deleteAll()) + .then( + reactivePostRepository + .save( + ReactivePost.builder() + .title("title 1") + .content("content 1") + .build()) + .flatMap( + reactivePost -> { + ReactiveComments comment1 = + ReactiveComments.builder() + .title("First Title") + .content("First Content") + .postId(reactivePost.getId()) + .build(); + ReactiveComments comment2 = + ReactiveComments.builder() + .title("Second Title") + .content("Second Content") + .postId(reactivePost.getId()) + .published(true) + .publishedAt( + LocalDateTime.now()) + .build(); + ReactiveComments comment3 = + ReactiveComments.builder() + .title("Third Title") + .content("Third Content") + .postId(reactivePost.getId()) + .build(); - return reactiveCommentsRepository - .save(comment1) - .then(reactiveCommentsRepository.save(comment2)) - .then(reactiveCommentsRepository.save(comment3)) - .then(Mono.just(reactivePost)); - })) - .flatMapMany(post -> reactiveCommentsRepository.findAllByPostId(post.getId())); + return reactiveCommentsRepository + .save(comment1) + .then( + reactiveCommentsRepository.save( + comment2)) + .then( + reactiveCommentsRepository.save( + comment3)) + .then(Mono.just(reactivePost)); + })) + .flatMapMany( + post -> reactiveCommentsRepository.findAllByPostId(post.getId())); } @Test void shouldFetchAllReactiveComments() { // Fetch all posts using WebClient - List expectedPostComments = - reactiveCommentsFlux.collectList().block(); + List expectedPostComments = reactiveCommentsFlux.collectList().block(); this.webTestClient .mutate() // Mutate the client to add basic authentication headers .defaultHeaders(headers -> headers.setBasicAuth("user", "password")) .build() .get() - .uri(uriBuilder -> { - uriBuilder.queryParam("postId", expectedPostComments.get(0).getPostId()); - uriBuilder.queryParam("sortBy", "title"); - uriBuilder.path("/api/posts/comments/"); - return uriBuilder.build(); - }) + .uri( + uriBuilder -> { + uriBuilder.queryParam( + "postId", expectedPostComments.get(0).getPostId()); + uriBuilder.queryParam("sortBy", "title"); + uriBuilder.path("/api/posts/comments/"); + return uriBuilder.build(); + }) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus() @@ -93,7 +105,8 @@ void shouldFetchAllReactiveComments() { .contentType(MediaType.APPLICATION_JSON) .expectBodyList(ReactiveComments.class) .hasSize(expectedPostComments.size()) - .isEqualTo(expectedPostComments); // Ensure fetched comments match the expected comments + .isEqualTo(expectedPostComments); // Ensure fetched comments match the expected + // comments } @Test @@ -103,10 +116,11 @@ void shouldFindReactiveCommentsById() { this.webTestClient .mutate() // Mutate the client to add basic authentication headers - .defaultHeaders(headers -> { - headers.setBasicAuth("user", "password"); - headers.setContentType(MediaType.APPLICATION_JSON); - }) + .defaultHeaders( + headers -> { + headers.setBasicAuth("user", "password"); + headers.setContentType(MediaType.APPLICATION_JSON); + }) .build() .get() .uri("/api/posts/comments/{id}", reactiveCommentsId) @@ -130,13 +144,15 @@ void shouldCreateNewReactiveComments() { ReactiveComments reactiveComments = reactiveCommentsFlux.next().block(); Long reactivePostId = reactiveComments.getPostId(); ReactiveCommentRequest reactiveCommentRequest = - new ReactiveCommentRequest("New Title", "New ReactiveComments", reactivePostId, false); + new ReactiveCommentRequest( + "New Title", "New ReactiveComments", reactivePostId, false); this.webTestClient .mutate() // Mutate the client to add basic authentication headers - .defaultHeaders(headers -> { - headers.setBasicAuth("user", "password"); - headers.setContentType(MediaType.APPLICATION_JSON); - }) + .defaultHeaders( + headers -> { + headers.setBasicAuth("user", "password"); + headers.setContentType(MediaType.APPLICATION_JSON); + }) .build() .post() .uri("/api/posts/comments/") @@ -149,11 +165,12 @@ void shouldCreateNewReactiveComments() { .contentType(MediaType.APPLICATION_JSON) .expectBody() .jsonPath("$.id") - .value(returningId -> { - // Attempt to parse the value as a UUID - UUID uuid = UUID.fromString((String) returningId); - assertThat(uuid).isNotNull(); - }) + .value( + returningId -> { + // Attempt to parse the value as a UUID + UUID uuid = UUID.fromString((String) returningId); + assertThat(uuid).isNotNull(); + }) .jsonPath("$.title") .isEqualTo(reactiveCommentRequest.title()) .jsonPath("$.content") @@ -166,14 +183,16 @@ void shouldCreateNewReactiveComments() { @Test void shouldReturn400WhenCreateNewReactiveCommentsWithoutTitleAndContent() { - ReactiveCommentRequest reactiveCommentRequest = new ReactiveCommentRequest(null, null, -90L, false); + ReactiveCommentRequest reactiveCommentRequest = + new ReactiveCommentRequest(null, null, -90L, false); this.webTestClient .mutate() // Mutate the client to add basic authentication headers - .defaultHeaders(headers -> { - headers.setBasicAuth("user", "password"); - headers.setContentType(MediaType.APPLICATION_JSON); - }) + .defaultHeaders( + headers -> { + headers.setBasicAuth("user", "password"); + headers.setContentType(MediaType.APPLICATION_JSON); + }) .build() .post() .uri("/api/posts/comments/") @@ -228,15 +247,20 @@ void shouldReturn400WhenCreateNewReactiveCommentsWithoutTitleAndContent() { void shouldUpdateReactiveComments() { ReactiveComments reactiveComments = reactiveCommentsFlux.next().block(); UUID reactivePostId = reactiveComments.getId(); - ReactiveCommentRequest reactivePostRequest = new ReactiveCommentRequest( - "Updated ReactivePost", reactiveComments.getContent(), reactiveComments.getPostId(), true); + ReactiveCommentRequest reactivePostRequest = + new ReactiveCommentRequest( + "Updated ReactivePost", + reactiveComments.getContent(), + reactiveComments.getPostId(), + true); this.webTestClient .mutate() // Mutate the client to add basic authentication headers - .defaultHeaders(headers -> { - headers.setBasicAuth("user", "password"); - headers.setContentType(MediaType.APPLICATION_JSON); - }) + .defaultHeaders( + headers -> { + headers.setBasicAuth("user", "password"); + headers.setContentType(MediaType.APPLICATION_JSON); + }) .build() .put() .uri("/api/posts/comments/{id}", reactivePostId) diff --git a/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/web/controllers/ReactiveCommentsControllerTest.java b/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/web/controllers/ReactiveCommentsControllerTest.java index 3b3ea51d4..7bd27f535 100644 --- a/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/web/controllers/ReactiveCommentsControllerTest.java +++ b/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/web/controllers/ReactiveCommentsControllerTest.java @@ -32,56 +32,58 @@ @Import(SecurityConfig.class) // Import the security configuration class ReactiveCommentsControllerTest { - @Autowired - private WebTestClient webTestClient; + @Autowired private WebTestClient webTestClient; - @MockBean - private ReactiveCommentsService reactiveCommentsService; + @MockBean private ReactiveCommentsService reactiveCommentsService; private Flux reactiveCommentsFlux; @BeforeEach void setUp() { - ReactiveComments comment1 = ReactiveComments.builder() - .id(UUID.randomUUID()) - .title("First Title") - .content("First Content") - .postId(1L) - .build(); - ReactiveComments comment2 = ReactiveComments.builder() - .id(UUID.randomUUID()) - .title("Second Title") - .content("Second Content") - .postId(1L) - .published(true) - .publishedAt(LocalDateTime.now()) - .build(); - ReactiveComments comment3 = ReactiveComments.builder() - .id(UUID.randomUUID()) - .title("Third Title") - .content("Third Content") - .postId(1L) - .build(); + ReactiveComments comment1 = + ReactiveComments.builder() + .id(UUID.randomUUID()) + .title("First Title") + .content("First Content") + .postId(1L) + .build(); + ReactiveComments comment2 = + ReactiveComments.builder() + .id(UUID.randomUUID()) + .title("Second Title") + .content("Second Content") + .postId(1L) + .published(true) + .publishedAt(LocalDateTime.now()) + .build(); + ReactiveComments comment3 = + ReactiveComments.builder() + .id(UUID.randomUUID()) + .title("Third Title") + .content("Third Content") + .postId(1L) + .build(); reactiveCommentsFlux = Flux.fromIterable(List.of(comment1, comment2, comment3)); } @Test void shouldFetchAllReactiveComments() { // Fetch all posts using WebClient - List expectedCommentsList = - reactiveCommentsFlux.collectList().block(); + List expectedCommentsList = reactiveCommentsFlux.collectList().block(); given(reactiveCommentsService.findAllReactiveCommentsByPostId(1L, "title", "asc")) .willReturn(reactiveCommentsFlux); this.webTestClient .get() - .uri(uriBuilder -> { - uriBuilder.queryParam("postId", expectedCommentsList.get(0).getPostId()); - uriBuilder.queryParam("sortBy", "title"); - uriBuilder.path("/api/posts/comments/"); - return uriBuilder.build(); - }) + .uri( + uriBuilder -> { + uriBuilder.queryParam( + "postId", expectedCommentsList.get(0).getPostId()); + uriBuilder.queryParam("sortBy", "title"); + uriBuilder.path("/api/posts/comments/"); + return uriBuilder.build(); + }) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus() @@ -160,11 +162,12 @@ void shouldCreateNewReactiveComments() { .contentType(MediaType.APPLICATION_JSON) .expectBody() .jsonPath("$.id") - .value(returningId -> { - // Attempt to parse the value as a UUID - UUID uuid = UUID.fromString((String) returningId); - assertThat(uuid).isNotNull(); - }) + .value( + returningId -> { + // Attempt to parse the value as a UUID + UUID uuid = UUID.fromString((String) returningId); + assertThat(uuid).isNotNull(); + }) .jsonPath("$.title") .isEqualTo(reactiveCommentRequest.title()) .jsonPath("$.content") @@ -177,7 +180,8 @@ void shouldCreateNewReactiveComments() { @Test void shouldReturn400WhenCreateNewReactiveCommentsWithoutTitleAndContent() { - ReactiveCommentRequest reactiveCommentRequest = new ReactiveCommentRequest(null, null, -90L, false); + ReactiveCommentRequest reactiveCommentRequest = + new ReactiveCommentRequest(null, null, -90L, false); this.webTestClient .post() @@ -234,11 +238,18 @@ void shouldUpdateReactiveComments() { ReactiveComments reactiveComments = reactiveCommentsFlux.next().block(); reactiveComments.setTitle("Updated ReactivePost"); UUID reactivePostId = reactiveComments.getId(); - ReactiveCommentRequest reactivePostRequest = new ReactiveCommentRequest( - "Updated ReactivePost", reactiveComments.getContent(), reactiveComments.getPostId(), true); - - given(reactiveCommentsService.findReactiveCommentById(reactivePostId)).willReturn(Mono.just(reactiveComments)); - given(reactiveCommentsService.updateReactivePostComment(reactivePostRequest, reactiveComments)) + ReactiveCommentRequest reactivePostRequest = + new ReactiveCommentRequest( + "Updated ReactivePost", + reactiveComments.getContent(), + reactiveComments.getPostId(), + true); + + given(reactiveCommentsService.findReactiveCommentById(reactivePostId)) + .willReturn(Mono.just(reactiveComments)); + given( + reactiveCommentsService.updateReactivePostComment( + reactivePostRequest, reactiveComments)) .willReturn(Mono.just(reactiveComments)); this.webTestClient @@ -261,10 +272,15 @@ void shouldUpdateReactiveComments() { void shouldReturn404WhenUpdatingNonExistingReactiveComments() { ReactiveComments reactiveComments = reactiveCommentsFlux.next().block(); UUID reactivePostId = reactiveComments.getId(); - ReactiveCommentRequest reactivePostRequest = new ReactiveCommentRequest( - "Updated ReactivePost", reactiveComments.getContent(), reactiveComments.getPostId(), false); - - given(reactiveCommentsService.findReactiveCommentById(reactivePostId)).willReturn(Mono.empty()); + ReactiveCommentRequest reactivePostRequest = + new ReactiveCommentRequest( + "Updated ReactivePost", + reactiveComments.getContent(), + reactiveComments.getPostId(), + false); + + given(reactiveCommentsService.findReactiveCommentById(reactivePostId)) + .willReturn(Mono.empty()); this.webTestClient .put() diff --git a/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/web/controllers/ReactivePostControllerIT.java b/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/web/controllers/ReactivePostControllerIT.java index 50833e836..57fbbf91c 100644 --- a/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/web/controllers/ReactivePostControllerIT.java +++ b/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/web/controllers/ReactivePostControllerIT.java @@ -17,34 +17,34 @@ class ReactivePostControllerIT extends AbstractIntegrationTest { - @Autowired - private ReactivePostRepository reactivePostRepository; + @Autowired private ReactivePostRepository reactivePostRepository; - @Autowired - private ReactiveCommentsRepository reactiveCommentsRepository; + @Autowired private ReactiveCommentsRepository reactiveCommentsRepository; private Flux reactivePostFlux = null; @BeforeEach void setUp() { - reactivePostFlux = reactiveCommentsRepository - .deleteAll() - .then(reactivePostRepository.deleteAll()) - .thenMany(Flux.just( - ReactivePost.builder() - .title("title 1") - .content("content 1") - .build(), - ReactivePost.builder() - .title("title 2") - .content("content 2") - .build(), - ReactivePost.builder() - .title("title 3") - .content("content 3") - .build())) - .flatMap(reactivePostRepository::save) - .thenMany(reactivePostRepository.findAll()); + reactivePostFlux = + reactiveCommentsRepository + .deleteAll() + .then(reactivePostRepository.deleteAll()) + .thenMany( + Flux.just( + ReactivePost.builder() + .title("title 1") + .content("content 1") + .build(), + ReactivePost.builder() + .title("title 2") + .content("content 2") + .build(), + ReactivePost.builder() + .title("title 3") + .content("content 3") + .build())) + .flatMap(reactivePostRepository::save) + .thenMany(reactivePostRepository.findAll()); } @Test @@ -76,10 +76,11 @@ void shouldFindReactivePostById() { this.webTestClient .mutate() // Mutate the client to add basic authentication headers - .defaultHeaders(headers -> { - headers.setBasicAuth("user", "password"); - headers.setContentType(MediaType.APPLICATION_JSON); - }) + .defaultHeaders( + headers -> { + headers.setBasicAuth("user", "password"); + headers.setContentType(MediaType.APPLICATION_JSON); + }) .build() .get() .uri("/api/posts/{id}", reactivePostId) @@ -103,10 +104,11 @@ void shouldCreateNewReactivePost() { ReactivePostRequest reactivePost = new ReactivePostRequest("New Title", "New ReactivePost"); this.webTestClient .mutate() // Mutate the client to add basic authentication headers - .defaultHeaders(headers -> { - headers.setBasicAuth("user", "password"); - headers.setContentType(MediaType.APPLICATION_JSON); - }) + .defaultHeaders( + headers -> { + headers.setBasicAuth("user", "password"); + headers.setContentType(MediaType.APPLICATION_JSON); + }) .build() .post() .uri("/api/posts/") @@ -132,10 +134,11 @@ void shouldReturn400WhenCreateNewReactivePostWithoutTitleAndContent() { this.webTestClient .mutate() // Mutate the client to add basic authentication headers - .defaultHeaders(headers -> { - headers.setBasicAuth("user", "password"); - headers.setContentType(MediaType.APPLICATION_JSON); - }) + .defaultHeaders( + headers -> { + headers.setBasicAuth("user", "password"); + headers.setContentType(MediaType.APPLICATION_JSON); + }) .build() .post() .uri("/api/posts/") @@ -187,10 +190,11 @@ void shouldUpdateReactivePost() { this.webTestClient .mutate() // Mutate the client to add basic authentication headers - .defaultHeaders(headers -> { - headers.setBasicAuth("user", "password"); - headers.setContentType(MediaType.APPLICATION_JSON); - }) + .defaultHeaders( + headers -> { + headers.setBasicAuth("user", "password"); + headers.setContentType(MediaType.APPLICATION_JSON); + }) .build() .put() .uri("/api/posts/{id}", reactivePostId) diff --git a/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/web/controllers/ReactivePostControllerTest.java b/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/web/controllers/ReactivePostControllerTest.java index 5a27b0a6b..e0d0e65b3 100644 --- a/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/web/controllers/ReactivePostControllerTest.java +++ b/r2dbc/boot-r2dbc-sample/src/test/java/com/example/bootr2dbc/web/controllers/ReactivePostControllerTest.java @@ -33,32 +33,21 @@ @Import(SecurityConfig.class) // Import the security configuration class ReactivePostControllerTest { - @Autowired - private WebTestClient webTestClient; + @Autowired private WebTestClient webTestClient; - @MockBean - private ReactivePostService reactivePostService; + @MockBean private ReactivePostService reactivePostService; private Flux reactivePostFlux; @BeforeEach void setUp() { List reactivePostList = new ArrayList<>(); - reactivePostList.add(ReactivePost.builder() - .id(1L) - .title("title 1") - .content("content 1") - .build()); - reactivePostList.add(ReactivePost.builder() - .id(2L) - .title("title 2") - .content("content 2") - .build()); - reactivePostList.add(ReactivePost.builder() - .id(3L) - .title("title 3") - .content("content 3") - .build()); + reactivePostList.add( + ReactivePost.builder().id(1L).title("title 1").content("content 1").build()); + reactivePostList.add( + ReactivePost.builder().id(2L).title("title 2").content("content 2").build()); + reactivePostList.add( + ReactivePost.builder().id(3L).title("title 3").content("content 3").build()); reactivePostFlux = Flux.fromIterable(reactivePostList); } @@ -102,7 +91,8 @@ void shouldFindReactivePostById() { ReactivePost reactivePost = reactivePostFlux.next().block(); Long reactivePostId = reactivePost.getId(); - given(reactivePostService.findReactivePostById(reactivePostId)).willReturn(Mono.just(reactivePost)); + given(reactivePostService.findReactivePostById(reactivePostId)) + .willReturn(Mono.just(reactivePost)); this.webTestClient .get() @@ -142,7 +132,8 @@ void shouldReturn404WhenFetchingNonExistingReactivePost() { void shouldCreateNewReactivePost() { ReactivePostRequest reactivePost = new ReactivePostRequest("title 1", "content 1"); - given(reactivePostService.saveReactivePost(reactivePost)).willReturn(reactivePostFlux.next()); + given(reactivePostService.saveReactivePost(reactivePost)) + .willReturn(reactivePostFlux.next()); this.webTestClient .mutateWith(csrf()) @@ -221,7 +212,8 @@ void shouldUpdateReactivePost() { new ReactivePostRequest("Updated ReactivePost", reactivePost.getContent()); reactivePost.setTitle("Updated ReactivePost"); - given(reactivePostService.findReactivePostById(reactivePostId)).willReturn(Mono.just(reactivePost)); + given(reactivePostService.findReactivePostById(reactivePostId)) + .willReturn(Mono.just(reactivePost)); given(reactivePostService.updateReactivePost(reactivePostRequest, reactivePost)) .willReturn(Mono.just(reactivePost)); @@ -246,7 +238,8 @@ void shouldUpdateReactivePost() { @Test void shouldReturn404WhenUpdatingNonExistingReactivePost() { - ReactivePostRequest reactivePostRequest = new ReactivePostRequest("Updated ReactivePost", "Updated Content"); + ReactivePostRequest reactivePostRequest = + new ReactivePostRequest("Updated ReactivePost", "Updated Content"); Long reactivePostId = 1000L; given(reactivePostService.findReactivePostById(reactivePostId)).willReturn(Mono.empty());