001package systems.dmx.core.impl; 002 003import java.util.Collection; 004import java.util.Map; 005import java.util.concurrent.ConcurrentHashMap; 006 007 008 009class WebSocketConnectionPool { 010 011 // ---------------------------------------------------------------------------------------------- Instance Variables 012 013 /** 014 * 1st hash: plugin URI 015 * 2nd hash: session ID 016 */ 017 private Map<String, Map<String, WebSocketConnection>> pool = new ConcurrentHashMap(); 018 019 // ----------------------------------------------------------------------------------------------------- Constructor 020 021 WebSocketConnectionPool() { 022 } 023 024 // ----------------------------------------------------------------------------------------- Package Private Methods 025 026 /** 027 * Returns the open WebSocket connections associated to the given plugin, or <code>null</code> if there are none. 028 */ 029 Collection<WebSocketConnection> getConnections(String pluginUri) { 030 Map connections = pool.get(pluginUri); 031 return connections != null ? connections.values() : null; 032 } 033 034 WebSocketConnection getConnection(String pluginUri, String sessionId) { 035 Map<String, WebSocketConnection> connections = pool.get(pluginUri); 036 if (connections == null) { 037 throw new RuntimeException("No WebSocket connection open for plugin \"" + pluginUri + "\""); 038 } 039 WebSocketConnection connection = connections.get(sessionId); 040 if (connection == null) { 041 throw new RuntimeException("No WebSocket connection open for session \"" + sessionId + "\" (plugin \"" + 042 pluginUri + "\")"); 043 } 044 return connection; 045 } 046 047 void add(WebSocketConnection connection) { 048 String pluginUri = connection.pluginUri; 049 Map connections = pool.get(pluginUri); 050 if (connections == null) { 051 connections = new ConcurrentHashMap(); 052 pool.put(pluginUri, connections); 053 } 054 connections.put(connection.sessionId, connection); 055 } 056 057 void remove(WebSocketConnection connection) { 058 String pluginUri = connection.pluginUri; 059 boolean removed = getConnections(pluginUri).remove(connection); 060 if (!removed) { 061 throw new RuntimeException("Removing a connection of plugin \"" + pluginUri + "\" failed"); 062 } 063 } 064}