Commit 98eae013 authored by Chamod Ishankha's avatar Chamod Ishankha

document upload api

parent 9ddefda2
package com.kaluwa.enterprises.babycarebackendservice.constants;
public class DocumetTypes {
public static final String PROFILE_IMAGE = "profile_image";
}
......@@ -4,5 +4,6 @@ public class TableNames {
public final static String USER_TABLE = "users";
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
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
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);
}
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;
}
......@@ -7,6 +7,7 @@ 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;
import java.util.List;
......@@ -47,4 +48,16 @@ public class UserController {
log.info("Inside user controller delete user method");
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;
import com.kaluwa.enterprises.babycarebackendservice.dto.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
......@@ -16,4 +18,8 @@ public interface UserService {
UserDto updateUser(Long userId, UserDto userDto);
ResponseDto deleteUser(Long userId);
ResponseDto uploadImage(Long userId, MultipartFile file);
ResponseEntity<byte[]> getImage(Long userId);
}
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.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;
@Service
@Slf4j
public class UserServiceImpl implements UserService {
private final UserDao userDao;
private final DocumentDao documentDao;
private final BabyCareUserDetailsService userDetailsService;
private final JWTUtils jwtUtils;
private final PasswordEncoder passwordEncoder;
private final AuthenticationManager authenticationManager;
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.documentDao = documentDao;
this.userDetailsService = userDetailsService;
this.jwtUtils = jwtUtils;
this.passwordEncoder = passwordEncoder;
this.authenticationManager = authenticationManager;
this.userMapper = userMapper;
this.documentMapper = documentMapper;
}
......@@ -116,7 +129,7 @@ public class UserServiceImpl implements UserService {
}
} catch (Exception e) {
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 {
return userMapper.listToDto(users);
} catch (Exception e) {
e.printStackTrace();
throw new BadRequestAlertException(e.getMessage(), "User", "User registration failed");
throw new BadRequestAlertException(e.getMessage(), "User", "error");
}
}
......@@ -159,7 +172,7 @@ public class UserServiceImpl implements UserService {
}
} catch (Exception e) {
e.printStackTrace();
throw new BadRequestAlertException(e.getMessage(), "User", "User registration failed");
throw new BadRequestAlertException(e.getMessage(), "User", "error");
}
}
......@@ -179,7 +192,73 @@ public class UserServiceImpl implements UserService {
}
} catch (Exception e) {
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;
}
}
......@@ -17,6 +17,11 @@ spring:
properties:
hibernate:
format_sql: true
servlet:
multipart:
enabled: true
max-file-size: 5MB
max-request-size: 5MB
server:
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