Commit f8379cc4 authored by Ishankha K.C's avatar Ishankha K.C

db host change and document management apis

parent b8dd6ac9
package com.kaluwa.enterprises.babycarebackendservice.constants;
public class DocumetTypes {
public class DocumentTypes {
public static final String PROFILE_IMAGE = "profile_image";
public static final String BABY_PROFILE_IMAGE = "baby_profile_image";
public static final String IMAGE = "image";
}
......@@ -9,5 +9,7 @@ import java.util.Optional;
@Repository
public interface DocumentDao extends JpaRepository<Document, Long> {
Optional<Document> findByUserUserIdAndDocumentType(Long userId, String profileImage);
// Optional<Document> findByUserUserIdAndDocumentType(Long userId, String profileImage);
Optional<Document> findByTableNameAndUniqKeyAndDocumentType(String table, String uniqKey, String documentType);
}
\ No newline at end of file
package com.kaluwa.enterprises.babycarebackendservice.dao;
import com.kaluwa.enterprises.babycarebackendservice.model.User;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
......@@ -11,4 +13,6 @@ public interface UserDao extends JpaRepository<User, Long> {
Optional<User> findByEmail(String username);
boolean existsByEmail(String email);
boolean existsByUniqKey(String uniqKey);
}
......@@ -15,5 +15,6 @@ public class AuthenticationDto {
private String phone;
private String role;
private String status;
private String uniqKey;
private TokenDto tokenDto;
}
......@@ -52,6 +52,7 @@ public class BabyDto {
private String secondaryEmergencyRelationship;
private String secondaryEmergencyContactNumber;
private String notes;
private String uniqKey;
private UserDto user;
@NotNull(message = "Logged user id is required")
......
......@@ -17,8 +17,7 @@ public class DocumentDto implements Serializable {
private Long documentId;
private String documentType;
private String documentName;
private String tableName;
private String uniqKey;
private byte[] data;
private UserDto user;
private Long userId;
}
\ No newline at end of file
......@@ -18,5 +18,6 @@ public class UserDto {
private String phone;
private String role;
private String status;
private String uniqKey;
private LocalDate dob;
}
......@@ -11,19 +11,10 @@ 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);
}
......@@ -49,6 +49,7 @@ public class Baby {
private String secondaryEmergencyRelationship;
private String secondaryEmergencyContactNumber;
private String notes;
private String uniqKey;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userId", referencedColumnName = "userId", nullable = false)
private User user;
......
......@@ -19,10 +19,12 @@ public class Document {
private Long documentId;
private String documentType;
private String documentName;
private String tableName;
private String uniqKey;
@Lob
@Column(name = "data", columnDefinition = "LONGBLOB")
private byte[] data;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userId", referencedColumnName = "userId", nullable = false)
private User user;
// @ManyToOne(fetch = FetchType.LAZY)
// @JoinColumn(name = "userId", referencedColumnName = "userId", nullable = false)
// private User user;
}
......@@ -30,6 +30,7 @@ public class User implements UserDetails {
private String phone;
private String role;
private String status;
private String uniqKey;
private LocalDate dob;
@Override
......
package com.kaluwa.enterprises.babycarebackendservice.rest;
import com.kaluwa.enterprises.babycarebackendservice.dto.ResponseDto;
import com.kaluwa.enterprises.babycarebackendservice.service.DocumentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/document")
@Slf4j
public class DocumentController {
private final DocumentService documentService;
public DocumentController(DocumentService documentService) {
this.documentService = documentService;
}
@PutMapping("/{docType}/{table}/{uniqKey}")
public ResponseEntity<ResponseDto> uploadImage(
@PathVariable String docType,
@PathVariable String table,
@PathVariable String uniqKey,
@RequestParam("image") MultipartFile file
) {
log.info("Inside document controller upload image method");
return documentService.uploadImage(docType, table, uniqKey, file);
}
@GetMapping("/{table}/{uniqKey}")
public ResponseEntity<byte[]> getImage(
@PathVariable String table,
@PathVariable String uniqKey
) {
log.info("Inside document controller get image method");
return documentService.getImage(table, uniqKey);
}
}
......@@ -49,15 +49,15 @@ public class UserController {
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);
}
// @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;
import com.kaluwa.enterprises.babycarebackendservice.dto.ResponseDto;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
public interface DocumentService {
ResponseEntity<ResponseDto> uploadImage(String docType, String table, String uniqKey, MultipartFile file);
ResponseEntity<byte[]> getImage(String table, String uniqKey);
}
......@@ -19,7 +19,7 @@ public interface UserService {
ResponseDto deleteUser(Long userId);
ResponseDto uploadImage(Long userId, MultipartFile file);
ResponseEntity<byte[]> getImage(Long userId);
// ResponseDto uploadImage(Long userId, MultipartFile file);
//
// ResponseEntity<byte[]> getImage(Long userId);
}
......@@ -17,6 +17,8 @@ import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import static com.kaluwa.enterprises.babycarebackendservice.utils.Utils.uniqKeyGenerator;
@Service
@Slf4j
public class BabyServiceImpl implements BabyService {
......@@ -35,6 +37,7 @@ public class BabyServiceImpl implements BabyService {
public BabyDto createBaby(BabyDto babyDto) {
log.info("Inside baby service createBaby method");
try {
babyDto.setUniqKey(uniqKeyGenerator());
return babyMapper.toDto(babyDao.save(babyMapper.toEntity(babyDto)));
} catch (Exception e) {
e.printStackTrace();
......
package com.kaluwa.enterprises.babycarebackendservice.service.impl;
import com.kaluwa.enterprises.babycarebackendservice.dao.DocumentDao;
import com.kaluwa.enterprises.babycarebackendservice.dto.DocumentDto;
import com.kaluwa.enterprises.babycarebackendservice.dto.ResponseDto;
import com.kaluwa.enterprises.babycarebackendservice.error.BadRequestAlertException;
import com.kaluwa.enterprises.babycarebackendservice.mappers.DocumentMapper;
import com.kaluwa.enterprises.babycarebackendservice.model.Document;
import com.kaluwa.enterprises.babycarebackendservice.service.DocumentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.Optional;
import static com.kaluwa.enterprises.babycarebackendservice.constants.DocumentTypes.IMAGE;
import static com.kaluwa.enterprises.babycarebackendservice.utils.Utils.ALLOWED_CONTENT_TYPES;
import static com.kaluwa.enterprises.babycarebackendservice.utils.Utils.determineImageContentType;
@Service
@Slf4j
public class DocumentServiceImpl implements DocumentService {
private final DocumentDao documentDao;
private final DocumentMapper documentMapper;
private final JdbcTemplate jdbcTemplate;
public DocumentServiceImpl(DocumentDao documentDao, DocumentMapper documentMapper, JdbcTemplate jdbcTemplate) {
this.documentDao = documentDao;
this.documentMapper = documentMapper;
this.jdbcTemplate = jdbcTemplate;
}
@Override
public ResponseEntity<ResponseDto> uploadImage(String docType, String table, String uniqKey, MultipartFile file) {
log.info("Inside document service upload image method");
try {
if (!recordExists(table, uniqKey)) {
throw new BadRequestAlertException("Record not found by uniqKey: "+uniqKey+" on "+table+" table.", "Error", "Record not found");
} else {
Optional<Document> documentOp = documentDao.findByTableNameAndUniqKeyAndDocumentType(table, uniqKey, 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(IMAGE);
documentDto.setDocumentName(file.getOriginalFilename());
documentDto.setData(file.getBytes());
documentDto.setTableName(table);
documentDto.setUniqKey(uniqKey);
// save image
documentDto = documentMapper.toDto(documentDao.save(documentMapper.toEntity(documentDto)));
// response
ResponseDto responseDto = new ResponseDto();
responseDto.setId(documentDto.getDocumentId());
responseDto.setMessage("Image uploaded successfully");
log.info("Image uploaded successfully");
return new ResponseEntity<>(responseDto, HttpStatus.OK);
}
} catch (Exception e) {
e.printStackTrace();
log.error("Error occurred while uploading image: "+e.getMessage());
throw new BadRequestAlertException(e.getMessage(), "User", "error");
}
}
@Override
public ResponseEntity<byte[]> getImage(String table, String uniqKey) {
log.info("Inside document service get image method");
try {
if (!recordExists(table, uniqKey)) {
throw new BadRequestAlertException("Record not found by uniqKey: "+uniqKey+" on "+table+" table.", "Error", "Record not found");
} else {
Optional<Document> documentOp = documentDao.findByTableNameAndUniqKeyAndDocumentType(table, uniqKey, 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");
}
}
private boolean recordExists(String tableName, String uniqueKey) {
String query = "SELECT COUNT(*) FROM " + tableName + " WHERE uniq_key = ?";
Integer count = jdbcTemplate.queryForObject(query, new Object[]{uniqueKey}, Integer.class);
return count != null && count > 0;
}
}
......@@ -6,30 +6,24 @@ import com.kaluwa.enterprises.babycarebackendservice.dto.*;
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.model.Document;
import com.kaluwa.enterprises.babycarebackendservice.model.User;
import com.kaluwa.enterprises.babycarebackendservice.service.UserService;
import com.kaluwa.enterprises.babycarebackendservice.utils.JWTUtils;
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.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
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.UserRoles.USER;
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;
import static com.kaluwa.enterprises.babycarebackendservice.utils.Utils.uniqKeyGenerator;
@Service
@Slf4j
......@@ -73,6 +67,7 @@ public class UserServiceImpl implements UserService {
authenticationDto.setPhone(user.getPhone());
authenticationDto.setRole(user.getRole());
authenticationDto.setStatus(user.getStatus());
authenticationDto.setUniqKey(user.getUniqKey());
TokenDto tokenDto = new TokenDto();
tokenDto.setTokenType(TOKEN_TYPE);
......@@ -105,6 +100,7 @@ public class UserServiceImpl implements UserService {
userDto.setPhone(registerRequest.getPhone());
userDto.setRole(USER);
userDto.setStatus(STATUS_NEW);
userDto.setUniqKey(uniqKeyGenerator());
User user = userMapper.toEntity(userDto);
user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
......@@ -196,69 +192,69 @@ public class UserServiceImpl implements UserService {
}
}
@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");
}
}
// @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");
// }
// }
}
......@@ -4,6 +4,7 @@ import org.springframework.web.multipart.MultipartFile;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
public class Utils {
......@@ -14,7 +15,7 @@ public class Utils {
"image/jpg"
);
public static final String determineImageContentType(String filename) {
public static String determineImageContentType(String filename) {
String contentType;
if (filename.endsWith(".jpeg")) {
contentType = "image/jpeg";
......@@ -28,4 +29,8 @@ public class Utils {
return contentType;
}
public static String uniqKeyGenerator() {
return UUID.randomUUID().toString().substring(0, 8);
}
}
......@@ -6,7 +6,7 @@ spring:
name: user
password: password
datasource:
url: jdbc:mysql://124.43.79.107:33306/baby_care_db?useSSL=false&serverTimezone=UTC
url: jdbc:mysql://192.168.1.8:30306/baby_care_db?useSSL=false&serverTimezone=UTC
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
......
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