Commit 63871d87 authored by Ishankha K.C's avatar Ishankha K.C

Merge branch 'feature/chamode_dev' into 'master'

Feature/chamode dev

See merge request !2
parents 6b62e55e fee6f1de
...@@ -47,6 +47,7 @@ public class SecurityConfig { ...@@ -47,6 +47,7 @@ public class SecurityConfig {
"/webjars/**", "/webjars/**",
"/swagger-ui.html", "/swagger-ui.html",
"/emotional/video-process", "/emotional/video-process",
"/test/**"
}; };
@Bean @Bean
......
...@@ -2,25 +2,38 @@ package com.kaluwa.enterprises.babycarebackendservice.config; ...@@ -2,25 +2,38 @@ package com.kaluwa.enterprises.babycarebackendservice.config;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaluwa.enterprises.babycarebackendservice.socketHandlers.EmotionPrediction; import com.kaluwa.enterprises.babycarebackendservice.socketHandlers.EmotionPrediction;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.socket.BinaryMessage; import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.standard.StandardWebSocketClient; import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.handler.TextWebSocketHandler; import org.springframework.web.socket.handler.TextWebSocketHandler;
import static com.kaluwa.enterprises.babycarebackendservice.config.WebSocketConfig.SendVideoHandler.sendTextMessageToClient; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static com.kaluwa.enterprises.babycarebackendservice.config.WebSocketConfig.VideoFrameHandler.sendTextMessageToClient;
public class WebSocketClient { public class WebSocketClient {
private WebSocketSession session; private WebSocketSession session;
private static final String WEBSOCKET_URL = "ws://localhost:8000/ws/emotion";
private static final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
public WebSocketClient() { public WebSocketClient() {
connectToWebSocket();
}
private void connectToWebSocket() {
try { try {
this.session = new StandardWebSocketClient() this.session = new StandardWebSocketClient()
.doHandshake(new MyWebSocketHandler(), "ws://localhost:8000/ws/emotion") .doHandshake(new MyWebSocketHandler(this), WEBSOCKET_URL)
.get(); .get();
System.out.println("Connected to WebSocket!");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); System.out.println("Failed to connect to WebSocket, scheduling reconnection...");
scheduleReconnection();
} }
} }
...@@ -32,10 +45,29 @@ public class WebSocketClient { ...@@ -32,10 +45,29 @@ public class WebSocketClient {
} }
} }
private void scheduleReconnection() {
scheduler.schedule(this::connectToWebSocket, 2, TimeUnit.MINUTES);
}
@Scheduled(fixedDelay = 120000) // Check every 5 minutes
private void checkConnection() {
if (session == null || !session.isOpen()) {
System.out.println("WebSocket connection is closed. Reconnecting...");
connectToWebSocket();
}
}
static ObjectMapper objectMapper = new ObjectMapper(); static ObjectMapper objectMapper = new ObjectMapper();
public static EmotionPrediction[] predictions; public static EmotionPrediction[] predictions;
static class MyWebSocketHandler extends TextWebSocketHandler { static class MyWebSocketHandler extends TextWebSocketHandler {
private final WebSocketClient webSocketClient;
public MyWebSocketHandler(WebSocketClient webSocketClient) {
this.webSocketClient = webSocketClient;
}
@Override @Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// This method will be called when the server sends a text message // This method will be called when the server sends a text message
...@@ -48,5 +80,11 @@ public class WebSocketClient { ...@@ -48,5 +80,11 @@ public class WebSocketClient {
sendTextMessageToClient(lastPrediction); sendTextMessageToClient(lastPrediction);
} }
} }
@Override
public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) {
System.out.println("WebSocket connection closed. Status: " + status);
webSocketClient.scheduleReconnection();
}
} }
} }
...@@ -28,7 +28,6 @@ public class WebSocketConfig implements WebSocketConfigurer { ...@@ -28,7 +28,6 @@ public class WebSocketConfig implements WebSocketConfigurer {
@Override @Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new VideoFrameHandler(), "/emotional/video-process").setAllowedOrigins("*"); registry.addHandler(new VideoFrameHandler(), "/emotional/video-process").setAllowedOrigins("*");
registry.addHandler(new SendVideoHandler(), "/emotional/video-send").setAllowedOrigins("*");
} }
@Bean @Bean
...@@ -39,34 +38,11 @@ public class WebSocketConfig implements WebSocketConfigurer { ...@@ -39,34 +38,11 @@ public class WebSocketConfig implements WebSocketConfigurer {
@Component @Component
class VideoFrameHandler extends BinaryWebSocketHandler { class VideoFrameHandler extends BinaryWebSocketHandler {
WebSocketClient webSocketClient = customWebSocketClient(); private static WebSocketSession currentSession;
@Override
protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
byte[] binaryData = message.getPayload().array();
// Process the binary data representing the video frame
// log.info("Received binary data from client: {}", binaryData);
// Here you can process the binary data as needed, such as saving it to a file, performing image processing, etc.
webSocketClient.sendBytesToWebSocket(binaryData);
SendVideoHandler.sendBinaryMessageToClient(binaryData);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
super.handleTextMessage(session, message);
}
}
@Component
class SendVideoHandler extends BinaryWebSocketHandler {
WebSocketClient webSocketClient = customWebSocketClient();
private static StandardWebSocketSession session;
@Override @Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception { public void afterConnectionEstablished(WebSocketSession session) throws Exception {
SendVideoHandler.session = (StandardWebSocketSession) session; currentSession = session; // Store the current session
log.info("Connection established with client: {}", session); log.info("Connection established with client: {}", session);
super.afterConnectionEstablished(session); super.afterConnectionEstablished(session);
} }
...@@ -74,13 +50,21 @@ public class WebSocketConfig implements WebSocketConfigurer { ...@@ -74,13 +50,21 @@ public class WebSocketConfig implements WebSocketConfigurer {
@Override @Override
protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception { protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
byte[] binaryData = message.getPayload().array(); byte[] binaryData = message.getPayload().array();
// Process the binary data as needed
// Send binary data back to the client
sendBinaryMessageToClient(binaryData);
// Optionally, send a text message
EmotionPrediction emotionPrediction = new EmotionPrediction(); // Example object
sendTextMessageToClient(emotionPrediction);
} }
@Override @Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// Handle session closure here if (currentSession == session) {
// For example, cleanup resources or attempt to reconnect currentSession = null; // Reset session variable
SendVideoHandler.session = null; // Reset session variable }
log.info("Connection closed with client: {}", session); log.info("Connection closed with client: {}", session);
super.afterConnectionClosed(session, status); super.afterConnectionClosed(session, status);
} }
...@@ -89,37 +73,37 @@ public class WebSocketConfig implements WebSocketConfigurer { ...@@ -89,37 +73,37 @@ public class WebSocketConfig implements WebSocketConfigurer {
protected void handleTextMessage(WebSocketSession session, TextMessage message) { protected void handleTextMessage(WebSocketSession session, TextMessage message) {
super.handleTextMessage(session, message); super.handleTextMessage(session, message);
try { try {
System.out.println("Received text message from client: "+message.getPayload()); System.out.println("Received text message from client: " + message.getPayload());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
// Method to send a message back to the client // Method to send a binary message back to the client
public static void sendBinaryMessageToClient(byte[] bytes) { public void sendBinaryMessageToClient(byte[] bytes) {
try { try {
if (session != null && session.isOpen()) { if (currentSession != null && currentSession.isOpen()) {
session.sendMessage(new BinaryMessage(bytes)); currentSession.sendMessage(new BinaryMessage(bytes));
System.out.println("Sent message to client: "+bytes.length); System.out.println("Sent binary message to client: " + bytes.length);
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
// Method to send a text message back to the client
public static void sendTextMessageToClient(EmotionPrediction emotionPrediction) { public static void sendTextMessageToClient(EmotionPrediction emotionPrediction) {
try { try {
if (session != null && session.isOpen()) { if (currentSession != null && currentSession.isOpen()) {
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(emotionPrediction); String json = objectMapper.writeValueAsString(emotionPrediction);
session.sendMessage(new TextMessage(json)); currentSession.sendMessage(new TextMessage(json));
System.out.println("Sent message to client: " + json); System.out.println("Sent text message to client: " + json);
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
} }
\ No newline at end of file
package com.kaluwa.enterprises.babycarebackendservice.constants;
public class DocumetTypes {
public static final String PROFILE_IMAGE = "profile_image";
}
...@@ -4,5 +4,6 @@ public class TableNames { ...@@ -4,5 +4,6 @@ public class TableNames {
public final static String USER_TABLE = "users"; public final static String USER_TABLE = "users";
public final static String BABY_TABLE = "babies"; public final static String BABY_TABLE = "babies";
public final static String DOCUMENT_TABLE = "documents";
} }
package com.kaluwa.enterprises.babycarebackendservice.dao;
import com.kaluwa.enterprises.babycarebackendservice.model.Document;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface DocumentDao extends JpaRepository<Document, Long> {
Optional<Document> findByUserUserIdAndDocumentType(Long userId, String profileImage);
}
\ No newline at end of file
...@@ -8,20 +8,54 @@ import lombok.NoArgsConstructor; ...@@ -8,20 +8,54 @@ import lombok.NoArgsConstructor;
import java.time.LocalDate; import java.time.LocalDate;
import static com.kaluwa.enterprises.babycarebackendservice.constants.Status.STATUS_NEW;
@Data @Data
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
public class BabyDto { public class BabyDto {
private Long babyId; private Long babyId;
@NotNull(message = "Baby name is required") @NotNull(message = "Baby's first name is required")
@NotEmpty(message = "Baby name is required") @NotEmpty(message = "Baby's first name is required")
private String babyName; private String firstName;
private String babyGender; private String lastName;
private LocalDate babyDob; @NotNull(message = "Baby's date of birth is required")
private String babyWeight; @NotEmpty(message = "Baby's date of birth is required")
private LocalDate dob;
@NotNull(message = "Baby's gender is required")
@NotEmpty(message = "Baby's gender is required")
private String sex;
private String status = STATUS_NEW;
private Boolean isActive;
private Float weight;
private Float height;
private String bloodType;
private String eyeColor;
private String hairColor;
private String allergies;
private String medicalConditions;
private String medications;
private String vaccinateRecords;
private String docName;
private String docContactNumber;
private String healthInsuranceInfo;
private LocalDate firstSmileDate;
private LocalDate firstToothDate;
private LocalDate firstWordDate;
private LocalDate firstStepDate;
private String favFoods;
private String foodsDislikes;
private String primaryEmergencyContactName;
private String primaryEmergencyRelationship;
private String primaryEmergencyContactNumber;
private String secondaryEmergencyContactName;
private String secondaryEmergencyRelationship;
private String secondaryEmergencyContactNumber;
private String notes;
private UserDto user; private UserDto user;
@NotNull(message = "Logged user id is required") @NotNull(message = "Logged user id is required")
@NotEmpty(message = "Logged user id is required") @NotEmpty(message = "Logged user id is required")
private Long userId; private Long userId;
private Long documentId;
} }
package com.kaluwa.enterprises.babycarebackendservice.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Value;
import java.io.Serializable;
/**
* DTO for {@link com.kaluwa.enterprises.babycarebackendservice.model.Document}
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DocumentDto implements Serializable {
private Long documentId;
private String documentType;
private String documentName;
private byte[] data;
private UserDto user;
private Long userId;
}
\ No newline at end of file
...@@ -5,6 +5,8 @@ import lombok.AllArgsConstructor; ...@@ -5,6 +5,8 @@ import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import java.time.LocalDate;
@Data @Data
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
...@@ -16,4 +18,5 @@ public class UserDto { ...@@ -16,4 +18,5 @@ public class UserDto {
private String phone; private String phone;
private String role; private String role;
private String status; private String status;
private LocalDate dob;
} }
package com.kaluwa.enterprises.babycarebackendservice.mappers;
import com.kaluwa.enterprises.babycarebackendservice.dto.DocumentDto;
import com.kaluwa.enterprises.babycarebackendservice.model.Document;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import java.util.List;
@Mapper(componentModel = "spring")
public interface DocumentMapper {
@Mappings({
@Mapping(target = "userId", source = "user.userId")
})
DocumentDto toDto(Document document);
@Mappings({
@Mapping(target = "user.userId", source = "userId")
})
Document toEntity(DocumentDto documentDto);
@Mappings({
@Mapping(target = "userId", source = "user.userId")
})
List<DocumentDto> listToDto(List<Document> documents);
}
...@@ -18,11 +18,39 @@ public class Baby { ...@@ -18,11 +18,39 @@ public class Baby {
@Id @Id
@GeneratedValue(strategy= GenerationType.AUTO) @GeneratedValue(strategy= GenerationType.AUTO)
private Long babyId; private Long babyId;
private String babyName; private String firstName;
private String babyGender; private String lastName;
private LocalDate babyDob; private LocalDate dob;
private String babyWeight; private String sex;
private String status;
private Boolean isActive;
private Float weight;
private Float height;
private String bloodType;
private String eyeColor;
private String hairColor;
private String allergies;
private String medicalConditions;
private String medications;
private String vaccinateRecords;
private String docName;
private String docContactNumber;
private String healthInsuranceInfo;
private LocalDate firstSmileDate;
private LocalDate firstToothDate;
private LocalDate firstWordDate;
private LocalDate firstStepDate;
private String favFoods;
private String foodsDislikes;
private String primaryEmergencyContactName;
private String primaryEmergencyRelationship;
private String primaryEmergencyContactNumber;
private String secondaryEmergencyContactName;
private String secondaryEmergencyRelationship;
private String secondaryEmergencyContactNumber;
private String notes;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userId", referencedColumnName = "userId", nullable = false) @JoinColumn(name = "userId", referencedColumnName = "userId", nullable = false)
private User user; private User user;
private Long documentId;
} }
package com.kaluwa.enterprises.babycarebackendservice.model;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import static com.kaluwa.enterprises.babycarebackendservice.constants.TableNames.DOCUMENT_TABLE;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = DOCUMENT_TABLE)
public class Document {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long documentId;
private String documentType;
private String documentName;
@Lob
@Column(name = "data", columnDefinition = "LONGBLOB")
private byte[] data;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userId", referencedColumnName = "userId", nullable = false)
private User user;
}
...@@ -8,6 +8,7 @@ import org.springframework.security.core.GrantedAuthority; ...@@ -8,6 +8,7 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import java.time.LocalDate;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
...@@ -29,6 +30,7 @@ public class User implements UserDetails { ...@@ -29,6 +30,7 @@ public class User implements UserDetails {
private String phone; private String phone;
private String role; private String role;
private String status; private String status;
private LocalDate dob;
@Override @Override
public Collection<? extends GrantedAuthority> getAuthorities() { public Collection<? extends GrantedAuthority> getAuthorities() {
......
...@@ -33,19 +33,19 @@ public class BabyController { ...@@ -33,19 +33,19 @@ public class BabyController {
return ResponseEntity.ok(babyService.getAllBabies()); return ResponseEntity.ok(babyService.getAllBabies());
} }
@GetMapping("/{id}") @GetMapping("/{babyId}")
public ResponseEntity<BabyDto> getBabyById(@PathVariable Long babyId) { public ResponseEntity<BabyDto> getBabyById(@PathVariable Long babyId) {
log.info("Inside baby controller getBabyById method"); log.info("Inside baby controller getBabyById method");
return ResponseEntity.ok(babyService.getBabyById(babyId)); return ResponseEntity.ok(babyService.getBabyById(babyId));
} }
@PutMapping("/{id}") @PutMapping("/{babyId}")
public ResponseEntity<BabyDto> updateBaby(@PathVariable Long babyId, @RequestBody BabyDto babyDto) { public ResponseEntity<BabyDto> updateBaby(@PathVariable Long babyId, @RequestBody BabyDto babyDto) {
log.info("Inside baby controller updateBaby method"); log.info("Inside baby controller updateBaby method");
return ResponseEntity.ok(babyService.updateBaby(babyId, babyDto)); return ResponseEntity.ok(babyService.updateBaby(babyId, babyDto));
} }
@DeleteMapping("/{id}") @DeleteMapping("/{babyId}")
public ResponseEntity<ResponseDto> deleteBaby(@PathVariable Long babyId) { public ResponseEntity<ResponseDto> deleteBaby(@PathVariable Long babyId) {
log.info("Inside baby controller deleteBaby method"); log.info("Inside baby controller deleteBaby method");
return ResponseEntity.ok(babyService.deleteBaby(babyId)); return ResponseEntity.ok(babyService.deleteBaby(babyId));
......
package com.kaluwa.enterprises.babycarebackendservice.rest; package com.kaluwa.enterprises.babycarebackendservice.rest;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
...@@ -18,4 +22,52 @@ public class TestController { ...@@ -18,4 +22,52 @@ public class TestController {
return new ResponseEntity<>("Test OK!", HttpStatus.OK); return new ResponseEntity<>("Test OK!", HttpStatus.OK);
} }
String lightStatus = "OFF";
@GetMapping("/light/on")
public ResponseEntity<String> lightOn() {
log.info("Inside lightOn controller");
lightStatus = "ON";
return new ResponseEntity<>("Light is ON", HttpStatus.OK);
}
@GetMapping("/light/off")
public ResponseEntity<String> lightOff() {
log.info("Inside lightOff controller");
lightStatus = "OFF";
return new ResponseEntity<>("Light is OFF", HttpStatus.OK);
}
@GetMapping("/light/status")
public ResponseEntity<String> lightStatus() {
log.info("Inside lightStatus controller");
return new ResponseEntity<>(lightStatus, HttpStatus.OK);
}
@GetMapping("/music/play")
public ResponseEntity<Resource> getMusicFile() {
log.info("Inside getMusicFile controller");
try {
// Load the music.wav file from the resources folder
ClassPathResource resource = new ClassPathResource("music.wav");
// Check if the resource exists
if (!resource.exists()) {
return ResponseEntity.notFound().build();
}
// Set the headers to specify the content type
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, "audio/wav");
// Return the file as the response
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
} catch (Exception e) {
log.error("Error serving music file", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
} }
...@@ -7,6 +7,7 @@ import lombok.extern.slf4j.Slf4j; ...@@ -7,6 +7,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List; import java.util.List;
...@@ -47,4 +48,16 @@ public class UserController { ...@@ -47,4 +48,16 @@ public class UserController {
log.info("Inside user controller delete user method"); log.info("Inside user controller delete user method");
return new ResponseEntity<>(userService.deleteUser(userId), HttpStatus.OK); return new ResponseEntity<>(userService.deleteUser(userId), HttpStatus.OK);
} }
@PutMapping("/image/{userId}")
public ResponseEntity<ResponseDto> uploadImage(@PathVariable Long userId, @RequestParam("image") MultipartFile file) {
log.info("Inside user controller upload image method");
return new ResponseEntity<>(userService.uploadImage(userId, file), HttpStatus.OK);
}
@GetMapping("/image/{userId}")
public ResponseEntity<byte[]> getImage(@PathVariable Long userId) {
log.info("Inside user controller get image method");
return userService.getImage(userId);
}
} }
package com.kaluwa.enterprises.babycarebackendservice.service; package com.kaluwa.enterprises.babycarebackendservice.service;
import com.kaluwa.enterprises.babycarebackendservice.dto.*; import com.kaluwa.enterprises.babycarebackendservice.dto.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import java.util.List; import java.util.List;
...@@ -16,4 +18,8 @@ public interface UserService { ...@@ -16,4 +18,8 @@ public interface UserService {
UserDto updateUser(Long userId, UserDto userDto); UserDto updateUser(Long userId, UserDto userDto);
ResponseDto deleteUser(Long userId); ResponseDto deleteUser(Long userId);
ResponseDto uploadImage(Long userId, MultipartFile file);
ResponseEntity<byte[]> getImage(Long userId);
} }
package com.kaluwa.enterprises.babycarebackendservice.service.impl; package com.kaluwa.enterprises.babycarebackendservice.service.impl;
import com.kaluwa.enterprises.babycarebackendservice.dao.BabyDao; import com.kaluwa.enterprises.babycarebackendservice.dao.BabyDao;
import com.kaluwa.enterprises.babycarebackendservice.dao.DocumentDao;
import com.kaluwa.enterprises.babycarebackendservice.dto.BabyDto; import com.kaluwa.enterprises.babycarebackendservice.dto.BabyDto;
import com.kaluwa.enterprises.babycarebackendservice.dto.ResponseDto; import com.kaluwa.enterprises.babycarebackendservice.dto.ResponseDto;
import com.kaluwa.enterprises.babycarebackendservice.error.BadRequestAlertException; import com.kaluwa.enterprises.babycarebackendservice.error.BadRequestAlertException;
import com.kaluwa.enterprises.babycarebackendservice.mappers.BabyMapper; import com.kaluwa.enterprises.babycarebackendservice.mappers.BabyMapper;
import com.kaluwa.enterprises.babycarebackendservice.model.Baby; import com.kaluwa.enterprises.babycarebackendservice.model.Baby;
import com.kaluwa.enterprises.babycarebackendservice.model.Document;
import com.kaluwa.enterprises.babycarebackendservice.service.BabyService; import com.kaluwa.enterprises.babycarebackendservice.service.BabyService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -15,15 +18,17 @@ import java.util.List; ...@@ -15,15 +18,17 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
@Service @Service
@Slf4j
public class BabyServiceImpl implements BabyService { public class BabyServiceImpl implements BabyService {
private static final Logger log = LoggerFactory.getLogger(BabyServiceImpl.class);
private final BabyDao babyDao; private final BabyDao babyDao;
private final BabyMapper babyMapper; private final BabyMapper babyMapper;
private final DocumentDao documentDao;
public BabyServiceImpl(BabyDao babyDao, BabyMapper babyMapper) { public BabyServiceImpl(BabyDao babyDao, BabyMapper babyMapper, DocumentDao documentDao) {
this.babyDao = babyDao; this.babyDao = babyDao;
this.babyMapper = babyMapper; this.babyMapper = babyMapper;
this.documentDao = documentDao;
} }
@Override @Override
...@@ -92,6 +97,10 @@ public class BabyServiceImpl implements BabyService { ...@@ -92,6 +97,10 @@ public class BabyServiceImpl implements BabyService {
if (babyOp.isEmpty()) { if (babyOp.isEmpty()) {
throw new BadRequestAlertException("Baby not found", "baby", "baby.error"); throw new BadRequestAlertException("Baby not found", "baby", "baby.error");
} else { } else {
Optional<Document> documentOp = documentDao.findById(babyOp.get().getDocumentId());
if (documentOp.isPresent()) {
documentDao.deleteById(babyOp.get().getDocumentId());
}
babyDao.deleteById(babyId); babyDao.deleteById(babyId);
ResponseDto responseDto = new ResponseDto(); ResponseDto responseDto = new ResponseDto();
responseDto.setId(babyId); responseDto.setId(babyId);
......
package com.kaluwa.enterprises.babycarebackendservice.service.impl; package com.kaluwa.enterprises.babycarebackendservice.service.impl;
import com.kaluwa.enterprises.babycarebackendservice.dao.DocumentDao;
import com.kaluwa.enterprises.babycarebackendservice.dao.UserDao; import com.kaluwa.enterprises.babycarebackendservice.dao.UserDao;
import com.kaluwa.enterprises.babycarebackendservice.dto.*; import com.kaluwa.enterprises.babycarebackendservice.dto.*;
import com.kaluwa.enterprises.babycarebackendservice.error.BadRequestAlertException; import com.kaluwa.enterprises.babycarebackendservice.error.BadRequestAlertException;
import com.kaluwa.enterprises.babycarebackendservice.mappers.DocumentMapper;
import com.kaluwa.enterprises.babycarebackendservice.mappers.UserMapper; import com.kaluwa.enterprises.babycarebackendservice.mappers.UserMapper;
import com.kaluwa.enterprises.babycarebackendservice.model.Document;
import com.kaluwa.enterprises.babycarebackendservice.model.User; import com.kaluwa.enterprises.babycarebackendservice.model.User;
import com.kaluwa.enterprises.babycarebackendservice.service.UserService; import com.kaluwa.enterprises.babycarebackendservice.service.UserService;
import com.kaluwa.enterprises.babycarebackendservice.utils.JWTUtils; import com.kaluwa.enterprises.babycarebackendservice.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import static com.kaluwa.enterprises.babycarebackendservice.constants.Common.TOKEN_TYPE; import static com.kaluwa.enterprises.babycarebackendservice.constants.Common.TOKEN_TYPE;
import static com.kaluwa.enterprises.babycarebackendservice.constants.DocumetTypes.PROFILE_IMAGE;
import static com.kaluwa.enterprises.babycarebackendservice.constants.Status.STATUS_NEW; import static com.kaluwa.enterprises.babycarebackendservice.constants.Status.STATUS_NEW;
import static com.kaluwa.enterprises.babycarebackendservice.constants.UserRoles.USER; import static com.kaluwa.enterprises.babycarebackendservice.constants.UserRoles.USER;
import static com.kaluwa.enterprises.babycarebackendservice.utils.JWTUtils.EXPIRATION_TIME; import static com.kaluwa.enterprises.babycarebackendservice.utils.JWTUtils.EXPIRATION_TIME;
import static com.kaluwa.enterprises.babycarebackendservice.utils.Utils.ALLOWED_CONTENT_TYPES;
import static com.kaluwa.enterprises.babycarebackendservice.utils.Utils.determineImageContentType;
@Service @Service
@Slf4j @Slf4j
public class UserServiceImpl implements UserService { public class UserServiceImpl implements UserService {
private final UserDao userDao; private final UserDao userDao;
private final DocumentDao documentDao;
private final BabyCareUserDetailsService userDetailsService; private final BabyCareUserDetailsService userDetailsService;
private final JWTUtils jwtUtils; private final JWTUtils jwtUtils;
private final PasswordEncoder passwordEncoder; private final PasswordEncoder passwordEncoder;
private final AuthenticationManager authenticationManager; private final AuthenticationManager authenticationManager;
private final UserMapper userMapper; private final UserMapper userMapper;
private final DocumentMapper documentMapper;
public UserServiceImpl(UserDao userDao, BabyCareUserDetailsService userDetailsService, JWTUtils jwtUtils, PasswordEncoder passwordEncoder, AuthenticationManager authenticationManager, UserMapper userMapper) { public UserServiceImpl(UserDao userDao, DocumentDao documentDao, BabyCareUserDetailsService userDetailsService, JWTUtils jwtUtils, PasswordEncoder passwordEncoder, AuthenticationManager authenticationManager, UserMapper userMapper, DocumentMapper documentMapper) {
this.userDao = userDao; this.userDao = userDao;
this.documentDao = documentDao;
this.userDetailsService = userDetailsService; this.userDetailsService = userDetailsService;
this.jwtUtils = jwtUtils; this.jwtUtils = jwtUtils;
this.passwordEncoder = passwordEncoder; this.passwordEncoder = passwordEncoder;
this.authenticationManager = authenticationManager; this.authenticationManager = authenticationManager;
this.userMapper = userMapper; this.userMapper = userMapper;
this.documentMapper = documentMapper;
} }
...@@ -116,7 +129,7 @@ public class UserServiceImpl implements UserService { ...@@ -116,7 +129,7 @@ public class UserServiceImpl implements UserService {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
throw new BadRequestAlertException(e.getMessage(), "User", "User registration failed"); throw new BadRequestAlertException(e.getMessage(), "User", "error");
} }
} }
...@@ -128,7 +141,7 @@ public class UserServiceImpl implements UserService { ...@@ -128,7 +141,7 @@ public class UserServiceImpl implements UserService {
return userMapper.listToDto(users); return userMapper.listToDto(users);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
throw new BadRequestAlertException(e.getMessage(), "User", "User registration failed"); throw new BadRequestAlertException(e.getMessage(), "User", "error");
} }
} }
...@@ -154,11 +167,12 @@ public class UserServiceImpl implements UserService { ...@@ -154,11 +167,12 @@ public class UserServiceImpl implements UserService {
user.setFirstName(userDto.getFirstName()); user.setFirstName(userDto.getFirstName());
user.setLastName(userDto.getLastName()); user.setLastName(userDto.getLastName());
user.setPhone(userDto.getPhone()); user.setPhone(userDto.getPhone());
user.setDob(userDto.getDob());
return userMapper.toDto(userDao.save(user)); return userMapper.toDto(userDao.save(user));
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
throw new BadRequestAlertException(e.getMessage(), "User", "User registration failed"); throw new BadRequestAlertException(e.getMessage(), "User", "error");
} }
} }
...@@ -178,7 +192,73 @@ public class UserServiceImpl implements UserService { ...@@ -178,7 +192,73 @@ public class UserServiceImpl implements UserService {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
throw new BadRequestAlertException(e.getMessage(), "User", "User registration failed"); throw new BadRequestAlertException(e.getMessage(), "User", "error");
}
}
@Override
public ResponseDto uploadImage(Long userId, MultipartFile file) {
log.info("Inside user service upload image method");
try {
Optional<User> userOp = userDao.findById(userId);
if (userOp.isEmpty()) {
throw new BadRequestAlertException("User not found", "User", "User not found");
} else {
Optional<Document> documentOp = documentDao.findByUserUserIdAndDocumentType(userId, PROFILE_IMAGE);
DocumentDto documentDto = new DocumentDto();
if (documentOp.isPresent()) {
documentDto = documentMapper.toDto(documentOp.get());
}
// save file into system
if (file.isEmpty()) {
throw new BadRequestAlertException("Please select a Image to upload", "User", "Image upload failed");
}
// Validate file content type
String contentType = file.getContentType();
if (!ALLOWED_CONTENT_TYPES.contains(contentType)) {
throw new BadRequestAlertException("Invalid file type. Only JPEG, PNG, and JPG files are allowed.", "User", "Image upload failed");
}
documentDto.setDocumentType(PROFILE_IMAGE);
documentDto.setDocumentName(file.getOriginalFilename());
documentDto.setData(file.getBytes());
documentDto.setUserId(userId);
// save image
documentDto = documentMapper.toDto(documentDao.save(documentMapper.toEntity(documentDto)));
// response
ResponseDto responseDto = new ResponseDto();
responseDto.setId(documentDto.getDocumentId());
responseDto.setMessage("Image uploaded successfully");
return responseDto;
}
} catch (Exception e) {
e.printStackTrace();
throw new BadRequestAlertException(e.getMessage(), "User", "error");
}
}
@Override
public ResponseEntity<byte[]> getImage(Long userId) {
log.info("Inside user service get image method");
try {
Optional<User> userOp = userDao.findById(userId);
if (userOp.isEmpty()) {
throw new BadRequestAlertException("User not found", "User", "User not found");
} else {
Optional<Document> documentOp = documentDao.findByUserUserIdAndDocumentType(userId, PROFILE_IMAGE);
if (documentOp.isEmpty()) {
throw new BadRequestAlertException("Image not found", "User", "Image not found");
} else {
DocumentDto documentDto = documentMapper.toDto(documentOp.get());
return ResponseEntity.ok()
.contentType(MediaType.valueOf(determineImageContentType(documentDto.getDocumentName())))
.body(documentDto.getData());
}
}
} catch (Exception e) {
e.printStackTrace();
throw new BadRequestAlertException(e.getMessage(), "User", "error");
} }
} }
} }
package com.kaluwa.enterprises.babycarebackendservice.utils;
import org.springframework.web.multipart.MultipartFile;
import java.util.Arrays;
import java.util.List;
public class Utils {
// List of allowed image MIME types
public static final List<String> ALLOWED_CONTENT_TYPES = Arrays.asList(
"image/jpeg",
"image/png",
"image/jpg"
);
public static final String determineImageContentType(String filename) {
String contentType;
if (filename.endsWith(".jpeg")) {
contentType = "image/jpeg";
} else if (filename.endsWith(".png")) {
contentType = "image/png";
} else if (filename.endsWith(".jpg")) {
contentType = "image/jpg";
} else {
contentType = "application/octet-stream";
}
return contentType;
}
}
...@@ -16,7 +16,13 @@ spring: ...@@ -16,7 +16,13 @@ spring:
show-sql: false show-sql: false
properties: properties:
hibernate: hibernate:
dialect: org.hibernate.dialect.MySQLDialect
format_sql: true format_sql: true
servlet:
multipart:
enabled: true
max-file-size: 5MB
max-request-size: 5MB
server: server:
port: 8080 port: 8080
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment