Skip to content

Commit c73978e

Browse files
committed
Comoplete java validation & Exception Handling
1 parent 0759ac0 commit c73978e

13 files changed

+125
-362
lines changed

pom.xml

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
<name>SpringBootBackEnd</name>
1616
<description>Demo project for Spring Boot</description>
1717
<properties>
18-
<java.version>11</java.version>
18+
<java.version>1.8</java.version>
1919
</properties>
2020
<dependencies>
2121
<dependency>
@@ -46,11 +46,6 @@
4646
<artifactId>mysql-connector-java</artifactId>
4747
<scope>runtime</scope>
4848
</dependency>
49-
<dependency>
50-
<groupId>org.springframework.boot</groupId>
51-
<artifactId>spring-boot-starter-tomcat</artifactId>
52-
<scope>provided</scope>
53-
</dependency>
5449
<dependency>
5550
<groupId>org.springframework.boot</groupId>
5651
<artifactId>spring-boot-starter-test</artifactId>

src/main/java/com/example/ServletInitializer.java

Lines changed: 0 additions & 13 deletions
This file was deleted.

src/main/java/com/example/advice/ExeptionHendler.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.example.advice;
22

3+
import com.example.exception.UserNotFoundException;
34
import org.springframework.http.HttpStatus;
45
import org.springframework.web.bind.MethodArgumentNotValidException;
56
import org.springframework.web.bind.annotation.ExceptionHandler;
@@ -21,5 +22,15 @@ public Map<String, String> InvalidArgumentHandler(MethodArgumentNotValidExceptio
2122
});
2223
return errorMap;
2324
}
25+
26+
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
27+
@ExceptionHandler(UserNotFoundException.class)
28+
public Map<String, String> handleBusinessExecution(UserNotFoundException exception){
29+
Map<String, String> errorMap = new HashMap<>();
30+
31+
errorMap.put("errorMessage", exception.getMessage());
32+
33+
return errorMap;
34+
}
2435
}
2536

src/main/java/com/example/controller/LoginController.java

Lines changed: 0 additions & 71 deletions
This file was deleted.
Lines changed: 19 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -1,111 +1,37 @@
11
package com.example.controller;
22

3+
import com.example.dto.UserRequest;
34
import com.example.exception.UserNotFoundException;
4-
import org.slf4j.Logger;
5-
import org.slf4j.LoggerFactory;
5+
import com.example.model.User;
6+
import com.example.service.UserService;
67
import org.springframework.beans.factory.annotation.Autowired;
78
import org.springframework.http.HttpStatus;
89
import org.springframework.http.ResponseEntity;
9-
import org.springframework.web.bind.annotation.CrossOrigin;
10-
import org.springframework.web.bind.annotation.PostMapping;
11-
import org.springframework.web.bind.annotation.RequestBody;
12-
import org.springframework.web.bind.annotation.RequestMapping;
13-
import org.springframework.web.bind.annotation.RestController;
14-
15-
import com.example.model.User;
16-
import com.example.service.MyService;
17-
import com.example.utilities.ApiResponse;
18-
import com.example.utilities.MyConstant;
10+
import org.springframework.web.bind.annotation.*;
1911

2012
import javax.validation.Valid;
13+
import java.util.List;
2114

2215
@RestController
2316
@RequestMapping("api/v1/user")
24-
@CrossOrigin(origins = "*")
2517
public class UserContoller {
26-
Logger log = LoggerFactory.getLogger(UserContoller.class);
27-
28-
private final MyService service;
29-
private final ApiResponse res;
3018

31-
@Autowired
32-
public UserContoller(MyService service, ApiResponse res) {
33-
this.service = service;
34-
this.res = res;
35-
}
19+
@Autowired
20+
private UserService service;
3621

37-
@PostMapping("/save")
38-
public ResponseEntity<?> save(@RequestBody @Valid User payload) {
39-
log.info("Invoke User save api[save(@RequestBody User payload)]");
40-
try {
41-
User dbUser = service.getUserByUserId(payload.getUserId());
42-
if (dbUser == null) {
43-
User user = service.saveUser(payload);
44-
res.setMessage("Registration Successful with User ID: " + user.getUserId().toString());
45-
res.setStatus(MyConstant.SUCCESS);
46-
res.setData(user);
47-
log.info(res.getMessage() + " with UserId : " + payload.getUserId());
48-
return ResponseEntity.ok(res);
49-
} else {
50-
res.setMessage("userId already in use");
51-
res.setStatus(MyConstant.FAILED);
52-
res.setData(null);
53-
log.error(res.getMessage() + " with UserId : " + payload.getUserId());
54-
return ResponseEntity.status(HttpStatus.CONFLICT).body(res);
55-
}
56-
} catch (Exception e) {
57-
res.setMessage(e.getMessage());
58-
res.setStatus(MyConstant.FAILED);
59-
res.setData(null);
60-
log.error("Sarver error: " + res.getMessage());
61-
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(res);
62-
}
63-
}
22+
@PostMapping
23+
public ResponseEntity<User> saveUserEntity(@RequestBody @Valid UserRequest request){
24+
return new ResponseEntity<>(service.saveUser(request), HttpStatus.CREATED);
25+
}
6426

65-
@PostMapping("/forgetPass")
66-
public ResponseEntity<?> matchUser(@RequestBody @Valid User payload) throws UserNotFoundException {
67-
log.info("Invoke api for match userId[matchUser(@RequestBody User payload)]");
68-
try {
69-
User dbUser = service.getUserByUserId(payload.getUserId());
70-
if (dbUser == null) {
71-
res.setMessage("User Id not found");
72-
res.setStatus(MyConstant.FAILED);
73-
res.setData(null);
74-
log.error(res.getMessage() + " with UserId : " + payload.getUserId());
75-
return ResponseEntity.status(HttpStatus.CONFLICT).body(res);
76-
} else {
77-
res.setMessage("User Found");
78-
res.setStatus(MyConstant.SUCCESS);
79-
res.setData(dbUser);
80-
log.info(res.getMessage() + " with UserId : " + payload.getUserId());
81-
return ResponseEntity.ok(res);
82-
}
83-
} catch (Exception e) {
84-
res.setMessage(e.getMessage());
85-
res.setStatus(MyConstant.FAILED);
86-
res.setData(null);
87-
log.error("Sarver error: " + res.getMessage());
88-
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(res);
89-
}
90-
}
27+
@GetMapping
28+
public ResponseEntity<List<User>> getAll(){
29+
return ResponseEntity.ok(service.getAllUser());
30+
}
9131

92-
@PostMapping("/reset")
93-
public ResponseEntity<?> resetPassword(@RequestBody @Valid User payload) {
94-
log.info("Invoke api for reset password[resetPassword(@RequestBody User payload)]");
95-
try {
96-
User user = service.updateUser(payload);
97-
res.setMessage("Reset your password successfully");
98-
res.setStatus(MyConstant.SUCCESS);
99-
res.setData(user);
100-
log.info(res.getMessage() + " with UserId : " + payload.getUserId());
101-
return ResponseEntity.ok(res);
102-
} catch (Exception e) {
103-
res.setMessage(e.getMessage());
104-
res.setStatus(MyConstant.FAILED);
105-
res.setData(null);
106-
log.error("Sarver error: " + res.getMessage());
107-
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(res);
108-
}
109-
}
32+
@GetMapping("/{id}")
33+
public ResponseEntity<User> getUserById(@PathVariable Long id) throws UserNotFoundException {
34+
return ResponseEntity.ok(service. GetUserByUserId(id));
35+
}
11036

11137
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.example.dto;
2+
3+
import lombok.AllArgsConstructor;
4+
import lombok.Data;
5+
import lombok.NoArgsConstructor;
6+
7+
import javax.validation.constraints.*;
8+
9+
@Data
10+
@AllArgsConstructor(staticName = "build")
11+
@NoArgsConstructor
12+
public class UserRequest {
13+
14+
@NotNull(message = "Name shouldn't be null")
15+
private String name;
16+
17+
@Email(message = "Email should be valid")
18+
private String email;
19+
20+
@Pattern(regexp = "^\\d{11}$", message = "mobile number should be valid")
21+
private String mobile;
22+
private String gender;
23+
24+
@Min(20)
25+
@Max(50)
26+
private int age;
27+
28+
@NotBlank
29+
private String nationality;
30+
31+
}
Lines changed: 10 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package com.example.model;
22

3+
import lombok.AllArgsConstructor;
34
import lombok.Data;
5+
import lombok.NoArgsConstructor;
46
import org.springframework.validation.annotation.Validated;
57

68
import javax.persistence.Column;
@@ -16,69 +18,18 @@
1618
@Entity
1719
@Table(name = "users")
1820
@Data
21+
@AllArgsConstructor(staticName = "build")
22+
@NoArgsConstructor
1923
@Validated
2024
public class User {
2125

2226
@Id
2327
@GeneratedValue(strategy = GenerationType.IDENTITY)
24-
private long id;
25-
26-
@Column(unique = true, nullable = false)
27-
@NotNull(message = "User ID shouldn't be Empty")
28-
private String userId;
29-
30-
@Column(nullable = false)
31-
@NotNull(message = "Password shouldn't be Empty")
32-
private String password;
33-
34-
@Pattern(regexp = "^\\d{11}$", message = "Invalid Mobile Number")
35-
@NotNull(message = "Mobile Number shouldn't be Empty")
36-
@NotBlank
37-
@Column(nullable = false)
28+
private long userId;
29+
private String name;
30+
private String email;
3831
private String mobile;
39-
40-
public User() {
41-
super();
42-
}
43-
44-
public User(long id, String userId, String password, String mobile) {
45-
super();
46-
this.id = id;
47-
this.userId = userId;
48-
this.password = password;
49-
this.mobile = mobile;
50-
}
51-
52-
public long getId() {
53-
return id;
54-
}
55-
56-
public void setId(long id) {
57-
this.id = id;
58-
}
59-
60-
public String getUserId() {
61-
return userId;
62-
}
63-
64-
public void setUserId(String userId) {
65-
this.userId = userId;
66-
}
67-
68-
public String getPassword() {
69-
return password;
70-
}
71-
72-
public void setPassword(String password) {
73-
this.password = password;
74-
}
75-
76-
public String getMobile() {
77-
return mobile;
78-
}
79-
80-
public void setMobile(String mobile) {
81-
this.mobile = mobile;
82-
}
83-
32+
private String gender;
33+
private int age;
34+
private String nationality;
8435
}

src/main/java/com/example/repository/UserRepository.java

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,5 @@
88

99
public interface UserRepository extends JpaRepository<User, Long> {
1010

11-
User findByUserId(String userId);
12-
13-
// Optional<User> findByUserId(String userId);
14-
15-
11+
User findByUserId(Long id);
1612
}

0 commit comments

Comments
 (0)