-
Notifications
You must be signed in to change notification settings - Fork 316
/
PresenceEventListener.java
62 lines (47 loc) · 2.13 KB
/
PresenceEventListener.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.sergialmar.wschat.event;
import java.util.Optional;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
/**
* Listener to track user presence.
* Sends notifications to the login destination when a connected event is received
* and notifications to the logout destination when a disconnect event is received
*
* @author Sergi Almar
*/
public class PresenceEventListener {
private ParticipantRepository participantRepository;
private SimpMessagingTemplate messagingTemplate;
private String loginDestination;
private String logoutDestination;
public PresenceEventListener(SimpMessagingTemplate messagingTemplate, ParticipantRepository participantRepository) {
this.messagingTemplate = messagingTemplate;
this.participantRepository = participantRepository;
}
@EventListener
private void handleSessionConnected(SessionConnectEvent event) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(event.getMessage());
String username = headers.getUser().getName();
LoginEvent loginEvent = new LoginEvent(username);
messagingTemplate.convertAndSend(loginDestination, loginEvent);
// We store the session as we need to be idempotent in the disconnect event processing
participantRepository.add(headers.getSessionId(), loginEvent);
}
@EventListener
private void handleSessionDisconnect(SessionDisconnectEvent event) {
Optional.ofNullable(participantRepository.getParticipant(event.getSessionId()))
.ifPresent(login -> {
messagingTemplate.convertAndSend(logoutDestination, new LogoutEvent(login.getUsername()));
participantRepository.removeParticipant(event.getSessionId());
});
}
public void setLoginDestination(String loginDestination) {
this.loginDestination = loginDestination;
}
public void setLogoutDestination(String logoutDestination) {
this.logoutDestination = logoutDestination;
}
}