Skip to content

Commit ebd0544

Browse files
committed
major(optimization): changed the code style to functional, optmized code, added proper logs
2 parents d9b4071 + a027cd6 commit ebd0544

3 files changed

Lines changed: 48 additions & 66 deletions

File tree

src/main/java/com/connect/controller/ChatRoomController.java

Lines changed: 12 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import com.connect.service.RoomService;
1010
import com.connect.utils.JwtUtil;
1111
import jakarta.servlet.http.HttpServletRequest;
12+
import lombok.AllArgsConstructor;
1213
import lombok.extern.slf4j.Slf4j;
1314
import org.springframework.beans.factory.annotation.Autowired;
1415
import org.springframework.http.HttpStatus;
@@ -20,22 +21,20 @@
2021

2122
import java.util.List;
2223
import java.util.Map;
24+
import java.util.Optional;
2325
import java.util.stream.Collectors;
2426

2527
@RestController
2628
@Slf4j
29+
@AllArgsConstructor
2730
public class ChatRoomController {
2831

29-
@Autowired
3032
private ChatUserService chatUserService;
3133

32-
@Autowired
3334
private RoomService roomService;
3435

35-
@Autowired
3636
private JwtTokenService jwtTokenService;
3737

38-
@Autowired
3938
private SimpMessagingTemplate messagingTemplate;
4039

4140
// Route for handling the joining message.
@@ -54,28 +53,18 @@ public void joinRoom(@Payload Map<String, String> joinReq) {
5453
// Person who is creating the room must give the necessary information as in body.
5554
@PostMapping("/room/create")
5655
public ResponseEntity<Map<String, String>> createRoom(@RequestBody Room room, HttpServletRequest request) {
56+
5757
log.info("New Room request");
5858
String rawToken = request.getHeader("Authorization");
59-
// Checking the token is valid or not.
60-
// This service extracts the username till then the token is valid otherwise it will not.
61-
String token = rawToken.substring(7);
62-
String username = jwtTokenService.extractUsername(token);
6359

64-
if (username.isEmpty()) {
65-
return ResponseEntity
66-
.status(HttpStatus.UNAUTHORIZED)
67-
.body(Map.of("response", "Invalid Token"));
68-
}
69-
// Here we need to send the data to the service class.
70-
var createdRoom = roomService.addNewRoom(room, username);
71-
if (createdRoom == null) {
72-
return ResponseEntity
73-
.status(HttpStatus.INTERNAL_SERVER_ERROR)
74-
.body(Map.of("response", "Something went wrong at the server! Try again later."));
75-
}
76-
return ResponseEntity
77-
.status(HttpStatus.CREATED)
78-
.body(Map.of("response", createdRoom.getRoomId().toString()));
60+
return Optional.ofNullable(jwtTokenService.extractUsername(rawToken.substring(7)))
61+
.flatMap(username -> Optional.ofNullable(roomService.addNewRoom(room, username))
62+
.map(newRoom -> ResponseEntity.ok(Map.of("response", "Room created successfully.")))
63+
)
64+
.orElseGet(() -> {
65+
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
66+
.body(Map.of("response", "Invalid Token or Room Creation Failed"));
67+
});
7968
}
8069

8170
@GetMapping("/room/getall")

src/main/java/com/connect/controller/ChatUserController.java

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -53,26 +53,26 @@ public void handleMessage(@Payload MessageDTO message, SimpMessageHeaderAccessor
5353
public void handleHistory(SimpMessageHeaderAccessor headerAccessor) {
5454
String roomId = headerAccessor.getFirstNativeHeader("roomId");
5555
log.info("Handling the History of chats for the Room: {}", roomId);
56-
Optional<List<Message>> messages = chatUserService.chatHistoryHandler(roomId);
57-
messages.ifPresent(msgs -> {
58-
System.out.println(messages.get().size());
59-
List<MessageDTO> dtoList = msgs.stream()
60-
.map(MessageDTO::new)
61-
.collect(Collectors.toList());
6256

63-
messagingTemplate.convertAndSend("/topic/history/"+roomId, dtoList);
64-
});
57+
chatUserService.chatHistoryHandler(roomId)
58+
.ifPresent(msgs -> {
59+
log.info("Message Size: {}", msgs.size());
60+
List<MessageDTO> dtoList = msgs.stream()
61+
.map(MessageDTO::new)
62+
.toList();
63+
messagingTemplate.convertAndSend("/topic/history/"+roomId, dtoList);
64+
});
6565
}
6666

6767
@MessageMapping("/users")
6868
public void fetchUsers() {
69-
Optional<List<User>> users = chatUserService.fetchUser();
70-
users.ifPresent(users1 -> {
71-
List<UserDTO> modifiedUsers = users1
72-
.stream()
73-
.map(UserDTO::new)
74-
.collect(Collectors.toList());
75-
messagingTemplate.convertAndSend("/topic/users", modifiedUsers);
76-
});
69+
chatUserService.fetchUser()
70+
.ifPresent(users1 -> {
71+
List<UserDTO> modifiedUsers = users1
72+
.stream()
73+
.map(UserDTO::new)
74+
.collect(Collectors.toList());
75+
messagingTemplate.convertAndSend("/topic/users", modifiedUsers);
76+
});
7777
}
7878
}
Lines changed: 20 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,43 @@
11
package com.connect.controller;
22

3+
import com.connect.service.JwtTokenService;
34
import com.connect.utils.JwtUtil;
5+
import lombok.extern.slf4j.Slf4j;
46
import org.springframework.beans.factory.annotation.Autowired;
57
import org.springframework.http.HttpStatus;
68
import org.springframework.http.ResponseEntity;
79
import org.springframework.web.bind.annotation.*;
810

11+
import java.util.Map;
12+
import java.util.Optional;
13+
914
// Controller for handling the Verify Token Request
1015

1116
@RestController
1217
@RequestMapping("/api")
18+
@Slf4j
1319
public class TokenController {
1420

1521
@Autowired
16-
private JwtUtil jwtUtil;
22+
private JwtTokenService tokenService;
1723

1824
@GetMapping("/verify-token")
1925
public ResponseEntity<?> verifyToken(@RequestHeader("Authorization") String authHeader) {
20-
try {
21-
22-
System.out.println("Request recieved for token verification");
23-
if (authHeader == null || !authHeader.startsWith("Bearer")) {
24-
return ResponseEntity
25-
.status(HttpStatus.UNAUTHORIZED)
26-
.body("Missing Authorization Header");
27-
}
28-
29-
String token = authHeader.substring(7);
30-
String username = jwtUtil.extractClaims(token).getSubject();
31-
32-
33-
if (jwtUtil.isTokenValid(token, username)) {
34-
System.out.println("Token is valid");
35-
return ResponseEntity.ok("Token is valid");
36-
} else {
37-
System.out.println("Token is invalid");
38-
return ResponseEntity
39-
.status(HttpStatus.UNAUTHORIZED)
40-
.body("Token is invalid");
41-
}
42-
}
43-
catch (Exception e) {
44-
System.out.println("[ERROR] Token Validation Failed: "+ e.getMessage());
26+
log.info("Request received for token verification");
27+
if (authHeader == null || !authHeader.startsWith("Bearer")) {
4528
return ResponseEntity
4629
.status(HttpStatus.UNAUTHORIZED)
47-
.body("Token Validation Failed");
30+
.body("Missing Authorization Header");
4831
}
32+
33+
return Optional.ofNullable(tokenService.extractUsername(authHeader.substring(7)))
34+
.map(username -> {
35+
return ResponseEntity.ok("Authorized");
36+
})
37+
.orElseGet(() -> {
38+
return ResponseEntity
39+
.status(HttpStatus.UNAUTHORIZED)
40+
.body("Invalid Token");
41+
});
4942
}
5043
}

0 commit comments

Comments
 (0)