Skip to content

Commit 3146f08

Browse files
committed
Sping Boot REST api validation
1 parent e0a1d15 commit 3146f08

File tree

11 files changed

+262
-0
lines changed

11 files changed

+262
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>com.hellokoding.springboot</groupId>
8+
<artifactId>springboot-restapi-validation</artifactId>
9+
<version>1.0-SNAPSHOT</version>
10+
11+
<parent>
12+
<groupId>org.springframework.boot</groupId>
13+
<artifactId>spring-boot-starter-parent</artifactId>
14+
<version>2.1.4.RELEASE</version>
15+
</parent>
16+
17+
<properties>
18+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
19+
<java.version>1.8</java.version>
20+
<org.apache.maven.plugins.version>3.6.0</org.apache.maven.plugins.version>
21+
</properties>
22+
23+
<dependencies>
24+
<dependency>
25+
<groupId>org.springframework.boot</groupId>
26+
<artifactId>spring-boot-starter-web</artifactId>
27+
</dependency>
28+
<dependency>
29+
<groupId>org.springframework.boot</groupId>
30+
<artifactId>spring-boot-starter-validation</artifactId>
31+
</dependency>
32+
<dependency>
33+
<groupId>org.springframework.boot</groupId>
34+
<artifactId>spring-boot-starter-data-jpa</artifactId>
35+
</dependency>
36+
<dependency>
37+
<groupId>org.projectlombok</groupId>
38+
<artifactId>lombok</artifactId>
39+
</dependency>
40+
<dependency>
41+
<groupId>org.hsqldb</groupId>
42+
<artifactId>hsqldb</artifactId>
43+
</dependency>
44+
</dependencies>
45+
46+
<build>
47+
<plugins>
48+
<plugin>
49+
<groupId>org.springframework.boot</groupId>
50+
<artifactId>spring-boot-maven-plugin</artifactId>
51+
</plugin>
52+
</plugins>
53+
</build>
54+
</project>
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package com.hellokoding.springboot.restful;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication
7+
public class Application {
8+
public static void main(String[] args) {
9+
SpringApplication.run(Application.class, args);
10+
}
11+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.hellokoding.springboot.restful;
2+
3+
import lombok.RequiredArgsConstructor;
4+
import lombok.extern.slf4j.Slf4j;
5+
import org.springframework.http.HttpHeaders;
6+
import org.springframework.http.HttpStatus;
7+
import org.springframework.http.ResponseEntity;
8+
import org.springframework.web.bind.MethodArgumentNotValidException;
9+
import org.springframework.web.bind.annotation.ControllerAdvice;
10+
import org.springframework.web.context.request.WebRequest;
11+
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
12+
13+
@ControllerAdvice
14+
@Slf4j
15+
@RequiredArgsConstructor
16+
public class ExceptionHandler extends ResponseEntityExceptionHandler {
17+
@Override
18+
protected ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
19+
log.error(ex.getMessage(), ex);
20+
21+
ResponseDTO responseDTO = ResponseDTO.builder()
22+
.status(status.toString())
23+
.message(ex.getBindingResult().getFieldError().getDefaultMessage())
24+
.body(ex.getBindingResult().getTarget()).build();
25+
26+
return ResponseEntity.badRequest().body(responseDTO);
27+
}
28+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package com.hellokoding.springboot.restful;
2+
3+
import lombok.Builder;
4+
import lombok.Data;
5+
6+
@Data
7+
@Builder
8+
public class ResponseDTO<T> {
9+
private String status;
10+
private String message;
11+
private T body;
12+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.hellokoding.springboot.restful.product;
2+
3+
import lombok.Data;
4+
5+
import javax.persistence.Entity;
6+
import javax.persistence.GeneratedValue;
7+
import javax.persistence.GenerationType;
8+
import javax.persistence.Id;
9+
import javax.validation.constraints.Min;
10+
import javax.validation.constraints.NotNull;
11+
import javax.validation.constraints.Size;
12+
import java.math.BigDecimal;
13+
14+
@Data
15+
@Entity
16+
public class Product {
17+
@Id
18+
@GeneratedValue(strategy = GenerationType.IDENTITY)
19+
@ProductIDExisting
20+
private Long id;
21+
22+
@NotNull(message = "{NotNull.name}")
23+
private String name;
24+
25+
@Size(max = 100)
26+
private String description;
27+
28+
@Min(1)
29+
private BigDecimal price;
30+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.hellokoding.springboot.restful.product;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.http.HttpStatus;
5+
import org.springframework.http.ResponseEntity;
6+
import org.springframework.web.bind.annotation.*;
7+
8+
import javax.validation.Valid;
9+
import java.util.List;
10+
11+
12+
@RestController
13+
@RequestMapping("/api/v1/products")
14+
public class ProductAPI {
15+
private final ProductService productService;
16+
17+
@Autowired
18+
public ProductAPI(ProductService productService) {
19+
this.productService = productService;
20+
}
21+
22+
@GetMapping
23+
public ResponseEntity<List<Product>> findAll() {
24+
return ResponseEntity.ok(productService.findAll());
25+
}
26+
27+
@GetMapping("/{id}")
28+
public ResponseEntity<Product> findById(@PathVariable @ProductIDExisting Long id) {
29+
return ResponseEntity.ok(productService.findById(id).get());
30+
}
31+
32+
@PostMapping
33+
public ResponseEntity<Product> create(@Valid @RequestBody Product product) {
34+
return ResponseEntity.status(HttpStatus.CREATED).body(productService.save(product));
35+
}
36+
37+
@PutMapping("/{id}")
38+
public ResponseEntity<Product> update(@PathVariable Long id, @Valid @RequestBody Product product) {
39+
return ResponseEntity.accepted().body(productService.save(product));
40+
}
41+
42+
@DeleteMapping("/{id}")
43+
public ResponseEntity delete(@PathVariable @ProductIDExisting Long id) {
44+
productService.deleteById(id);
45+
46+
return ResponseEntity.accepted().build();
47+
}
48+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.hellokoding.springboot.restful.product;
2+
3+
import javax.validation.Constraint;
4+
import javax.validation.Payload;
5+
import java.lang.annotation.*;
6+
7+
@Documented
8+
@Retention(RetentionPolicy.RUNTIME)
9+
@Target({ElementType.FIELD, ElementType.PARAMETER})
10+
@Constraint(validatedBy = ProductIDExistingValidator.class)
11+
public @interface ProductIDExisting {
12+
String message() default "{ProductIDExisting}";
13+
14+
Class<?>[] groups() default { };
15+
16+
Class<? extends Payload>[] payload() default { };
17+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.hellokoding.springboot.restful.product;
2+
3+
import lombok.NoArgsConstructor;
4+
import org.springframework.beans.factory.annotation.Autowired;
5+
import org.springframework.stereotype.Component;
6+
7+
import javax.validation.ConstraintValidator;
8+
import javax.validation.ConstraintValidatorContext;
9+
import java.util.Objects;
10+
11+
@Component
12+
@NoArgsConstructor
13+
public class ProductIDExistingValidator implements ConstraintValidator<ProductIDExisting, Long> {
14+
@Autowired
15+
private ProductService productService;
16+
17+
@Override
18+
public boolean isValid(Long productId, ConstraintValidatorContext context) {
19+
return Objects.isNull(productId) || productService.findById(productId).isPresent();
20+
}
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
package com.hellokoding.springboot.restful.product;
2+
3+
import org.springframework.data.jpa.repository.JpaRepository;
4+
5+
public interface ProductRepository extends JpaRepository<Product, Long> {
6+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.hellokoding.springboot.restful.product;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.stereotype.Service;
5+
6+
import java.util.List;
7+
import java.util.Optional;
8+
9+
@Service
10+
public class ProductService {
11+
private final ProductRepository productRepository;
12+
13+
@Autowired
14+
public ProductService(ProductRepository productRespository) {
15+
this.productRepository = productRespository;
16+
}
17+
18+
public List<Product> findAll() {
19+
return productRepository.findAll();
20+
}
21+
22+
public Optional<Product> findById(Long id) {
23+
return productRepository.findById(id);
24+
}
25+
26+
public Product save(Product stock) {
27+
return productRepository.save(stock);
28+
}
29+
30+
public void deleteById(Long id) {
31+
productRepository.deleteById(id);
32+
}
33+
}

0 commit comments

Comments
 (0)