Skip to content

Commit

Permalink
Merge pull request #155 from Link-MIND/test
Browse files Browse the repository at this point in the history
[Merge] 용감한 미혜
  • Loading branch information
sss4920 authored Jan 17, 2024
2 parents c35ae4a + e727f1a commit 11fcf19
Show file tree
Hide file tree
Showing 12 changed files with 96 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,18 @@

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.stereotype.Component;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

import com.app.toaster.common.dto.ApiResponse;
import com.app.toaster.exception.Error;
Expand All @@ -25,6 +28,7 @@
import io.sentry.Sentry;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintDefinitionException;
import jakarta.validation.ConstraintViolationException;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;

Expand Down Expand Up @@ -54,29 +58,57 @@ protected ResponseEntity<ApiResponse> handleConstraintDefinitionException(final
}

@ExceptionHandler(MalformedURLException.class)
protected ApiResponse handleConstraintDefinitionException(final MalformedURLException e) {
protected ResponseEntity<ApiResponse> handleConstraintDefinitionException(final MalformedURLException e) {
Sentry.captureException(e);
return ApiResponse.error(Error.MALFORMED_URL_EXEPTION, Error.MALFORMED_URL_EXEPTION.getMessage());
return ResponseEntity.status(Error.MALFORMED_URL_EXEPTION.getErrorCode())
.body(ApiResponse.error(Error.MALFORMED_URL_EXEPTION, Error.MALFORMED_URL_EXEPTION.getMessage()));
}

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(DateTimeParseException.class)
protected ApiResponse handleDateTimeParseException(final DateTimeParseException e) {
return ApiResponse.error(Error.BAD_REQUEST_REMIND_TIME, Error.BAD_REQUEST_REMIND_TIME.getMessage());
protected ResponseEntity<ApiResponse> handleDateTimeParseException(final DateTimeParseException e) {
return ResponseEntity.status(Error.BAD_REQUEST_REMIND_TIME.getErrorCode())
.body(ApiResponse.error(Error.BAD_REQUEST_REMIND_TIME, Error.BAD_REQUEST_REMIND_TIME.getMessage()));
}

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
protected ApiResponse handleHttpRequestMethodNotSupportedException(final HttpRequestMethodNotSupportedException e) {
return ApiResponse.error(Error.REQUEST_METHOD_VALIDATION_EXCEPTION, e.getMessage());
protected ResponseEntity<ApiResponse> handleHttpRequestMethodNotSupportedException(final HttpRequestMethodNotSupportedException e) {
return ResponseEntity.status(e.getStatusCode())
.body(ApiResponse.error(Error.REQUEST_METHOD_VALIDATION_EXCEPTION, Error.REQUEST_METHOD_VALIDATION_EXCEPTION.getMessage()));
}

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
protected ApiResponse handleHttpMediaTypeNotSupportedException(final HttpMediaTypeNotSupportedException e) {
return ApiResponse.error(Error.REQUEST_MEDIA_TYPE_VALIDATION_EXCEPTION, e.getMessage());
protected ResponseEntity<ApiResponse> handleHttpMediaTypeNotSupportedException(final HttpMediaTypeNotSupportedException e) {
return ResponseEntity.status(e.getStatusCode())
.body(ApiResponse.error(Error.REQUEST_MEDIA_TYPE_VALIDATION_EXCEPTION, Error.REQUEST_MEDIA_TYPE_VALIDATION_EXCEPTION.getMessage()));
}

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MissingServletRequestParameterException.class)
protected ResponseEntity<ApiResponse> MissingServletRequestParameterException(final MissingServletRequestParameterException e) {
return ResponseEntity.status(e.getStatusCode())
.body(ApiResponse.error(Error.BAD_REQUEST_VALIDATION, Error.BAD_REQUEST_VALIDATION.getMessage()));
}

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
protected ResponseEntity<ApiResponse> MissingServletRequestParameterException(final HttpMessageNotReadableException e) {
return ResponseEntity.status(Error.BAD_REQUEST_VALIDATION.getErrorCode())
.body(ApiResponse.error(Error.BAD_REQUEST_VALIDATION, Error.BAD_REQUEST_VALIDATION.getMessage()));
}

@ResponseStatus(HttpStatus.BAD_REQUEST) // 커스텀 validation 에러 핸들링.
@ExceptionHandler(HandlerMethodValidationException.class)
protected ResponseEntity<ApiResponse> ConstraintViolationException(final HandlerMethodValidationException e) {
Sentry.captureException(e);
return ResponseEntity.status(Error.BAD_REQUEST_VALIDATION.getErrorCode())
.body(ApiResponse.error(Error.BAD_REQUEST_VALIDATION, Error.BAD_REQUEST_VALIDATION.getMessage()));
}




/**
* 500 Internal Server Error
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@
import com.app.toaster.controller.response.toast.ToastFilter;
import com.app.toaster.controller.response.category.CategoryResponse;
import com.app.toaster.controller.response.category.GetCategoryResponseDto;
import com.app.toaster.controller.valid.Severity;
import com.app.toaster.controller.valid.TitleValid;
import com.app.toaster.exception.Success;
import com.app.toaster.service.category.CategoryService;
import com.app.toaster.service.search.SearchService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
Expand Down Expand Up @@ -87,12 +90,12 @@ public ApiResponse<GetCategoryResponseDto> getCategory(


@GetMapping("/search")
public ApiResponse searchProducts(@UserId Long userId ,@RequestParam("query") String query){
public ApiResponse searchProducts(@UserId Long userId , @TitleValid(payload = Severity.Error.class) @RequestParam("query") String query){
return searchService.searchMain(userId,query);
}

@GetMapping("/check")
public ApiResponse checkDuplicatedNickname(@UserId Long userId ,@RequestParam("title") String title){
public ApiResponse checkDuplicatedCategoryTitle(@UserId Long userId ,@RequestParam("title") String title){
return ApiResponse.success(Success.GET_DUPLICATED_SUCCESS, categoryService.checkDuplicatedTitle(userId,title));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import com.app.toaster.common.dto.ApiResponse;
import com.app.toaster.config.UserId;
import com.app.toaster.controller.valid.TitleValid;
import com.app.toaster.service.UserService;
import com.app.toaster.service.search.SearchService;
import com.app.toaster.service.toast.ToastService;
Expand All @@ -18,7 +19,7 @@ public class MainController {
private final SearchService searchService;

@GetMapping("/search")
public ApiResponse searchProducts(@UserId Long userId ,@RequestParam("query") String query){
public ApiResponse searchProducts(@UserId Long userId ,@TitleValid @RequestParam("query") String query){
return searchService.searchMain(userId,query);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.app.toaster.controller.valid;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.ArrayList;
Expand All @@ -10,7 +11,7 @@

@Documented
@Constraint(validatedBy = TitleValidator.class)
@Target({java.lang.annotation.ElementType.FIELD})
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
public @interface TitleValid {
String message() default "Invalid title";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ public boolean isValid(String title, ConstraintValidatorContext context) {
return false;
}

if(!title.matches("^[\\S][가-힣a-zA-Z0-9\\s]{0,20}$")){
context.buildConstraintViolationWithTemplate("특수 문자로는 검색할 수 없어요.")
.addConstraintViolation();
return false;
}

return true;
}
}
}
9 changes: 8 additions & 1 deletion linkmind/src/main/java/com/app/toaster/domain/Reminder.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@
import org.springframework.format.annotation.DateTimeFormat;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Reminder extends BaseTimeEntity {
public class Reminder{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
Expand All @@ -37,6 +38,8 @@ public class Reminder extends BaseTimeEntity {

private Boolean isAlarm;

private LocalDateTime updateAt = LocalDateTime.now();

@Builder
public Reminder(User user, Category category, String comment, LocalTime remindTime, ArrayList<Integer> remindDates, Boolean isAlarm) {
this.user = user;
Expand All @@ -63,4 +66,8 @@ public void changeAlarm(){
this.isAlarm = !isAlarm;
}

public void setUpdatedAtNow(){
this.updateAt = LocalDateTime.now();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public enum Success {
CHANGE_TIMER_ALARM_SUCCESS(HttpStatus.OK, "타이머 알람여부 수정 완료"),
PUSH_ALARM_PERIODIC_SUCCESS(HttpStatus.OK, "푸시알림 활성에 성공했습니다."),
PUSH_ALARM_SUCCESS(HttpStatus.OK, "푸시알림 전송에 성공했습니다."),
CLEAR_SCHEDULED_TASKS_SUCCESS(HttpStatus.OK, "스케줄러에서 예약된 작업을 제거했습니다."),


/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@
import com.app.toaster.exception.Success;
import com.app.toaster.external.client.fcm.FCMService;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.units.qual.A;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

import static com.app.toaster.external.client.fcm.FCMService.clearScheduledTasks;

@RestController
@RequestMapping("/alarm")
@RequiredArgsConstructor
Expand Down Expand Up @@ -42,4 +45,11 @@ public ApiResponse sendTopicScheduledTest(@RequestBody FCMPushRequestDto request
sqsProducer.sendMessage(request);
return ApiResponse.success(Success.PUSH_ALARM_PERIODIC_SUCCESS);
}

@DeleteMapping("/clear")
@ResponseStatus(HttpStatus.OK)
public ApiResponse deleteScheduledTasks(){
clearScheduledTasks();
return ApiResponse.success(Success.CLEAR_SCHEDULED_TASKS_SUCCESS);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,24 @@ public interface CategoryRepository extends JpaRepository<Category, Long> {

@Modifying
@Query("UPDATE Category c SET c.priority = c.priority - 1 " +
"WHERE c.categoryId != :categoryId AND c.priority > :currentPriority AND c.priority <= :newPriority")
"WHERE c.categoryId != :categoryId AND c.user.userId =:userId AND c.priority > :currentPriority AND c.priority <= :newPriority")
void decreasePriorityByOne(@Param("categoryId") Long categoryId,
@Param("currentPriority") int currentPriority,
@Param("newPriority") int newPriority);
@Param("newPriority") int newPriority,
@Param("userId")Long userId);

@Modifying
@Query("UPDATE Category c SET c.priority = c.priority + 1 " +
"WHERE c.categoryId != :categoryId AND c.priority >= :newPriority AND c.priority < :currentPriority")
"WHERE c.categoryId != :categoryId AND c.user.userId =:userId AND c.priority >= :newPriority AND c.priority < :currentPriority")
void increasePriorityByOne(@Param("categoryId") Long categoryId,
@Param("currentPriority") int currentPriority,
@Param("newPriority") int newPriority);
@Param("newPriority") int newPriority,
@Param("userId")Long userId);

@Modifying
@Query("UPDATE Category c SET c.priority = c.priority - 1 " +
"WHERE c.categoryId != :categoryId AND c.priority > :currentPriority")
void decreasePriorityNextDeleteCategory(@Param("categoryId") Long categoryId, @Param("currentPriority") int currentPriority);
"WHERE c.categoryId != :categoryId AND c.user.userId =:userId AND c.priority > :currentPriority")
void decreasePriorityNextDeleteCategory(@Param("categoryId") Long categoryId, @Param("currentPriority") int currentPriority,@Param("userId")Long userId);

@Query("SELECT c FROM Category c WHERE " +
"c.user.userId = :userId and " +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public void deleteCategory(final ArrayList<Long> deleteCategoryDto){
Category category = categoryRepository.findById(categoryId)
.orElseThrow(() -> new NotFoundException(Error.NOT_FOUND_CATEGORY_EXCEPTION, Error.NOT_FOUND_CATEGORY_EXCEPTION.getMessage()));

categoryRepository.decreasePriorityNextDeleteCategory(categoryId, category.getPriority());
categoryRepository.decreasePriorityNextDeleteCategory(categoryId, category.getPriority(),category.getUser().getUserId());

Reminder timer = timerRepository.findByCategory_CategoryId(categoryId);
if(timer != null)
Expand Down Expand Up @@ -137,9 +137,9 @@ public void editCategoryPriority(ChangeCateoryPriorityDto changeCateoryPriorityD
category.updateCategoryPriority(changeCateoryPriorityDto.newPriority());

if(currentPriority < newPriority)
categoryRepository.decreasePriorityByOne(changeCateoryPriorityDto.categoryId(), currentPriority, newPriority);
categoryRepository.decreasePriorityByOne(changeCateoryPriorityDto.categoryId(), currentPriority, newPriority, category.getUser().getUserId());
else if (currentPriority > newPriority)
categoryRepository.increasePriorityByOne(changeCateoryPriorityDto.categoryId(), currentPriority, newPriority);
categoryRepository.increasePriorityByOne(changeCateoryPriorityDto.categoryId(), currentPriority, newPriority,category.getUser().getUserId());


}
Expand Down Expand Up @@ -173,4 +173,5 @@ public DuplicatedResponse checkDuplicatedTitle(Long userId, String title){
return DuplicatedResponse.of(categoryRepository.existsCategoriesByUserAndTitle(findUser(userId), title));

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@
import com.app.toaster.domain.User;
import com.app.toaster.exception.Error;
import com.app.toaster.exception.Success;
import com.app.toaster.exception.model.BadRequestException;
import com.app.toaster.exception.model.CustomException;
import com.app.toaster.exception.model.NotFoundException;
import com.app.toaster.infrastructure.CategoryRepository;
import com.app.toaster.infrastructure.ToastRepository;
import com.app.toaster.infrastructure.UserRepository;
import com.google.protobuf.Api;

import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;

@Service
Expand All @@ -33,6 +35,10 @@ public class SearchService {
private final CategoryRepository categoryRepository;

public ApiResponse<SearchMainResult> searchMain(Long userId, String searchParam){
if(searchParam.isBlank()){
throw new BadRequestException(Error.BAD_REQUEST_VALIDATION, Error.BAD_REQUEST_URL.getMessage());
}

User presentUser = userRepository.findByUserId(userId).orElseThrow(
()-> new NotFoundException(Error.NOT_FOUND_USER_EXCEPTION, Error.NOT_FOUND_USER_EXCEPTION.getMessage())
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ public void updateTimerDatetime(Long userId, Long timerId, UpdateTimerDateTimeDt
}
reminder.updateRemindDates(updateTimerDateTimeDto.remindDates());
reminder.updateRemindTime(updateTimerDateTimeDto.remindTime());

reminder.setUpdatedAtNow();
em.flush();

LocalDateTime now = LocalDateTime.now();
Expand Down Expand Up @@ -139,6 +141,7 @@ public void updateTimerComment(Long userId, Long timerId, UpdateTimerCommentDto
}

reminder.updateComment(updateTimerCommentDto.newComment());
reminder.setUpdatedAtNow();

}

Expand Down

0 comments on commit 11fcf19

Please sign in to comment.