Skip to content

Commit

Permalink
#876 - preparation for upgrading to Java 21
Browse files Browse the repository at this point in the history
we need to change to spotless 1.17.0 to work with java 21
  • Loading branch information
rajadilipkolli committed Oct 5, 2023
1 parent 3d43638 commit 676555d
Show file tree
Hide file tree
Showing 50 changed files with 831 additions and 610 deletions.
7 changes: 4 additions & 3 deletions batch-boot-jpa-sample/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -246,9 +246,10 @@
<version>${spotless.version}</version>
<configuration>
<java>
<palantirJavaFormat>
<version>2.30.0</version>
</palantirJavaFormat>
<googleJavaFormat>
<version>1.17.0</version>
<style>AOSP</style>
</googleJavaFormat>
<importOrder />
<removeUnusedImports />
<formatAnnotations />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,29 @@ Job allCustomersJob(
JpaPagingItemReader<Customer> jpaPagingItemReader,
JobRepository jobRepository,
PlatformTransactionManager transactionManager) {
Step step = new StepBuilder("all-customers-step", jobRepository)
.allowStartIfComplete(true)
.<Customer, CustomerDTO>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)
.<Customer, CustomerDTO>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)
Expand All @@ -66,7 +78,8 @@ JpaPagingItemReader<Customer> jpaPagingItemReader(
return new JpaPagingItemReaderBuilder<Customer>()
.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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<ApiValidationError> 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<ApiValidationError> 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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@ public class Initializer implements CommandLineRunner {
@Override
public void run(String... args) {
log.info("Running Initializer.....");
List<Customer> customerList = Instancio.ofList(Customer.class)
.size(1000)
.generate(field(Customer.class, "gender"), gen -> gen.oneOf("male", "female"))
.create();
List<Customer> 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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ public class CustomerService {
private final CustomerRepository customerRepository;

@Transactional(readOnly = true)
public PagedResult<Customer> 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<Customer> 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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,21 +28,35 @@ public class CustomerController {

@GetMapping
public PagedResult<Customer> 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<Customer> 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
Expand All @@ -52,24 +66,27 @@ public Customer createCustomer(@RequestBody @Validated Customer customer) {
}

@PutMapping("/{id}")
public ResponseEntity<Customer> updateCustomer(@PathVariable Long id, @RequestBody Customer customer) {
public ResponseEntity<Customer> 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());
}

@DeleteMapping("/{id}")
public ResponseEntity<Customer> 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());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class SchemaValidationTest {

@Autowired
private DataSource dataSource;
@Autowired private DataSource dataSource;

@Test
void contextLoads() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,20 @@

class CustomerControllerIT extends AbstractIntegrationTest {

@Autowired
private CustomerRepository customerRepository;
@Autowired private CustomerRepository customerRepository;

private List<Customer> customerList = null;

@BeforeEach
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);
}
Expand Down Expand Up @@ -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())));
Expand All @@ -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")))
Expand All @@ -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")));
Expand Down
Loading

0 comments on commit 676555d

Please sign in to comment.