|
| 1 | +/* |
| 2 | + * Copyright 2002-2013 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.messaging.handler.websocket; |
| 18 | + |
| 19 | +import java.util.Arrays; |
| 20 | +import java.util.List; |
| 21 | +import java.util.Map; |
| 22 | +import java.util.TreeMap; |
| 23 | +import java.util.concurrent.ConcurrentHashMap; |
| 24 | + |
| 25 | +import org.apache.commons.logging.Log; |
| 26 | +import org.apache.commons.logging.LogFactory; |
| 27 | +import org.springframework.messaging.Message; |
| 28 | +import org.springframework.messaging.MessageChannel; |
| 29 | +import org.springframework.messaging.MessageHandler; |
| 30 | +import org.springframework.messaging.MessagingException; |
| 31 | +import org.springframework.util.Assert; |
| 32 | +import org.springframework.util.CollectionUtils; |
| 33 | +import org.springframework.web.socket.CloseStatus; |
| 34 | +import org.springframework.web.socket.WebSocketHandler; |
| 35 | +import org.springframework.web.socket.WebSocketMessage; |
| 36 | +import org.springframework.web.socket.WebSocketSession; |
| 37 | + |
| 38 | + |
| 39 | +/** |
| 40 | + * A {@link WebSocketHandler} that delegates messages to a {@link SubProtocolHandler} |
| 41 | + * based on the sub-protocol value requested by the client through the |
| 42 | + * {@code Sec-WebSocket-Protocol} request header A default handler can also be configured |
| 43 | + * to use if the client does not request a specific sub-protocol. |
| 44 | + * |
| 45 | + * @author Rossen Stoyanchev |
| 46 | + * @author Andy Wilkinson |
| 47 | + * |
| 48 | + * @since 4.0 |
| 49 | + */ |
| 50 | +public class SubProtocolWebSocketHandler implements WebSocketHandler, MessageHandler { |
| 51 | + |
| 52 | + private final Log logger = LogFactory.getLog(SubProtocolWebSocketHandler.class); |
| 53 | + |
| 54 | + private final MessageChannel outputChannel; |
| 55 | + |
| 56 | + private final Map<String, SubProtocolHandler> protocolHandlers = |
| 57 | + new TreeMap<String, SubProtocolHandler>(String.CASE_INSENSITIVE_ORDER); |
| 58 | + |
| 59 | + private SubProtocolHandler defaultProtocolHandler; |
| 60 | + |
| 61 | + private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<String, WebSocketSession>(); |
| 62 | + |
| 63 | + |
| 64 | + /** |
| 65 | + * @param outputChannel |
| 66 | + */ |
| 67 | + public SubProtocolWebSocketHandler(MessageChannel outputChannel) { |
| 68 | + Assert.notNull(outputChannel, "outputChannel is required"); |
| 69 | + this.outputChannel = outputChannel; |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * Configure one or more handlers to use depending on the sub-protocol requested by |
| 74 | + * the client in the WebSocket handshake request. |
| 75 | + * |
| 76 | + * @param protocolHandlers the sub-protocol handlers to use |
| 77 | + */ |
| 78 | + public void setProtocolHandlers(List<SubProtocolHandler> protocolHandlers) { |
| 79 | + this.protocolHandlers.clear(); |
| 80 | + for (SubProtocolHandler handler: protocolHandlers) { |
| 81 | + List<String> protocols = handler.getSupportedProtocols(); |
| 82 | + if (CollectionUtils.isEmpty(protocols)) { |
| 83 | + logger.warn("No sub-protocols, ignoring handler " + handler); |
| 84 | + continue; |
| 85 | + } |
| 86 | + for (String protocol: protocols) { |
| 87 | + SubProtocolHandler replaced = this.protocolHandlers.put(protocol, handler); |
| 88 | + if (replaced != null) { |
| 89 | + throw new IllegalStateException("Failed to map handler " + handler |
| 90 | + + " to protocol '" + protocol + "', it is already mapped to handler " + replaced); |
| 91 | + } |
| 92 | + } |
| 93 | + } |
| 94 | + if ((this.protocolHandlers.size() == 1) &&(this.defaultProtocolHandler == null)) { |
| 95 | + this.defaultProtocolHandler = this.protocolHandlers.values().iterator().next(); |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + /** |
| 100 | + * @return the configured sub-protocol handlers |
| 101 | + */ |
| 102 | + public Map<String, SubProtocolHandler> getProtocolHandlers() { |
| 103 | + return this.protocolHandlers; |
| 104 | + } |
| 105 | + |
| 106 | + /** |
| 107 | + * Set the {@link SubProtocolHandler} to use when the client did not request a |
| 108 | + * sub-protocol. |
| 109 | + * |
| 110 | + * @param defaultProtocolHandler the default handler |
| 111 | + */ |
| 112 | + public void setDefaultProtocolHandler(SubProtocolHandler defaultProtocolHandler) { |
| 113 | + this.defaultProtocolHandler = defaultProtocolHandler; |
| 114 | + if (this.protocolHandlers.isEmpty()) { |
| 115 | + setProtocolHandlers(Arrays.asList(defaultProtocolHandler)); |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + /** |
| 120 | + * @return the default sub-protocol handler to use |
| 121 | + */ |
| 122 | + public SubProtocolHandler getDefaultProtocolHandler() { |
| 123 | + return this.defaultProtocolHandler; |
| 124 | + } |
| 125 | + |
| 126 | + |
| 127 | + @Override |
| 128 | + public void afterConnectionEstablished(WebSocketSession session) throws Exception { |
| 129 | + this.sessions.put(session.getId(), session); |
| 130 | + getProtocolHandler(session).afterSessionStarted(session, this.outputChannel); |
| 131 | + } |
| 132 | + |
| 133 | + protected final SubProtocolHandler getProtocolHandler(WebSocketSession session) { |
| 134 | + SubProtocolHandler handler; |
| 135 | + String protocol = session.getAcceptedProtocol(); |
| 136 | + if (protocol != null) { |
| 137 | + handler = this.protocolHandlers.get(protocol); |
| 138 | + Assert.state(handler != null, |
| 139 | + "No handler for sub-protocol '" + protocol + "', handlers=" + this.protocolHandlers); |
| 140 | + } |
| 141 | + else { |
| 142 | + handler = this.defaultProtocolHandler; |
| 143 | + Assert.state(handler != null, |
| 144 | + "No sub-protocol was requested and a default sub-protocol handler was not configured"); |
| 145 | + } |
| 146 | + return handler; |
| 147 | + } |
| 148 | + |
| 149 | + @Override |
| 150 | + public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { |
| 151 | + getProtocolHandler(session).handleMessageFromClient(session, message, this.outputChannel); |
| 152 | + } |
| 153 | + |
| 154 | + @Override |
| 155 | + public void handleMessage(Message<?> message) throws MessagingException { |
| 156 | + |
| 157 | + String sessionId = resolveSessionId(message); |
| 158 | + if (sessionId == null) { |
| 159 | + logger.error("sessionId not found in message " + message); |
| 160 | + return; |
| 161 | + } |
| 162 | + |
| 163 | + WebSocketSession session = this.sessions.get(sessionId); |
| 164 | + if (session == null) { |
| 165 | + logger.error("Session not found for session with id " + sessionId); |
| 166 | + return; |
| 167 | + } |
| 168 | + |
| 169 | + try { |
| 170 | + getProtocolHandler(session).handleMessageToClient(session, message); |
| 171 | + } |
| 172 | + catch (Exception e) { |
| 173 | + logger.error("Failed to send message to client " + message, e); |
| 174 | + } |
| 175 | + } |
| 176 | + |
| 177 | + private String resolveSessionId(Message<?> message) { |
| 178 | + for (SubProtocolHandler handler : this.protocolHandlers.values()) { |
| 179 | + String sessionId = handler.resolveSessionId(message); |
| 180 | + if (sessionId != null) { |
| 181 | + return sessionId; |
| 182 | + } |
| 183 | + } |
| 184 | + if (this.defaultProtocolHandler != null) { |
| 185 | + String sessionId = this.defaultProtocolHandler.resolveSessionId(message); |
| 186 | + if (sessionId != null) { |
| 187 | + return sessionId; |
| 188 | + } |
| 189 | + } |
| 190 | + return null; |
| 191 | + } |
| 192 | + |
| 193 | + @Override |
| 194 | + public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { |
| 195 | + } |
| 196 | + |
| 197 | + @Override |
| 198 | + public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { |
| 199 | + this.sessions.remove(session.getId()); |
| 200 | + getProtocolHandler(session).afterSessionEnded(session, closeStatus, this.outputChannel); |
| 201 | + } |
| 202 | + |
| 203 | + @Override |
| 204 | + public boolean supportsPartialMessages() { |
| 205 | + return false; |
| 206 | + } |
| 207 | + |
| 208 | +} |
0 commit comments