Skip to content

Commit

Permalink
refactor: 세션 속성에 대한 enum 클래스 생성
Browse files Browse the repository at this point in the history
  • Loading branch information
JJ503 committed May 5, 2024
1 parent edd8e7f commit e9323a4
Show file tree
Hide file tree
Showing 10 changed files with 74 additions and 32 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.USER_ID;

@Getter
public class WebSocketSessions {

protected static final String CHAT_ROOM_ID_KEY = "chatRoomId";
private static final String USER_ID_KEY = "userId";

private final Set<WebSocketSession> sessions = Collections.newSetFromMap(new ConcurrentHashMap<>());

Expand All @@ -24,7 +25,7 @@ public void putIfAbsent(final WebSocketSession session, final Long chatRoomId) {

public boolean contains(final Long userId) {
return sessions.stream()
.anyMatch(session -> session.getAttributes().get(USER_ID_KEY) == userId);
.anyMatch(session -> session.getAttributes().get(USER_ID.getName()) == userId);
}

public void remove(final WebSocketSession session) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,14 @@
import java.util.Set;
import java.util.stream.Collectors;

import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.CONNECTED;
import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.USER_ID;

@Slf4j
@Component
@RequiredArgsConstructor
public class ChatWebSocketHandleTextMessageProvider implements WebSocketHandleTextMessageProvider {

private static final String CONNECTED_KEY = "connected";

private final WebSocketChatSessions sessions;
private final ObjectMapper objectMapper;
private final MessageService messageService;
Expand Down Expand Up @@ -123,7 +124,7 @@ private TextMessage createTextMessage(
}

private boolean isMyMessage(final WebSocketSession session, final Long writerId) {
final long userId = Long.parseLong(String.valueOf(session.getAttributes().get("userId")));
final long userId = Long.parseLong(String.valueOf(session.getAttributes().get(USER_ID.getName())));

return writerId.equals(userId);
}
Expand Down Expand Up @@ -166,13 +167,13 @@ private Set<WebSocketSession> getWebSocketSessions() {

private void sendPingMessage(final WebSocketSession session) {
final Map<String, Object> attributes = session.getAttributes();
final boolean connected = (boolean) attributes.get(CONNECTED_KEY);
final boolean connected = (boolean) attributes.get(CONNECTED.getName());
if (!connected) {
sessions.remove(session);
return;
}

attributes.put(CONNECTED_KEY, false);
attributes.put(CONNECTED.getName(), false);
try {
session.sendMessage(new PingMessage());
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@

import java.util.Map;

import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.BASE_URL;
import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.CONNECTED;
import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.USER_ID;

@Component
@RequiredArgsConstructor
public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor {
Expand All @@ -27,9 +31,9 @@ public boolean beforeHandshake(
final WebSocketHandler wsHandler,
final Map<String, Object> attributes
) throws Exception {
attributes.put("userId", findUserId(request));
attributes.put("baseUrl", ImageRelativeUrl.USER.calculateAbsoluteUrl());
attributes.put("connected", true);
attributes.put(USER_ID.getName(), findUserId(request));
attributes.put(BASE_URL.getName(), ImageRelativeUrl.USER.calculateAbsoluteUrl());
attributes.put(CONNECTED.getName(), true);

return super.beforeHandshake(request, response, wsHandler, attributes);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,21 @@
import java.util.List;
import java.util.Map;

import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.CONNECTED;
import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.TYPE;

@Component
@RequiredArgsConstructor
public class WebSocketHandler extends TextWebSocketHandler {

private static final String TYPE_KEY = "type";
private static final String CONNECTED_KEY = "connected";

private final WebSocketHandleTextMessageProviderComposite providerComposite;
private final ObjectMapper objectMapper;

@Override
protected void handleTextMessage(final WebSocketSession session, final TextMessage message) throws Exception {
final String payload = message.getPayload();
System.out.println(payload);
final TextMessageDto textMessageDto = objectMapper.readValue(payload, TextMessageDto.class);
session.getAttributes().put(TYPE_KEY, textMessageDto.type());
session.getAttributes().put(TYPE.getName(), textMessageDto.type());

final WebSocketHandleTextMessageProvider provider = providerComposite.findProvider(textMessageDto.type());
final List<SendMessageDto> sendMessageDtos = provider.handleCreateSendMessage(session, textMessageDto.data());
Expand All @@ -42,7 +41,7 @@ protected void handleTextMessage(final WebSocketSession session, final TextMessa

@Override
public void afterConnectionClosed(final WebSocketSession session, final CloseStatus status) {
final String type = String.valueOf(session.getAttributes().get(TYPE_KEY));
final String type = String.valueOf(session.getAttributes().get(TYPE.getName()));
final TextMessageType textMessageType = TextMessageType.valueOf(type);
final WebSocketHandleTextMessageProvider provider = providerComposite.findProvider(textMessageType);
provider.remove(session);
Expand All @@ -51,6 +50,6 @@ public void afterConnectionClosed(final WebSocketSession session, final CloseSta
@Override
public void handlePongMessage(WebSocketSession session, PongMessage message) {
final Map<String, Object> attributes = session.getAttributes();
attributes.put(CONNECTED_KEY, true);
attributes.put(CONNECTED.getName(), true);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.ddang.ddang.websocket.handler.dto;

import lombok.Getter;

@Getter
public enum WebSocketAttributeKey {

USER_ID("userId"),
BASE_URL("baseUrl"),
CONNECTED("connected"),
TYPE("type");

private final String name;

WebSocketAttributeKey(final String name) {
this.name = name;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@
import java.util.HashMap;
import java.util.Map;

import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.BASE_URL;
import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.CONNECTED;
import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.USER_ID;

@SuppressWarnings("NonAsciiCharacters")
public class WebSocketSessionsTestFixture {

protected Long 사용자_아이디 = 1L;
protected Map<String, Object> 세션_attribute_정보 = new HashMap<>(Map.of("userId", 사용자_아이디, "baseUrl", "/images"));
protected Map<String, Object> 세션_attribute_정보 = new HashMap<>(
Map.of(USER_ID.getName(), 사용자_아이디, BASE_URL.getName(), "/images", CONNECTED.getName(), true)
);
protected Long 채팅방_아이디 = 1L;
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
import java.util.HashMap;
import java.util.Map;

import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.BASE_URL;
import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.CONNECTED;
import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.USER_ID;

@SuppressWarnings("NonAsciiCharacters")
public class ChatWebSocketHandleTextMessageProviderTestFixture {

Expand Down Expand Up @@ -87,19 +91,19 @@ void setUpFixture() {
chatRoomRepository.save(채팅방);

발신자_세션_attribute_정보 = new HashMap<>(Map.of(
"userId", 발신자.getId(),
"baseUrl", "/images",
"connected", true
USER_ID.getName(), 발신자.getId(),
BASE_URL.getName(), "/images",
CONNECTED.getName(), true
));
수신자_세션_attribute_정보 = new HashMap<>(Map.of(
"userId", 수신자.getId(),
"baseUrl", "/images",
"connected", true
USER_ID.getName(), 수신자.getId(),
BASE_URL.getName(), "/images",
CONNECTED.getName(), true
));
연결이_끊긴_세션_attribute_정보 = new HashMap<>(Map.of(
"userId", 수신자.getId(),
"baseUrl", "/images",
"connected", false
USER_ID.getName(), 수신자.getId(),
BASE_URL.getName(), "/images",
CONNECTED.getName(), false
));
메시지_전송_데이터 = Map.of(
"chatRoomId", String.valueOf(채팅방.getId()),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@
import java.util.List;
import java.util.Map;

import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.BASE_URL;
import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.CONNECTED;
import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.USER_ID;

@SuppressWarnings("NonAsciiCharacters")
public class NotificationEventListenerFixture {

Expand Down Expand Up @@ -117,8 +121,9 @@ void setUpFixture() {
bidRepository.save(bid);

세션_attribute_정보 = new HashMap<>(Map.of(
"userId", 발신자_겸_판매자.getId(),
"baseUrl", 이미지_절대_경로
USER_ID.getName(), 발신자_겸_판매자.getId(),
BASE_URL.getName(), 이미지_절대_경로,
CONNECTED.getName(), true
));
메시지_전송_데이터 = Map.of(
"chatRoomId", String.valueOf(채팅방.getId()),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import java.util.List;

import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.CONNECTED;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
Expand Down Expand Up @@ -81,6 +82,6 @@ class WebSocketHandlerTest extends WebSocketHandlerTestFixture {
webSocketHandler.handlePongMessage(session, new PongMessage());

// then
assertThat((boolean) 세션_attribute_정보.get(연결_상태_키)).isTrue();
assertThat((boolean) 세션_attribute_정보.get(CONNECTED.getName())).isTrue();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,18 @@
import java.util.HashMap;
import java.util.Map;

import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.BASE_URL;
import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.CONNECTED;
import static com.ddang.ddang.websocket.handler.dto.WebSocketAttributeKey.USER_ID;

@SuppressWarnings("NonAsciiCharacters")
public class WebSocketHandlerTestFixture {

protected Long 사용자_아이디 = 1L;
protected String 연결_상태_키 = "connected";
protected Map<String, Object> 세션_attribute_정보 = new HashMap<>(
Map.of(
"type", TextMessageType.CHATTINGS.name(),
"data", Map.of("userId", 사용자_아이디, "baseUrl", "/images", 연결_상태_키, false)
"data", Map.of(USER_ID.getName(), 사용자_아이디, BASE_URL.getName(), "/images", CONNECTED.getName(), false)
)
);
protected TextMessage 전송할_메시지 = new TextMessage("메시지");
Expand Down

0 comments on commit e9323a4

Please sign in to comment.