Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ public class ComponentsService {
private final ComponentMapper componentMapper;
private final ImageService imagesService;

private static final String NOT_FOUND_MESSAGE = "Componente no encontrado.";

public ComponentsService(ComponentsRepository componentRepository, ComponentMapper componentMapper,
ImageService imagesService) {
this.componentRepository = componentRepository;
Expand All @@ -47,7 +49,7 @@ public List<Component> findTop3MoreRecent() {

public Component getComponent(long id) {
return componentRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Componente no encontrado."));
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE));
}

public Resource getImageFile(long id) throws SQLException {
Expand All @@ -67,7 +69,7 @@ public Component save(Component component) {
List<String> errors = validateComponent(component, null);

if (!errors.isEmpty()) {
throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors));
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Validación fallida:\n• " + String.join("\n• ", errors));
}

return componentRepository.save(component);
Expand Down Expand Up @@ -96,23 +98,21 @@ public Image addComponentImage(long id, MultipartFile imageFile) throws IOExcept
@PreAuthorize("hasRole('ADMIN')")
public void delete(long id) {

Optional<Component> deletedComponent = componentRepository.findById(id);

if (deletedComponent.isPresent()) {
componentRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE));

componentRepository.deleteById(id);

}
componentRepository.deleteById(id);

}

@PreAuthorize("hasRole('ADMIN')")
public Component updateComponent(Component newComponentData, long id) {

componentRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE));

List<String> errors = validateComponent(newComponentData, id);

if (!errors.isEmpty()) {
throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors));
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Validación fallida:\n• " + String.join("\n• ", errors));
}

Component component = componentRepository.findById(id).orElseThrow();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@

import javax.sql.rowset.serial.SerialBlob;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;

import es.codeurjcstudents.pcmod.model.Image;
import es.codeurjcstudents.pcmod.repository.ImageRepository;
Expand All @@ -17,6 +19,7 @@ public class ImageService {

private static final long MAX_SIZE = 10L * 1024L * 1024L; // 10MB
private static final List<String> ALLOWED_TYPES = List.of("image/jpeg", "image/png", "image/webp");
private static final String NOT_FOUND_MESSAGE = "Imagen no encontrada.";

private final ImageRepository imageRepository;

Expand Down Expand Up @@ -45,7 +48,7 @@ public Image createImage(InputStream inputStream) throws IOException {

public Image replaceImageFile(long id, InputStream inputStream) throws IOException {

Image image = imageRepository.findById(id).orElseThrow();
Image image = imageRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE));

try {
image.setImageFile(new SerialBlob(inputStream.readAllBytes()));
Expand All @@ -60,7 +63,7 @@ public Image replaceImageFile(long id, InputStream inputStream) throws IOExcepti

public Image deleteImage(long id) {

Image image = imageRepository.findById(id).orElseThrow();
Image image = imageRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE));
imageRepository.deleteById(id);

return image;
Expand All @@ -69,12 +72,12 @@ public Image deleteImage(long id) {
public void validate(MultipartFile imageField) {

if (imageField.getSize() > MAX_SIZE) {
throw new IllegalArgumentException("El tamaño de la imagen no puede superar los 10MB.");
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "El tamaño de la imagen no puede superar los 10MB.");
}

String contentType = imageField.getContentType();
if (contentType == null || !ALLOWED_TYPES.contains(contentType)) {
throw new IllegalArgumentException(
throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
"El tipo de archivo no es válido. Solo se permiten imágenes JPEG, PNG y WebP.");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ public class ReviewsService {
private final ComponentsRepository componentRepository;
private final UsersRepository userRepository;

private static final String NOT_FOUND_MESSAGE = "Reseña no encontrada.";
private static final String COMPONENT_NOT_FOUND_MESSAGE = "Componente no encontrado.";
private static final String USER_NOT_FOUND_MESSAGE = "Usuario no encontrado.";

public ReviewsService(ReviewsRepository reviewsRepository, ReviewMapper reviewMapper, ComponentsRepository componentRepository,
UsersRepository userRepository) {
this.reviewRepository = reviewsRepository;
Expand All @@ -44,10 +48,10 @@ public ReviewsService(ReviewsRepository reviewsRepository, ReviewMapper reviewMa
public Review createReview(Long userId, Long componentId, Review review) {

User user = userRepository.findById(userId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Usuario no encontrado."));
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, USER_NOT_FOUND_MESSAGE));

Component component = componentRepository.findById(componentId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Componente no encontrado."));
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, COMPONENT_NOT_FOUND_MESSAGE));

user.addReview(review);
component.addReview(review);
Expand All @@ -64,20 +68,20 @@ public Page<Review> findAllByComponent(long id, Pageable pageable) {
public Review save(Review review, long userId, long componentId) {

if (reviewRepository.existsByComponentIdAndUserId(componentId, userId)) {
throw new IllegalArgumentException("Validación fallida:\n• Ya existe una reseña de este producto para tu usuario.");
throw new ResponseStatusException(HttpStatus.CONFLICT, "Validación fallida:\n• Ya existe una reseña de este producto para tu usuario.");
}

List<String> errors = validateReview(review);

if (!errors.isEmpty()) {
throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors));
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Validación fallida:\n• " + String.join("\n• ", errors));
}

User user = userRepository.findById(userId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Usuario no encontrado."));
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, USER_NOT_FOUND_MESSAGE));

Component component = componentRepository.findById(componentId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Componente no encontrado."));
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, COMPONENT_NOT_FOUND_MESSAGE));

review.setDate(LocalDate.now(ZoneId.of("Europe/Madrid")));
user.addReview(review);
Expand All @@ -89,33 +93,29 @@ public Review save(Review review, long userId, long componentId) {
@PreAuthorize("hasRole('ADMIN') or @reviewsService.isOwner(#reviewId, principal.username)")
public void delete(long componentId, long reviewId) {

Optional<Review> reviewToDelete = reviewRepository.findById(reviewId);
Review reviewToDelete = reviewRepository.findById(reviewId).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE));

if ((reviewToDelete.isPresent()) && (reviewToDelete.get().getComponent().getId() != componentId)) {
if (reviewToDelete.getComponent().getId() != componentId) {
throw new NoSuchElementException("La reseña no pertenece a ese componente.");
}

if (reviewToDelete.isPresent()) {

reviewRepository.deleteById(reviewId);

}
reviewRepository.deleteById(reviewId);

}

@PreAuthorize("hasRole('ADMIN') or @reviewsService.isOwner(#reviewId, principal.username)")
public Review updateReview(Review newReviewData, long componentId, long reviewId) {

Optional<Review> reviewToUpdate = reviewRepository.findById(reviewId);
Review reviewToUpdate = reviewRepository.findById(reviewId).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE));

if ((reviewToUpdate.isPresent()) && (reviewToUpdate.get().getComponent().getId() != componentId)) {
if (reviewToUpdate.getComponent().getId() != componentId) {
throw new NoSuchElementException("La reseña no pertenece a ese componente.");
}

List<String> errors = validateReview(newReviewData);

if (!errors.isEmpty()) {
throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors));
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Validación fallida:\n• " + String.join("\n• ", errors));
}

Review review = reviewRepository.findById(reviewId).orElseThrow();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public class UsersService {

private static final String EMAIL_REGEX = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
private static final String PASS_REGEX = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&\\-_])[A-Za-z\\d@$!%*?&\\-_]{8,}$";
private static final String NOT_FOUND_MESSAGE = "Usuario no encontrado.";

public UsersService(UsersRepository userRepository, PasswordEncoder passwordEncoder, UserMapper userMapper,
ImageService imagesService) {
Expand All @@ -48,7 +49,7 @@ public User createUser(User user) {

public User getUser(long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Usuario no encontrado."));
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE));
}

public Resource getImageFile(long id) throws SQLException {
Expand All @@ -67,7 +68,7 @@ public User register(User user, String rawPassword) {
List<String> errors = validateUser(user, rawPassword, null);

if (!errors.isEmpty()) {
throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors));
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Validación fallida:\n• " + String.join("\n• ", errors));
}

User userToSave = new User(user.getName(), user.getSurname(), user.getUsername(), user.getAddress(),
Expand All @@ -81,7 +82,7 @@ public Image addUserImage(long id, MultipartFile imageFile) throws IOException {

imagesService.validate(imageFile);

User user = userRepository.findById(id).orElseThrow();
User user = userRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE));
Image image;

if (user.getImage() == null) {
Expand All @@ -98,23 +99,21 @@ public Image addUserImage(long id, MultipartFile imageFile) throws IOException {
@PreAuthorize("hasRole('ADMIN') or principal.username == #id.toString()")
public void deleteUser(long id) {

Optional<User> user = userRepository.findById(id);

if (user.isPresent()) {
userRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE));

userRepository.deleteById(id);

}
userRepository.deleteById(id);

}

@PreAuthorize("hasRole('ADMIN') or principal.username == #id.toString()")
public User updateUser(User newUserData, String rawPassword, long id) {

userRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE));

List<String> errors = validateUser(newUserData, rawPassword, id);

if (!errors.isEmpty()) {
throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors));
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Validación fallida:\n• " + String.join("\n• ", errors));
}

User user = userRepository.findById(id).orElseThrow();
Expand Down
Loading
Loading