All Downloads are FREE. Search and download functionalities are using the official Maven repository.

fr.hhdev.ocelot.web.TopicsMessagesBroadcaster Maven / Gradle / Ivy

The newest version!
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
package fr.hhdev.ocelot.web;

import fr.hhdev.ocelot.core.SessionManager;
import fr.hhdev.ocelot.messaging.MessageEvent;
import fr.hhdev.ocelot.messaging.MessageToClient;
import fr.hhdev.ocelot.messaging.MessageType;
import java.util.ArrayList;
import java.util.Collection;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.websocket.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Singleton that send push messages
 *
 * @author hhfrancois
 */
public class TopicsMessagesBroadcaster {

	private final static Logger logger = LoggerFactory.getLogger(TopicsMessagesBroadcaster.class);

	@Inject
	private SessionManager sessionManager;

	/**
	 * Send message to topic
	 *
	 * @param msg
	 */
	public void sendMessageToTopic(@Observes @MessageEvent MessageToClient msg) {
		msg.setType(MessageType.MESSAGE);
		logger.debug("Sending message to topic {}...", msg.toJson());
		if (sessionManager.existsSessionForTopic(msg.getId())) {
			Collection sessions = sessionManager.getSessionsForTopic(msg.getId());
			Collection closed = new ArrayList<>();
			if (!sessions.isEmpty()) {
				for (Session session : sessions) {
					if (session.isOpen()) {
						session.getAsyncRemote().sendObject(msg);
					} else {
						closed.add(session);
					}
				}
				logger.debug("Send message to '{}' topic {} client(s) : {}", new Object[]{msg.getId(), sessions.size()-closed.size(), msg.toJson()});
				logger.debug("Session closed to remove '{}'", closed.size());
				sessions.removeAll(closed);
			} else {
				logger.debug("No client for topic '{}'", msg.getId());
			}
		} else {
			logger.debug("No topic '{}'", msg.getId());
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy