aboutsummaryrefslogtreecommitdiff
path: root/juick-server-web/src/main/java/com/juick/server/component/JuickServerComponent.java
blob: 96b8c398ac23a72f706a61885507efbf0b00e6aa (plain) (blame)
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
package com.juick.server.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.PingMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.inject.Inject;
import java.io.IOException;

public class JuickServerComponent extends TextWebSocketHandler {
    private static Logger logger = LoggerFactory.getLogger(JuickServerComponent.class);
    @Inject
    private ApplicationEventPublisher applicationEventPublisher;
    @Inject
    private ObjectMapper jsonMapper;

    private WebSocketSession session;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logger.info("WebSocket connected");
        this.session = session;
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        logger.info("WebSocket disconnected with code {}: {}", status.getCode(), status.getReason());
        applicationEventPublisher.publishEvent(new DisconnectedEvent(this));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage text) throws Exception {
        com.juick.Message jmsg = jsonMapper.readValue(text.asBytes(), com.juick.Message.class);

        if (logger.isInfoEnabled()) // prevent writeValueAsString execution if logger disabled
            logger.info("got jmsg: {}", jsonMapper.writeValueAsString(jmsg));
        applicationEventPublisher.publishEvent(new MessageEvent(this, jmsg));
    }

    @Scheduled(fixedRate = 30000, initialDelay = 30000)
    public void ping() throws IOException {
        if (session != null && session.isOpen()) {
            logger.debug("Sending WebSocket ping");
            session.sendMessage(new PingMessage());
        } else {
            applicationEventPublisher.publishEvent(new DisconnectedEvent(this));
        }
    }
}