Skip to content

Commit 0bd28a3

Browse files
committed
Validation and Exception handling
1 parent ca529bf commit 0bd28a3

19 files changed

+472
-3
lines changed

pom.xml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@
2525
<groupId>org.springframework.boot</groupId>
2626
<artifactId>spring-boot-starter-data-jpa</artifactId>
2727
</dependency>
28+
<dependency>
29+
<groupId>org.springframework.boot</groupId>
30+
<artifactId>spring-boot-starter-validation</artifactId>
31+
</dependency>
2832
<dependency>
2933
<groupId>com.h2database</groupId>
3034
<artifactId>h2</artifactId>
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.rajeshkawali.controller;
2+
3+
import com.rajeshkawali.model.EmployeeDTO;
4+
import com.rajeshkawali.model.Person;
5+
import com.rajeshkawali.service.EmployeeService;
6+
import jakarta.validation.Valid;
7+
import lombok.extern.slf4j.Slf4j;
8+
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.http.HttpStatus;
10+
import org.springframework.http.ResponseEntity;
11+
import org.springframework.web.bind.annotation.*;
12+
13+
import java.util.List;
14+
15+
/**
16+
* @author Rajesh_Kawali
17+
*/
18+
@Slf4j
19+
@RestController
20+
@RequestMapping("/api")
21+
public class EmployeeController {
22+
23+
public static final String CLASS_NAME = EmployeeController.class.getName();
24+
@Autowired
25+
private EmployeeService service;
26+
27+
@PostMapping("/addEmployee")
28+
public ResponseEntity<EmployeeDTO> addEmployee(@RequestBody @Valid EmployeeDTO employee) {
29+
String _function = ".addEmployee";
30+
log.info(CLASS_NAME + _function + "::ENTER");
31+
EmployeeDTO employeeDTO = service.addEmployee(employee);
32+
log.info(CLASS_NAME + _function + "::EXIT");
33+
return ResponseEntity.status(HttpStatus.CREATED).body(employeeDTO);
34+
}
35+
36+
@GetMapping(value = "/getAllEmployee")
37+
public List<EmployeeDTO> getAllEmployee() {
38+
String _function = ".getAllEmployee";
39+
log.info(CLASS_NAME + _function + "::ENTER");
40+
return service.getAllEmployee();
41+
}
42+
43+
@GetMapping(value = "/findByEmployeeId/{id}")
44+
public EmployeeDTO findByEmployeeId(@PathVariable Long id) {
45+
String _function = ".findByEmployeeId";
46+
log.info(CLASS_NAME + _function + "::ENTER");
47+
return service.findByEmployeeId(id);
48+
}
49+
50+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.rajeshkawali.entity;
2+
3+
import com.fasterxml.jackson.annotation.JsonFormat;
4+
import jakarta.persistence.*;
5+
import jakarta.validation.constraints.*;
6+
import lombok.AllArgsConstructor;
7+
import lombok.Data;
8+
import lombok.NoArgsConstructor;
9+
10+
import java.util.Date;
11+
12+
/**
13+
* @author Rajesh_Kawali
14+
*/
15+
@Data
16+
@AllArgsConstructor
17+
@NoArgsConstructor
18+
@Entity
19+
@Table(name = "employee")
20+
public class Employee {
21+
22+
@Id
23+
@GeneratedValue(strategy = GenerationType.AUTO)
24+
private Long id;
25+
26+
@Column(name = "firstName")
27+
private String firstName;
28+
29+
@Column(name = "lastName")
30+
private String lastName;
31+
32+
@Column(name = "doj")
33+
private Date doj;
34+
35+
@Column(name = "dept")
36+
private String dept;
37+
38+
@Column(name = "email")
39+
private String email;
40+
41+
@Column(name = "mobile")
42+
private String mobile;
43+
44+
@Column(name = "gender")
45+
private String gender;
46+
47+
@Column(name = "age")
48+
private int age;
49+
50+
@Column(name = "aboutMe", length = 500)
51+
private String aboutMe;
52+
53+
@Column(name = "nationality")
54+
private String nationality;
55+
56+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.rajeshkawali.exception;
2+
3+
import org.springframework.http.HttpStatus;
4+
import org.springframework.web.bind.MethodArgumentNotValidException;
5+
import org.springframework.web.bind.annotation.ExceptionHandler;
6+
import org.springframework.web.bind.annotation.ResponseStatus;
7+
import org.springframework.web.bind.annotation.RestControllerAdvice;
8+
9+
import java.util.HashMap;
10+
import java.util.Map;
11+
12+
/**
13+
* @author Rajesh_Kawali
14+
*/
15+
16+
@RestControllerAdvice
17+
public class ApplicationExceptionHandler {
18+
19+
@ResponseStatus(HttpStatus.BAD_REQUEST)
20+
@ExceptionHandler(MethodArgumentNotValidException.class)
21+
public Map<String, String> handleInvalidArgument(MethodArgumentNotValidException ex) {
22+
Map<String, String> errorMap = new HashMap<>();
23+
ex.getBindingResult().getFieldErrors().forEach(error -> {
24+
errorMap.put(error.getField(), error.getDefaultMessage());
25+
});
26+
return errorMap;
27+
}
28+
29+
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
30+
@ExceptionHandler(EmployeeNotFoundException.class)
31+
public Map<String, String> handleBusinessException(EmployeeNotFoundException ex) {
32+
Map<String, String> errorMap = new HashMap<>();
33+
errorMap.put("errorMessage", ex.getMessage());
34+
return errorMap;
35+
}
36+
37+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.rajeshkawali.exception;
2+
/**
3+
* @author Rajesh_Kawali
4+
*
5+
*/
6+
public class EmployeeNotFoundException extends Exception {
7+
8+
public EmployeeNotFoundException() {
9+
super();
10+
}
11+
12+
public EmployeeNotFoundException(String message) {
13+
super(message);
14+
}
15+
}

src/main/java/com/rajeshkawali/lombok/Actor.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@
77
import lombok.experimental.SuperBuilder;
88

99
import java.util.List;
10-
10+
/**
11+
* @author Rajesh_Kawali
12+
*/
1113
@Data
1214
@SuperBuilder
1315
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)

src/main/java/com/rajeshkawali/lombok/Address.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
import lombok.*;
44

5+
/**
6+
* @author Rajesh_Kawali
7+
*/
58
@ToString(includeFieldNames = false) // includeFieldNames = false --> field name will not add while printing the object
69
@EqualsAndHashCode
710
@Getter

src/main/java/com/rajeshkawali/lombok/ImmutableClass.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33

44
import lombok.Value;
5+
6+
/**
7+
* @author Rajesh_Kawali
8+
*/
59
/*
610
@Value annotation -->is shorthand for the annotation combination of
711
@Getter

src/main/java/com/rajeshkawali/lombok/LombokCleanup.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66

77
import java.io.*;
88

9+
/**
10+
* @author Rajesh_Kawali
11+
*/
912
public class LombokCleanup {
1013
public static void main(String[] args) throws IOException {
1114

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package com.rajeshkawali.model;
2+
3+
import com.fasterxml.jackson.annotation.JsonFormat;
4+
import com.rajeshkawali.validation.GenderEitherOneOf;
5+
import com.rajeshkawali.validation.ValidateNationality;
6+
import jakarta.validation.constraints.*;
7+
import lombok.AllArgsConstructor;
8+
import lombok.Data;
9+
import lombok.NoArgsConstructor;
10+
11+
import java.util.Date;
12+
13+
/**
14+
* @author Rajesh_Kawali
15+
*/
16+
@Data
17+
@AllArgsConstructor
18+
@NoArgsConstructor
19+
public class EmployeeDTO {
20+
21+
private Long id;
22+
23+
@NotBlank(message = "First Name shouldn't be null or empty")
24+
private String firstName;
25+
26+
@NotBlank(message = "Last Name shouldn't be null or empty")
27+
private String lastName;
28+
29+
@PastOrPresent(message = "DOJ should be in the past or the past including the present")
30+
@JsonFormat(pattern = "dd-MM-yyyy")
31+
private Date doj;
32+
33+
@NotNull(message = "Department shouldn't be null")
34+
@NotEmpty(message = "Department shouldn't be empty")
35+
private String dept;
36+
37+
@Email(message = "Invalid email")
38+
private String email;
39+
40+
@Pattern(regexp = "^\\d{10}$",message = "Invalid mobile number")
41+
private String mobile;
42+
43+
//custom annotation
44+
@GenderEitherOneOf({"male", "female"})
45+
private String gender; // male or female
46+
47+
@Min(value = 18, message = "Age should not be less than 18")
48+
@Max(value = 60, message = "Age should not be greater than 60")
49+
private int age;
50+
51+
@Size(min = 10, max = 500, message = "About Me must be between 10 and 500 characters")
52+
private String aboutMe;
53+
54+
@ValidateNationality //custom annotation
55+
private String nationality; //Indian or American or Canadian or British or French or German or Japanese
56+
57+
}
58+
/*
59+
All the annotations are standard JSR annotations:
60+
61+
@NotNull :--> validates that the annotated property value is not null.
62+
@AssertTrue :--> validates that the annotated property value is true.
63+
@Size :--> validates that the annotated property value has a size between the attributes min and max; can be applied to String, Collection, Map, and array properties.
64+
@Min :--> validates that the annotated property has a value no smaller than the value attribute.
65+
@Max :--> validates that the annotated property has a value no larger than the value attribute.
66+
@Email :--> validates that the annotated property is a valid email address.
67+
@NotEmpty :--> validates that the property is not null or empty; can be applied to String, Collection, Map or Array values.
68+
@NotBlank :--> can be applied only to text values and validates that the property is not null or whitespace.
69+
@Positive and @PositiveOrZero :--> apply to numeric values and validate that they are strictly positive, or positive including 0.
70+
@Negative and @NegativeOrZero :--> apply to numeric values and validate that they are strictly negative, or negative including 0.
71+
@Past and @PastOrPresent :--> validate that a date value is in the past or the past including the present; can be applied to date types including those added in Java 8.
72+
@Future and @FutureOrPresent :--> validate that a date value is in the future, or in the future including the present.
73+
*/

0 commit comments

Comments
 (0)