Skip to content

Commit

Permalink
format using palantir
Browse files Browse the repository at this point in the history
  • Loading branch information
rajadilipkolli committed Jan 7, 2025
1 parent 4875365 commit b6c8e3d
Show file tree
Hide file tree
Showing 39 changed files with 252 additions and 345 deletions.
7 changes: 3 additions & 4 deletions batch-boot-jpa-sample/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -242,10 +242,9 @@
<version>${spotless.version}</version>
<configuration>
<java>
<googleJavaFormat>
<version>1.25.2</version>
<style>AOSP</style>
</googleJavaFormat>
<palantirJavaFormat>
<version>2.50.0</version>
</palantirJavaFormat>
<importOrder />
<removeUnusedImports />
<formatAnnotations />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
@ConfigurationProperties("application")
public class ApplicationProperties {

@NestedConfigurationProperty private Cors cors = new Cors();
@NestedConfigurationProperty
private Cors cors = new Cors();

public Cors getCors() {
return cors;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,17 @@ 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(getCustomerCustomerDTOItemProcessor())
.writer(getCustomerDTOItemWriter())
.faultTolerant() // tell to spring batch that this step can face errors
.skip(Exception.class) // skip all Exception
.noSkip(ConstraintViolationException.class) // but do not skip this one
.skipLimit(20) // the number of times you want to skip Exception.class
.build();
Step step = new StepBuilder("all-customers-step", jobRepository)
.allowStartIfComplete(true)
.<Customer, CustomerDTO>chunk(10, transactionManager)
.reader(jpaPagingItemReader)
.processor(getCustomerCustomerDTOItemProcessor())
.writer(getCustomerDTOItemWriter())
.faultTolerant() // tell to spring batch that this step can face errors
.skip(Exception.class) // skip all Exception
.noSkip(ConstraintViolationException.class) // but do not skip this one
.skipLimit(20) // the number of times you want to skip Exception.class
.build();

return new JobBuilder("all-customers-job", jobRepository)
.start(step)
Expand All @@ -76,8 +75,7 @@ private ItemWriter<CustomerDTO> getCustomerDTOItemWriter() {
}

private ItemProcessor<Customer, CustomerDTO> getCustomerCustomerDTOItemProcessor() {
return customer ->
new CustomerDTO(customer.getName(), customer.getAddress(), customer.getGender());
return customer -> new CustomerDTO(customer.getName(), customer.getAddress(), customer.getGender());
}

@Bean
Expand All @@ -91,8 +89,7 @@ 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 @@ -22,23 +22,19 @@ 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 @@ -24,13 +24,11 @@ class Initializer implements CommandLineRunner {
@Override
public void run(String... args) {
log.info("Running Initializer.....");
List<Customer> customerList =
Instancio.ofList(Customer.class)
.size(1000)
.ignore(field(Customer.class, "id"))
.generate(
field(Customer.class, "gender"), gen -> gen.oneOf("male", "female"))
.create();
List<Customer> customerList = Instancio.ofList(Customer.class)
.size(1000)
.ignore(field(Customer.class, "id"))
.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,7 +6,5 @@
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 = "/"))
class SwaggerConfig {}
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ public class Customer {
private Long id;

@Column(nullable = false)
@NotEmpty(message = "Name cannot be empty")
private String name;
@NotEmpty(message = "Name cannot be empty") private String name;

private String address;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,10 @@ public CustomerService(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}

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 @@ -11,7 +11,6 @@ public final class AppConstants {
public static final String DEFAULT_SORT_DIRECTION = "asc";

private AppConstants() {
throw new UnsupportedOperationException(
"This is a utility class and cannot be instantiated");
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,23 +30,17 @@ class CustomerController {

@GetMapping
PagedResult<Customer> getAllCustomers(
@RequestParam(defaultValue = AppConstants.DEFAULT_PAGE_NUMBER, required = false)
int pageNo,
@RequestParam(defaultValue = AppConstants.DEFAULT_PAGE_SIZE, required = false)
int pageSize,
@RequestParam(defaultValue = AppConstants.DEFAULT_SORT_BY, required = false)
String sortBy,
@RequestParam(defaultValue = AppConstants.DEFAULT_SORT_DIRECTION, required = false)
String sortDir) {
@RequestParam(defaultValue = AppConstants.DEFAULT_PAGE_NUMBER, required = false) int pageNo,
@RequestParam(defaultValue = AppConstants.DEFAULT_PAGE_SIZE, required = false) int pageSize,
@RequestParam(defaultValue = AppConstants.DEFAULT_SORT_BY, required = false) String sortBy,
@RequestParam(defaultValue = AppConstants.DEFAULT_SORT_DIRECTION, required = false) String sortDir) {
return customerService.findAllCustomers(pageNo, pageSize, sortBy, sortDir);
}

@GetMapping("/{id}")
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 @@ -59,23 +53,21 @@ Customer createCustomer(@RequestBody @Validated Customer customer) {
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}")
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 @@ -27,14 +27,12 @@ class JobInvokerController {
}

@GetMapping("/customers")
String allCustomersJobHandle(@RequestParam Long minId, @RequestParam Long maxId)
throws Exception {

JobParameters jobParameters =
new JobParametersBuilder()
.addLong("minId", minId)
.addLong("maxId", maxId)
.toJobParameters();
String allCustomersJobHandle(@RequestParam Long minId, @RequestParam Long maxId) throws Exception {

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 @@ -6,6 +6,8 @@
public class TestBatchApplication {

public static void main(String[] args) {
SpringApplication.from(BatchApplication::main).with(ContainersConfig.class).run(args);
SpringApplication.from(BatchApplication::main)
.with(ContainersConfig.class)
.run(args);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,14 @@
@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,12 @@
@AutoConfigureMockMvc
public abstract class AbstractIntegrationTest {

@Autowired protected MockMvc mockMvc;
@Autowired
protected MockMvc mockMvc;

@Autowired protected MockMvcTester mockMvcTester;
@Autowired
protected MockMvcTester mockMvcTester;

@Autowired protected ObjectMapper objectMapper;
@Autowired
protected ObjectMapper objectMapper;
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
@AutoConfigureTestDatabase
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,9 +25,11 @@
@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,21 +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)
.ignore(field(Customer.class, "id"))
.generate(
field(Customer.class, "gender"), gen -> gen.oneOf("male", "female"))
.create();
customerList = Instancio.ofList(Customer.class)
.size(3)
.ignore(field(Customer.class, "id"))
.generate(field(Customer.class, "gender"), gen -> gen.oneOf("male", "female"))
.create();

customerList = customerRepository.saveAll(customerList);
}
Expand Down Expand Up @@ -75,10 +74,9 @@ void shouldCreateNewCustomer() throws Exception {
Customer customer = Instancio.create(Customer.class);
customer.setId(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().isCreated())
.andExpect(jsonPath("$.id", notNullValue()))
.andExpect(jsonPath("$.name", is(customer.getName())));
Expand All @@ -89,10 +87,9 @@ void shouldReturn400WhenCreateNewCustomerWithoutName() 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 @@ -112,10 +109,9 @@ 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 b6c8e3d

Please sign in to comment.