Skip to content

Commit

Permalink
Merge pull request #124 from Team-B1ND/Refactor/#123
Browse files Browse the repository at this point in the history
Refactor #123: PushAlarmAspect에서 AOP @around -> @AfterReturning
  • Loading branch information
dongchandev authored Nov 11, 2024
2 parents 103ef34 + c322cfb commit 2a054dc
Show file tree
Hide file tree
Showing 17 changed files with 64 additions and 64 deletions.
2 changes: 1 addition & 1 deletion dodam-application/dodam-rest-api/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ dependencies {
implementation project(':dodam-in-system-available:dodam-discord-webhook-client')
implementation project(':dodam-in-system-available:dodam-gabia-client')
implementation project(':dodam-in-system-available:dodam-melon-chart-client')
implementation project(':dodam-in-system-available:dodam-ncp-object-storage-client')
implementation project(':dodam-in-system-available:dodam-simple-storage-service-client')
implementation project(':dodam-in-system-available:dodam-neis-meal-client')
implementation project(':dodam-in-system-available:dodam-token-client')
implementation project(':dodam-in-system-available:dodam-youtube-video-client')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public CompletableFuture<ResponseData<LoginRes>> login(LoginReq req) {
member.checkIfPasswordIsCorrect(Sha512PasswordEncoder.encode(req.pw()));
member.checkIfStatusIncorrect();
member.updatePushToken(req.pushToken());
memberRepository.save(member);
return CompletableFuture.supplyAsync(() -> member, executor)
.thenCompose(m -> tokenClient.issueTokens(member.getId(), member.getRole().getNumber()))
.thenApply(tokens -> new LoginRes(member, tokens.accessToken(), tokens.refreshToken()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ public class BusUseCase {
@Transactional(rollbackFor = Exception.class)
public Response register(BusReq req) {
busRepository.save(req.mapToBus());
Optional<List<String>> pushTokens = Optional.of(studentRepository.findAllMembers().stream().map(Member::getPushToken).toList());
List<String> pushTokens = studentRepository.findAllMembers().stream()
.map(Member::getPushToken).toList();
fcmClient.sendMessages(pushTokens, "귀가버스 신청", "귀가 버스 신청이 가능해요! 신청해주세요.");
return Response.created("버스 등록 성공");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
import b1nd.dodam.domain.rds.member.entity.Student;
import b1nd.dodam.domain.rds.member.entity.Teacher;
import b1nd.dodam.domain.rds.member.enumeration.ActiveStatus;
import b1nd.dodam.domain.rds.member.enumeration.MemberRole;
import b1nd.dodam.domain.rds.member.event.StudentRegisteredEvent;
import b1nd.dodam.domain.rds.member.exception.*;
import b1nd.dodam.domain.rds.member.exception.BroadcastClubMemberDuplicateException;
import b1nd.dodam.domain.rds.member.exception.MemberDuplicateException;
import b1nd.dodam.domain.rds.member.repository.BroadcastClubMemberRepository;
import b1nd.dodam.domain.rds.member.repository.MemberRepository;
import b1nd.dodam.domain.rds.member.repository.StudentRepository;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ public class NightStudyPushAlarmScheduler {
private final NightStudyService service;
private final FCMClient fcmClient;

@Scheduled(cron = "0 0 11 * * ?")
@Scheduled(cron = "0 0 8 * * ?")
public void scheduledPushAlarm() {
List<NightStudy> nightStudies = service.getByEndDate(LocalDate.now().minusDays(1));
List<String> tokens = nightStudies.stream()
.map(n -> n.getStudent().getMember().getPushToken())
.toList();
fcmClient.sendMessages(Optional.of(tokens), "심야자습 만료", "심야자습이 만료됐어요.");
fcmClient.sendMessages(tokens, "심야자습 만료", "심야자습이 만료됐어요.");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,13 @@ private void throwExceptionWhenStudentIsNotApplicant(NightStudy nightStudy, Stud
}
}

@PushAlarmEvent(target = "심야자습", status = ApprovalStatus.PENDING)
@PushAlarmEvent(target = "심야자습", status = ApprovalStatus.ALLOWED)
public Response allow(Long id) {
modifyStatus(id, ApprovalStatus.ALLOWED, null);
return Response.noContent("심야자습 승인 성공");
}

@PushAlarmEvent(target = "심야자습", status = ApprovalStatus.PENDING)
@PushAlarmEvent(target = "심야자습", status = ApprovalStatus.REJECTED)
public Response reject(Long id, Optional<RejectNightStudyReq> req) {
modifyStatus(id, ApprovalStatus.REJECTED, req.map(RejectNightStudyReq::rejectReason).orElse(null));
return Response.noContent("심야자습 거절 성공");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,8 @@
import b1nd.dodam.restapi.outgoing.application.data.res.OutGoingRes;
import b1nd.dodam.restapi.support.data.Response;
import b1nd.dodam.restapi.support.data.ResponseData;
import b1nd.dodam.restapi.support.pushalarm.ApprovalAlarmUtil;
import b1nd.dodam.restapi.support.pushalarm.PushAlarmEvent;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,13 @@ public void throwExceptionWhenStudentIsNotApplicant(OutSleeping o) {
}
}

@PushAlarmEvent(target = "외박", status = ApprovalStatus.PENDING)
@PushAlarmEvent(target = "외박", status = ApprovalStatus.ALLOWED)
public Response allow(Long id) {
modifyStatus(id, ApprovalStatus.ALLOWED, null);
return Response.noContent("외박 승인 성공");
}

@PushAlarmEvent(target = "외박", status = ApprovalStatus.PENDING)
@PushAlarmEvent(target = "외박", status = ApprovalStatus.REJECTED)
public Response reject(Long id, Optional<RejectOutSleepingReq> req) {
modifyStatus(id, ApprovalStatus.REJECTED, req.map(RejectOutSleepingReq::rejectReason).orElse(null));
return Response.noContent("외박 거절 성공");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import b1nd.dodam.simple.storage.service.client.SimpleStorageServiceClient;
import b1nd.dodam.restapi.support.data.ResponseData;
import b1nd.dodam.simple.storage.service.client.SimpleStorageServiceClient;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
import b1nd.dodam.domain.rds.support.enumeration.ApprovalStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.ApplicationEventPublisher;
Expand All @@ -26,29 +28,17 @@ public class PushAlarmAspect {
private final OutGoingService outGoingService;
private final OutSleepingService outSleepingService;

@Around("@annotation(pushAlarmEvent)")
public Object handlePushAlarmEvent(ProceedingJoinPoint joinPoint, PushAlarmEvent pushAlarmEvent) {

Object result = proceedJoinPointSafely(joinPoint);

Long id = getIdFromArgs(joinPoint.getArgs());
String rejectReason = getRejectReasonFromArgs(joinPoint.getArgs());
@AfterReturning(pointcut = "@annotation(pushAlarmEvent)")
public void handlePushAlarmEvent(JoinPoint joinPoint, PushAlarmEvent pushAlarmEvent) {
Object[] args = joinPoint.getArgs();
String target = pushAlarmEvent.target();
ApprovalStatus status = pushAlarmEvent.status();

Student student = getStudentByTargetAndId(target, id);

sendPushAlarm(student, target, rejectReason, status);

return result;
}

private Object proceedJoinPointSafely(ProceedingJoinPoint joinPoint) {
try {
return joinPoint.proceed();
} catch (Throwable e) {
throw new InternalServerException();
}
sendPushAlarm(
getStudentByTargetAndId(target, getIdFromArgs(args)),
target,
getRejectReasonFromArgs(args, status),
status
);
}

private Long getIdFromArgs(Object[] args) {
Expand All @@ -59,10 +49,9 @@ private Long getIdFromArgs(Object[] args) {
}
}

private String getRejectReasonFromArgs(Object[] args) {
if (args.length > 1 && args[1] instanceof Optional<?> optionalArg) {
private String getRejectReasonFromArgs(Object[] args, ApprovalStatus status) {
if (status == ApprovalStatus.REJECTED && args[1] instanceof Optional<?> optionalArg)
return (String) optionalArg.orElse(null);
}
return null;
}

Expand All @@ -72,12 +61,12 @@ private Student getStudentByTargetAndId(String target, Long id) {
case "외박" -> outSleepingService.getById(id).getStudent();
case "심야자습" -> nightStudyService.getBy(id).getStudent();
default -> throw new InternalServerException();

};
}

private void sendPushAlarm(Student student, String target, String rejectReason, ApprovalStatus status) {
String pushToken = student.getMember().getPushToken();
ApprovalAlarmEvent alarmEvent = ApprovalAlarmUtil.createAlarmEvent(pushToken, target, rejectReason, status);
eventPublisher.publishEvent(alarmEvent);
eventPublisher.publishEvent(ApprovalAlarmUtil.createAlarmEvent(
student.getMember().getPushToken(), target, rejectReason, status));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ spring:
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
hikari:
connection-timeout: 20000 # ??? ???? (20?)
maximum-pool-size: 10 # ?? ??? ? ?? (10?)
minimum-idle: 2 # ?? ?? ??? ? (2?)
idle-timeout: 30000 # ?? ??? ???? (30?)
connection-timeout: 20000
maximum-pool-size: 10
minimum-idle: 2
idle-timeout: 30000
pool-name: MyHikariCP
servlet:
multipart:
Expand All @@ -22,7 +22,7 @@ spring:
static-locations: classpath:/static/
jpa:
hibernate:
ddl-auto: none
ddl-auto: update
properties:
hibernate:
show_sql: false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ dependencies {
implementation 'com.google.firebase:firebase-admin:9.3.0'
implementation 'org.springframework:spring-context:6.0.6'
implementation 'org.springframework.boot:spring-boot:3.0.4'
implementation 'org.apache.commons:commons-lang3:3.13.0'
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,48 @@
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.Notification;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

@Component
@RequiredArgsConstructor
public class FCMClient {
public void sendMessage(String pushToken, String title, String body) {
try {
if(pushToken != null && !pushToken.isBlank()){
FirebaseMessaging.getInstance().send(Message.builder()
.setNotification(Notification.builder()
.setTitle(title)
.setBody(body)
.build())
.setToken(pushToken)
.build());
}
if (StringUtils.isEmpty(pushToken)) return;

FirebaseMessaging.getInstance().send(Message.builder()
.setNotification(Notification.builder()
.setTitle(title)
.setBody(body)
.build())
.setToken(pushToken)
.build());
} catch (FirebaseMessagingException e){
throw new InternalServerException();
}
}

public void sendMessages(Optional<List<String>> pushTokens, String title, String body) {
public void sendMessages(List<String> pushTokens, String title, String body) {
Notification notification = Notification.builder()
.setTitle(title)
.setBody(body)
.build();

List<Message> messages = pushTokens.stream()
.filter(StringUtils::isNotBlank)
.map(token -> Message.builder()
.setNotification(notification)
.setToken(token.toString())
.setToken(token)
.build()
).toList();
)
.toList();

if (!messages.isEmpty()) {
FirebaseMessaging.getInstance().sendEachAsync(messages);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ dependencies {
implementation 'org.springframework:spring-web:6.0.6'

implementation 'org.springframework.boot:spring-boot:3.0.4'
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
Expand All @@ -21,12 +20,13 @@ public class SimpleStorageServiceClient {

public String uploadFile(MultipartFile multipartFile) {
String bucket = cloudProperties.storage().getBucket();
try {
String originalFilename = bucket + "/" + UUID.randomUUID() + multipartFile.getOriginalFilename();

ObjectMetadata metadata = createObjectMetadata(multipartFile);

try (InputStream inputStream = multipartFile.getInputStream()){
amazonS3Client.putObject(new PutObjectRequest(bucket, originalFilename, inputStream, metadata));
PutObjectRequest request = new PutObjectRequest(bucket, originalFilename, multipartFile.getInputStream(), metadata);
amazonS3Client.putObject(request);

return amazonS3Client.getUrl(bucket, originalFilename).toString();
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package b1nd.dodam.simple.storage.service.client.storage.client;
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

@Getter
@Entity(name = "member")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
Expand Down Expand Up @@ -102,7 +100,9 @@ public void checkIfStatusIncorrect() {
}

public void updatePushToken(String pushToken){
this.pushToken = pushToken;
if(StringUtils.isNotBlank(pushToken)){
this.pushToken = pushToken;
}
}

}

0 comments on commit 2a054dc

Please sign in to comment.