From ac12981e84bd691e4a5f689d239cf4b935e0f643 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Tue, 17 Jan 2017 16:51:07 +0300 Subject: juick-ws: add protocol listener --- .../main/java/com/juick/ws/WebsocketComponent.java | 29 +++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) (limited to 'juick-ws/src/main/java/com/juick/ws') diff --git a/juick-ws/src/main/java/com/juick/ws/WebsocketComponent.java b/juick-ws/src/main/java/com/juick/ws/WebsocketComponent.java index 2f998298..909933e4 100644 --- a/juick-ws/src/main/java/com/juick/ws/WebsocketComponent.java +++ b/juick-ws/src/main/java/com/juick/ws/WebsocketComponent.java @@ -2,6 +2,7 @@ package com.juick.ws; import com.juick.User; import com.juick.server.protocol.JuickProtocol; +import com.juick.server.protocol.ProtocolListener; import com.juick.service.MessagesService; import com.juick.service.UserService; import org.apache.commons.lang3.CharEncoding; @@ -19,6 +20,7 @@ import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; +import javax.annotation.PostConstruct; import javax.inject.Inject; import java.io.IOException; import java.lang.reflect.InvocationTargetException; @@ -30,7 +32,7 @@ import java.util.List; /** * Created by vitalyster on 28.06.2016. */ -public class WebsocketComponent extends TextWebSocketHandler { +public class WebsocketComponent extends TextWebSocketHandler implements ProtocolListener { private static final Logger logger = LoggerFactory.getLogger(WebsocketComponent.class); private final List clients = Collections.synchronizedList(new ArrayList()); @@ -42,6 +44,11 @@ public class WebsocketComponent extends TextWebSocketHandler { @Inject JuickProtocol protocol; + @PostConstruct + public void init() { + protocol.setListener(this); + } + @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { URI hLocation; @@ -155,6 +162,26 @@ public class WebsocketComponent extends TextWebSocketHandler { return clients; } + @Override + public void privateMessage(User from, User to, String body) { + notifyUser(from, to, "Private message from @" + from.getName() + ":\n" + body); + } + + @Override + public void userSubscribed(User from, User to) { + notifyUser(from, to, String.format("@%s subscribed to your blog", from.getName())); + } + + private void notifyUser(User from, User to, String body) { + getClients().stream().filter(s -> !s.legacy && s.visitor.equals(to)).forEach(s -> { + try { + s.session.sendMessage(new TextMessage(body)); + } catch (IOException e) { + logger.error("protocol exception", e); + } + }); + } + class SocketSubscribed { WebSocketSession session; String clientName; -- cgit v1.2.3