language
stringclasses
1 value
owner
stringlengths
2
15
repo
stringlengths
2
21
sha
stringlengths
45
45
message
stringlengths
7
36.3k
path
stringlengths
1
199
patch
stringlengths
15
102k
is_multipart
bool
2 classes
Other
spring-projects
spring-framework
34c95034d8437249b573912aaf275c0a734b15a7.json
Fix minor issue and polish
spring-websocket/src/main/java/org/springframework/websocket/server/support/WebSocketHttpRequestHandler.java
@@ -44,25 +44,26 @@ */ public class WebSocketHttpRequestHandler implements HttpRequestHandler { - private HandshakeHandler handshakeHandler; + private final HandshakeHandler handshakeHandler; private final HandlerProvider<WebSocketHandler> handlerProvider; public WebSocketHttpRequestHandler(WebSocketHandler webSocketHandler) { - Assert.notNull(webSocketHandler, "webSocketHandler is required"); - this.handlerProvider = new SimpleHandlerProvider<WebSocketHandler>(webSocketHandler); - this.handshakeHandler = new DefaultHandshakeHandler(); + this(new SimpleHandlerProvider<WebSocketHandler>(webSocketHandler)); } public WebSocketHttpRequestHandler( HandlerProvider<WebSocketHandler> handlerProvider) { - Assert.notNull(handlerProvider, "handlerProvider is required"); - this.handlerProvider = handlerProvider; + this(handlerProvider, new DefaultHandshakeHandler()); } - public void setHandshakeHandler(HandshakeHandler handshakeHandler) { + public WebSocketHttpRequestHandler( HandlerProvider<WebSocketHandler> handlerProvider, + HandshakeHandler handshakeHandler) { + + Assert.notNull(handlerProvider, "handlerProvider is required"); Assert.notNull(handshakeHandler, "handshakeHandler is required"); - this.handshakeHandler = handshakeHandler; + this.handlerProvider = handlerProvider; + this.handshakeHandler = new DefaultHandshakeHandler(); } @Override
true
Other
spring-projects
spring-framework
36148b7cb1066b77b7849f9852d36d0fcf0f5db0.json
Switch DefaultSockJsService to constructor DI DefaultSockJsService now relies on constructors and requires a TaskScheduler at a minimum. It no longer needs lifecycle methods.
spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractServerSockJsSession.java
@@ -129,13 +129,13 @@ public synchronized void sendHeartbeat() throws Exception { } protected void scheduleHeartbeat() { - Assert.notNull(getSockJsConfig().getHeartbeatScheduler(), "heartbeatScheduler not configured"); + Assert.notNull(getSockJsConfig().getTaskScheduler(), "heartbeatScheduler not configured"); cancelHeartbeat(); if (!isActive()) { return; } Date time = new Date(System.currentTimeMillis() + getSockJsConfig().getHeartbeatTime()); - this.heartbeatTask = getSockJsConfig().getHeartbeatScheduler().schedule(new Runnable() { + this.heartbeatTask = getSockJsConfig().getTaskScheduler().schedule(new Runnable() { public void run() { try { sendHeartbeat();
true
Other
spring-projects
spring-framework
36148b7cb1066b77b7849f9852d36d0fcf0f5db0.json
Switch DefaultSockJsService to constructor DI DefaultSockJsService now relies on constructors and requires a TaskScheduler at a minimum. It no longer needs lifecycle methods.
spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractSockJsService.java
@@ -25,15 +25,12 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.DisposableBean; -import org.springframework.beans.factory.InitializingBean; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.scheduling.TaskScheduler; -import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.DigestUtils; @@ -49,8 +46,7 @@ * @author Rossen Stoyanchev * @since 4.0 */ -public abstract class AbstractSockJsService - implements SockJsService, SockJsConfiguration, InitializingBean, DisposableBean { +public abstract class AbstractSockJsService implements SockJsService, SockJsConfiguration { protected final Log logger = LogFactory.getLog(getClass()); @@ -71,17 +67,13 @@ private boolean webSocketsEnabled = true; - private final TaskSchedulerHolder heartbeatSchedulerHolder; + private final TaskScheduler taskScheduler; - public AbstractSockJsService() { - this.heartbeatSchedulerHolder = new TaskSchedulerHolder("SockJs-heartbeat-"); - } - - public AbstractSockJsService(TaskScheduler heartbeatScheduler) { - Assert.notNull(heartbeatScheduler, "heartbeatScheduler is required"); - this.heartbeatSchedulerHolder = new TaskSchedulerHolder(heartbeatScheduler); + public AbstractSockJsService(TaskScheduler scheduler) { + Assert.notNull(scheduler, "scheduler is required"); + this.taskScheduler = scheduler; } /** @@ -159,8 +151,8 @@ public long getHeartbeatTime() { return this.heartbeatTime; } - public TaskScheduler getHeartbeatScheduler() { - return this.heartbeatSchedulerHolder.getScheduler(); + public TaskScheduler getTaskScheduler() { + return this.taskScheduler; } /** @@ -199,16 +191,6 @@ public boolean isWebSocketEnabled() { return this.webSocketsEnabled; } - @Override - public void afterPropertiesSet() throws Exception { - this.heartbeatSchedulerHolder.initialize(); - } - - @Override - public void destroy() throws Exception { - this.heartbeatSchedulerHolder.destroy(); - } - /** * TODO * @@ -423,46 +405,4 @@ public void handle(ServerHttpRequest request, ServerHttpResponse response) throw } }; - - /** - * Holds an externally provided or an internally managed TaskScheduler. Provides - * initialize and destroy methods have no effect if the scheduler is externally - * managed. - */ - protected static class TaskSchedulerHolder { - - private final TaskScheduler taskScheduler; - - private final boolean isDefaultTaskScheduler; - - public TaskSchedulerHolder(TaskScheduler taskScheduler) { - Assert.notNull(taskScheduler, "taskScheduler is required"); - this.taskScheduler = taskScheduler; - this.isDefaultTaskScheduler = false; - } - - public TaskSchedulerHolder(String threadNamePrefix) { - ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); - scheduler.setThreadNamePrefix(threadNamePrefix); - this.taskScheduler = scheduler; - this.isDefaultTaskScheduler = true; - } - - public TaskScheduler getScheduler() { - return this.taskScheduler; - } - - public void initialize() { - if (this.isDefaultTaskScheduler) { - ((ThreadPoolTaskScheduler) this.taskScheduler).afterPropertiesSet(); - } - } - - public void destroy() { - if (this.isDefaultTaskScheduler) { - ((ThreadPoolTaskScheduler) this.taskScheduler).shutdown(); - } - } - } - }
true
Other
spring-projects
spring-framework
36148b7cb1066b77b7849f9852d36d0fcf0f5db0.json
Switch DefaultSockJsService to constructor DI DefaultSockJsService now relies on constructors and requires a TaskScheduler at a minimum. It no longer needs lifecycle methods.
spring-websocket/src/main/java/org/springframework/sockjs/server/SockJsConfiguration.java
@@ -48,10 +48,8 @@ public interface SockJsConfiguration { public long getHeartbeatTime(); /** - * A scheduler instance to use for scheduling heartbeat frames. - * <p> - * By default a {@link ThreadPoolTaskScheduler} with default settings is used. + * A scheduler instance to use for scheduling heart-beat messages. */ - public TaskScheduler getHeartbeatScheduler(); + public TaskScheduler getTaskScheduler(); }
true
Other
spring-projects
spring-framework
36148b7cb1066b77b7849f9852d36d0fcf0f5db0.json
Switch DefaultSockJsService to constructor DI DefaultSockJsService now relies on constructors and requires a TaskScheduler at a minimum. It no longer needs lifecycle methods.
spring-websocket/src/main/java/org/springframework/sockjs/server/support/DefaultSockJsService.java
@@ -16,10 +16,15 @@ package org.springframework.sockjs.server.support; import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledFuture; import org.springframework.http.Cookie; import org.springframework.http.HttpMethod; @@ -41,7 +46,7 @@ import org.springframework.sockjs.server.transport.XhrPollingTransportHandler; import org.springframework.sockjs.server.transport.XhrStreamingTransportHandler; import org.springframework.sockjs.server.transport.XhrTransportHandler; -import org.springframework.util.Assert; +import org.springframework.util.CollectionUtils; import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; import org.springframework.websocket.server.DefaultHandshakeHandler; @@ -58,101 +63,58 @@ public class DefaultSockJsService extends AbstractSockJsService { private final Map<TransportType, TransportHandler> transportHandlers = new HashMap<TransportType, TransportHandler>(); - private final Map<TransportType, TransportHandler> transportHandlerOverrides = new HashMap<TransportType, TransportHandler>(); - - private TaskSchedulerHolder sessionTimeoutSchedulerHolder; - private final Map<String, AbstractSockJsSession> sessions = new ConcurrentHashMap<String, AbstractSockJsSession>(); + private ScheduledFuture sessionCleanupTask; - public DefaultSockJsService() { - this.sessionTimeoutSchedulerHolder = new TaskSchedulerHolder("SockJs-sessionTimeout-"); - } - public DefaultSockJsService(TaskScheduler heartbeatScheduler, TaskScheduler sessionTimeoutScheduler) { - Assert.notNull(sessionTimeoutScheduler, "sessionTimeoutScheduler is required"); - this.sessionTimeoutSchedulerHolder = new TaskSchedulerHolder(sessionTimeoutScheduler); + public DefaultSockJsService(TaskScheduler taskScheduler) { + this(taskScheduler, null); } - public void setTransportHandlers(TransportHandler... handlers) { - this.transportHandlers.clear(); - for (TransportHandler handler : handlers) { - this.transportHandlers.put(handler.getTransportType(), handler); - } - } + public DefaultSockJsService(TaskScheduler taskScheduler, Set<TransportHandler> transportHandlers, + TransportHandler... transportHandlerOverrides) { - public void setTransportHandlerOverrides(TransportHandler... handlers) { - this.transportHandlerOverrides.clear(); - for (TransportHandler handler : handlers) { - this.transportHandlerOverrides.put(handler.getTransportType(), handler); - } - } + super(taskScheduler); + transportHandlers = CollectionUtils.isEmpty(transportHandlers) ? getDefaultTransportHandlers() : transportHandlers; + addTransportHandlers(transportHandlers); + addTransportHandlers(Arrays.asList(transportHandlerOverrides)); + } - @Override - public void afterPropertiesSet() throws Exception { - - super.afterPropertiesSet(); - - if (this.transportHandlers.isEmpty()) { - if (isWebSocketEnabled() && (this.transportHandlerOverrides.get(TransportType.WEBSOCKET) == null)) { - this.transportHandlers.put(TransportType.WEBSOCKET, - new WebSocketTransportHandler(new DefaultHandshakeHandler())); + protected Set<TransportHandler> getDefaultTransportHandlers() { + Set<TransportHandler> result = new HashSet<TransportHandler>(); + result.add(new XhrPollingTransportHandler()); + result.add(new XhrTransportHandler()); + result.add(new JsonpPollingTransportHandler()); + result.add(new JsonpTransportHandler()); + result.add(new XhrStreamingTransportHandler()); + result.add(new EventSourceTransportHandler()); + result.add(new HtmlFileTransportHandler()); + if (isWebSocketEnabled()) { + try { + result.add(new WebSocketTransportHandler(new DefaultHandshakeHandler())); } - this.transportHandlers.put(TransportType.XHR, new XhrPollingTransportHandler()); - this.transportHandlers.put(TransportType.XHR_SEND, new XhrTransportHandler()); - this.transportHandlers.put(TransportType.JSONP, new JsonpPollingTransportHandler()); - this.transportHandlers.put(TransportType.JSONP_SEND, new JsonpTransportHandler()); - this.transportHandlers.put(TransportType.XHR_STREAMING, new XhrStreamingTransportHandler()); - this.transportHandlers.put(TransportType.EVENT_SOURCE, new EventSourceTransportHandler()); - this.transportHandlers.put(TransportType.HTML_FILE, new HtmlFileTransportHandler()); - } - - if (!this.transportHandlerOverrides.isEmpty()) { - for (TransportHandler transportHandler : this.transportHandlerOverrides.values()) { - this.transportHandlers.put(transportHandler.getTransportType(), transportHandler); + catch (Exception ex) { + if (logger.isWarnEnabled()) { + logger.warn("Failed to add default WebSocketTransportHandler: " + ex.getMessage()); + } } } + return result; + } - for (TransportHandler h : this.transportHandlers.values()) { - if (h instanceof ConfigurableTransportHandler) { - ((ConfigurableTransportHandler) h).setSockJsConfiguration(this); + protected void addTransportHandlers(Collection<TransportHandler> handlers) { + for (TransportHandler handler : handlers) { + if (handler instanceof ConfigurableTransportHandler) { + ((ConfigurableTransportHandler) handler).setSockJsConfiguration(this); } + this.transportHandlers.put(handler.getTransportType(), handler); } - - this.sessionTimeoutSchedulerHolder.initialize(); - - this.sessionTimeoutSchedulerHolder.getScheduler().scheduleAtFixedRate(new Runnable() { - public void run() { - try { - int count = sessions.size(); - if (logger.isTraceEnabled() && (count != 0)) { - logger.trace("Checking " + count + " session(s) for timeouts [" + getName() + "]"); - } - for (AbstractSockJsSession session : sessions.values()) { - if (session.getTimeSinceLastActive() > getDisconnectDelay()) { - if (logger.isTraceEnabled()) { - logger.trace("Removing " + session + " for [" + getName() + "]"); - } - session.close(); - sessions.remove(session.getId()); - } - } - if (logger.isTraceEnabled() && (count != 0)) { - logger.trace(sessions.size() + " remaining session(s) [" + getName() + "]"); - } - } - catch (Throwable t) { - logger.error("Failed to complete session timeout checks for [" + getName() + "]", t); - } - } - }, getDisconnectDelay()); } - @Override - public void destroy() throws Exception { - super.destroy(); - this.sessionTimeoutSchedulerHolder.destroy(); + public Map<TransportType, TransportHandler> getTransportHandlers() { + return Collections.unmodifiableMap(this.transportHandlers); } @Override @@ -239,6 +201,9 @@ public AbstractSockJsSession getSockJsSession(String sessionId, HandlerProvider< if (session != null) { return session; } + if (this.sessionCleanupTask == null) { + scheduleSessionTask(); + } logger.debug("Creating new session with session id \"" + sessionId + "\""); session = (AbstractSockJsSession) sessionFactory.createSession(sessionId, handler); this.sessions.put(sessionId, session); @@ -249,4 +214,32 @@ public AbstractSockJsSession getSockJsSession(String sessionId, HandlerProvider< return null; } + private void scheduleSessionTask() { + this.sessionCleanupTask = getTaskScheduler().scheduleAtFixedRate(new Runnable() { + public void run() { + try { + int count = sessions.size(); + if (logger.isTraceEnabled() && (count != 0)) { + logger.trace("Checking " + count + " session(s) for timeouts [" + getName() + "]"); + } + for (AbstractSockJsSession session : sessions.values()) { + if (session.getTimeSinceLastActive() > getDisconnectDelay()) { + if (logger.isTraceEnabled()) { + logger.trace("Removing " + session + " for [" + getName() + "]"); + } + session.close(); + sessions.remove(session.getId()); + } + } + if (logger.isTraceEnabled() && (count != 0)) { + logger.trace(sessions.size() + " remaining session(s) [" + getName() + "]"); + } + } + catch (Throwable t) { + logger.error("Failed to complete session timeout checks for [" + getName() + "]", t); + } + } + }, getDisconnectDelay()); + } + }
true
Other
spring-projects
spring-framework
36148b7cb1066b77b7849f9852d36d0fcf0f5db0.json
Switch DefaultSockJsService to constructor DI DefaultSockJsService now relies on constructors and requires a TaskScheduler at a minimum. It no longer needs lifecycle methods.
spring-websocket/src/main/java/org/springframework/websocket/client/WebSocketConnectionManager.java
@@ -15,9 +15,11 @@ */ package org.springframework.websocket.client; +import java.util.ArrayList; import java.util.List; import org.springframework.http.HttpHeaders; +import org.springframework.util.CollectionUtils; import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; import org.springframework.websocket.WebSocketSession; @@ -37,7 +39,7 @@ public class WebSocketConnectionManager extends AbstractWebSocketConnectionManag private WebSocketSession webSocketSession; - private List<String> subProtocols; + private final List<String> subProtocols = new ArrayList<String>(); public WebSocketConnectionManager(WebSocketClient webSocketClient, @@ -57,7 +59,10 @@ public WebSocketConnectionManager(WebSocketClient webSocketClient, } public void setSubProtocols(List<String> subProtocols) { - this.subProtocols = subProtocols; + this.subProtocols.clear(); + if (!CollectionUtils.isEmpty(subProtocols)) { + this.subProtocols.addAll(subProtocols); + } } public List<String> getSubProtocols() {
true
Other
spring-projects
spring-framework
36148b7cb1066b77b7849f9852d36d0fcf0f5db0.json
Switch DefaultSockJsService to constructor DI DefaultSockJsService now relies on constructors and requires a TaskScheduler at a minimum. It no longer needs lifecycle methods.
spring-websocket/src/test/java/org/springframework/sockjs/server/support/DefaultSockJsServiceTests.java
@@ -0,0 +1,55 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.sockjs.server.support; + +import java.util.Map; + +import org.junit.Test; +import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; +import org.springframework.sockjs.server.TransportHandler; +import org.springframework.sockjs.server.TransportType; + +import static org.junit.Assert.*; + + +/** + * Test fixture for {@link DefaultSockJsService}. + * + * @author Rossen Stoyanchev + */ +public class DefaultSockJsServiceTests { + + + @Test + public void testDefaultTransportHandlers() { + + DefaultSockJsService sockJsService = new DefaultSockJsService(new ThreadPoolTaskScheduler()); + Map<TransportType, TransportHandler> handlers = sockJsService.getTransportHandlers(); + + assertEquals(8, handlers.size()); + assertNotNull(handlers.get(TransportType.WEBSOCKET)); + assertNotNull(handlers.get(TransportType.XHR)); + assertNotNull(handlers.get(TransportType.XHR_SEND)); + assertNotNull(handlers.get(TransportType.XHR_STREAMING)); + assertNotNull(handlers.get(TransportType.JSONP)); + assertNotNull(handlers.get(TransportType.JSONP_SEND)); + assertNotNull(handlers.get(TransportType.HTML_FILE)); + assertNotNull(handlers.get(TransportType.EVENT_SOURCE)); + } + + +}
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/AbstractSockJsSession.java
@@ -22,6 +22,7 @@ import org.apache.commons.logging.LogFactory; import org.springframework.util.Assert; import org.springframework.websocket.CloseStatus; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.TextMessage; import org.springframework.websocket.TextMessageHandler; import org.springframework.websocket.WebSocketHandler; @@ -40,6 +41,8 @@ public abstract class AbstractSockJsSession implements WebSocketSession { private final String sessionId; + private final HandlerProvider<WebSocketHandler> handlerProvider; + private final TextMessageHandler handler; private State state = State.NEW; @@ -52,14 +55,17 @@ public abstract class AbstractSockJsSession implements WebSocketSession { /** * * @param sessionId - * @param handler the recipient of SockJS messages + * @param handlerProvider the recipient of SockJS messages */ - public AbstractSockJsSession(String sessionId, WebSocketHandler webSocketHandler) { + public AbstractSockJsSession(String sessionId, HandlerProvider<WebSocketHandler> handlerProvider) { Assert.notNull(sessionId, "sessionId is required"); - Assert.notNull(webSocketHandler, "webSocketHandler is required"); - Assert.isInstanceOf(TextMessageHandler.class, webSocketHandler, "Expected a TextMessageHandler"); + Assert.notNull(handlerProvider, "handlerProvider is required"); this.sessionId = sessionId; + + WebSocketHandler webSocketHandler = handlerProvider.getHandler(); + Assert.isInstanceOf(TextMessageHandler.class, webSocketHandler, "Expected a TextMessageHandler"); this.handler = (TextMessageHandler) webSocketHandler; + this.handlerProvider = handlerProvider; } public String getId() { @@ -180,7 +186,12 @@ public final void close(CloseStatus status) throws Exception { } finally { this.state = State.CLOSED; - this.handler.afterConnectionClosed(status, this); + try { + this.handler.afterConnectionClosed(status, this); + } + finally { + this.handlerProvider.destroy(this.handler); + } } } }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/SockJsSessionFactory.java
@@ -16,6 +16,7 @@ package org.springframework.sockjs; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; import org.springframework.websocket.WebSocketSession; @@ -28,6 +29,6 @@ */ public interface SockJsSessionFactory<S extends WebSocketSession>{ - S createSession(String sessionId, WebSocketHandler webSocketHandler); + S createSession(String sessionId, HandlerProvider<WebSocketHandler> handler); }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractServerSockJsSession.java
@@ -25,6 +25,7 @@ import org.springframework.sockjs.AbstractSockJsSession; import org.springframework.util.Assert; import org.springframework.websocket.CloseStatus; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.TextMessage; import org.springframework.websocket.WebSocketHandler; import org.springframework.websocket.WebSocketMessage; @@ -45,9 +46,9 @@ public abstract class AbstractServerSockJsSession extends AbstractSockJsSession public AbstractServerSockJsSession(String sessionId, SockJsConfiguration config, - WebSocketHandler webSocketHandler) { + HandlerProvider<WebSocketHandler> handler) { - super(sessionId, webSocketHandler); + super(sessionId, handler); this.sockJsConfig = config; }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractSockJsService.java
@@ -39,6 +39,7 @@ import org.springframework.util.DigestUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; @@ -218,7 +219,7 @@ public void destroy() throws Exception { * @throws Exception */ public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response, - String sockJsPath, WebSocketHandler webSocketHandler) throws Exception { + String sockJsPath, HandlerProvider<WebSocketHandler> handler) throws Exception { logger.debug(request.getMethod() + " [" + sockJsPath + "]"); @@ -244,7 +245,7 @@ else if (sockJsPath.matches("/iframe[0-9-.a-z_]*.html")) { return; } else if (sockJsPath.equals("/websocket")) { - handleRawWebSocketRequest(request, response, webSocketHandler); + handleRawWebSocketRequest(request, response, handler); return; } @@ -264,18 +265,18 @@ else if (sockJsPath.equals("/websocket")) { return; } - handleTransportRequest(request, response, sessionId, TransportType.fromValue(transport), webSocketHandler); + handleTransportRequest(request, response, sessionId, TransportType.fromValue(transport), handler); } finally { response.flush(); } } protected abstract void handleRawWebSocketRequest(ServerHttpRequest request, ServerHttpResponse response, - WebSocketHandler webSocketHandler) throws Exception; + HandlerProvider<WebSocketHandler> handler) throws Exception; protected abstract void handleTransportRequest(ServerHttpRequest request, ServerHttpResponse response, - String sessionId, TransportType transportType, WebSocketHandler webSocketHandler) throws Exception; + String sessionId, TransportType transportType, HandlerProvider<WebSocketHandler> handler) throws Exception; protected boolean validateRequest(String serverId, String sessionId, String transport) {
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/server/SockJsService.java
@@ -18,6 +18,7 @@ import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; @@ -30,6 +31,6 @@ public interface SockJsService { void handleRequest(ServerHttpRequest request, ServerHttpResponse response, String sockJsPath, - WebSocketHandler webSocketHandler) throws Exception; + HandlerProvider<WebSocketHandler> handler) throws Exception; }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/server/TransportHandler.java
@@ -18,6 +18,7 @@ import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.sockjs.AbstractSockJsSession; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; @@ -31,6 +32,6 @@ public interface TransportHandler { TransportType getTransportType(); void handleRequest(ServerHttpRequest request, ServerHttpResponse response, - WebSocketHandler webSocketHandler, AbstractSockJsSession session) throws Exception; + HandlerProvider<WebSocketHandler> handler, AbstractSockJsSession session) throws Exception; }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/server/support/DefaultSockJsService.java
@@ -21,7 +21,6 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import org.springframework.beans.factory.InitializingBean; import org.springframework.http.Cookie; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; @@ -43,6 +42,7 @@ import org.springframework.sockjs.server.transport.XhrStreamingTransportHandler; import org.springframework.sockjs.server.transport.XhrTransportHandler; import org.springframework.util.Assert; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; import org.springframework.websocket.server.DefaultHandshakeHandler; import org.springframework.websocket.server.HandshakeHandler; @@ -54,7 +54,7 @@ * @author Rossen Stoyanchev * @since 4.0 */ -public class DefaultSockJsService extends AbstractSockJsService implements InitializingBean { +public class DefaultSockJsService extends AbstractSockJsService { private final Map<TransportType, TransportHandler> transportHandlers = new HashMap<TransportType, TransportHandler>(); @@ -157,13 +157,13 @@ public void destroy() throws Exception { @Override protected void handleRawWebSocketRequest(ServerHttpRequest request, ServerHttpResponse response, - WebSocketHandler webSocketHandler) throws Exception { + HandlerProvider<WebSocketHandler> handler) throws Exception { if (isWebSocketEnabled()) { TransportHandler transportHandler = this.transportHandlers.get(TransportType.WEBSOCKET); if (transportHandler != null) { if (transportHandler instanceof HandshakeHandler) { - ((HandshakeHandler) transportHandler).doHandshake(request, response, webSocketHandler); + ((HandshakeHandler) transportHandler).doHandshake(request, response, handler); return; } } @@ -174,7 +174,7 @@ protected void handleRawWebSocketRequest(ServerHttpRequest request, ServerHttpRe @Override protected void handleTransportRequest(ServerHttpRequest request, ServerHttpResponse response, - String sessionId, TransportType transportType, WebSocketHandler webSocketHandler) throws Exception { + String sessionId, TransportType transportType, HandlerProvider<WebSocketHandler> handler) throws Exception { TransportHandler transportHandler = this.transportHandlers.get(transportType); @@ -201,7 +201,7 @@ protected void handleTransportRequest(ServerHttpRequest request, ServerHttpRespo return; } - AbstractSockJsSession session = getSockJsSession(sessionId, webSocketHandler, transportHandler); + AbstractSockJsSession session = getSockJsSession(sessionId, handler, transportHandler); if (session != null) { if (transportType.setsNoCacheHeader()) { @@ -220,10 +220,10 @@ protected void handleTransportRequest(ServerHttpRequest request, ServerHttpRespo } } - transportHandler.handleRequest(request, response, webSocketHandler, session); + transportHandler.handleRequest(request, response, handler, session); } - public AbstractSockJsSession getSockJsSession(String sessionId, WebSocketHandler webSocketHandler, + public AbstractSockJsSession getSockJsSession(String sessionId, HandlerProvider<WebSocketHandler> handler, TransportHandler transportHandler) { AbstractSockJsSession session = this.sessions.get(sessionId); @@ -240,7 +240,7 @@ public AbstractSockJsSession getSockJsSession(String sessionId, WebSocketHandler return session; } logger.debug("Creating new session with session id \"" + sessionId + "\""); - session = (AbstractSockJsSession) sessionFactory.createSession(sessionId, webSocketHandler); + session = (AbstractSockJsSession) sessionFactory.createSession(sessionId, handler); this.sessions.put(sessionId, session); return session; }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/server/support/SockJsHttpRequestHandler.java
@@ -22,9 +22,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.http.server.AsyncServletServerHttpRequest; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; @@ -36,14 +33,15 @@ import org.springframework.web.util.UrlPathHelper; import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; +import org.springframework.websocket.support.SimpleHandlerProvider; /** * * @author Rossen Stoyanchev * @since 4.0 */ -public class SockJsHttpRequestHandler implements HttpRequestHandler, BeanFactoryAware { +public class SockJsHttpRequestHandler implements HttpRequestHandler { private final String prefix; @@ -61,15 +59,15 @@ public class SockJsHttpRequestHandler implements HttpRequestHandler, BeanFactory * that begins with the specified prefix will be handled by this service. In a * Servlet container this is the path within the current servlet mapping. */ - public SockJsHttpRequestHandler(String prefix, SockJsService sockJsService, WebSocketHandler webSocketHandler) { + public SockJsHttpRequestHandler(String prefix, SockJsService sockJsService, WebSocketHandler handler) { Assert.hasText(prefix, "prefix is required"); Assert.notNull(sockJsService, "sockJsService is required"); - Assert.notNull(webSocketHandler, "webSocketHandler is required"); + Assert.notNull(handler, "webSocketHandler is required"); this.prefix = prefix; this.sockJsService = sockJsService; - this.handlerProvider = new HandlerProvider<WebSocketHandler>(webSocketHandler); + this.handlerProvider = new SimpleHandlerProvider<WebSocketHandler>(handler); } /** @@ -80,15 +78,15 @@ public SockJsHttpRequestHandler(String prefix, SockJsService sockJsService, WebS * Servlet container this is the path within the current servlet mapping. */ public SockJsHttpRequestHandler(String prefix, SockJsService sockJsService, - Class<? extends WebSocketHandler> webSocketHandlerClass) { + HandlerProvider<WebSocketHandler> handlerProvider) { Assert.hasText(prefix, "prefix is required"); Assert.notNull(sockJsService, "sockJsService is required"); - Assert.notNull(webSocketHandlerClass, "webSocketHandlerClass is required"); + Assert.notNull(handlerProvider, "handlerProvider is required"); this.prefix = prefix; this.sockJsService = sockJsService; - this.handlerProvider = new HandlerProvider<WebSocketHandler>(webSocketHandlerClass); + this.handlerProvider = handlerProvider; } public String getPrefix() { @@ -99,11 +97,6 @@ public String getPattern() { return this.prefix + "/**"; } - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.handlerProvider.setBeanFactory(beanFactory); - } - @Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { @@ -119,8 +112,7 @@ public void handleRequest(HttpServletRequest request, HttpServletResponse respon ServerHttpResponse httpResponse = new ServletServerHttpResponse(response); try { - WebSocketHandler webSocketHandler = this.handlerProvider.getHandler(); - this.sockJsService.handleRequest(httpRequest, httpResponse, sockJsPath, webSocketHandler); + this.sockJsService.handleRequest(httpRequest, httpResponse, sockJsPath, this.handlerProvider); } catch (Exception ex) { // TODO
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractHttpReceivingTransportHandler.java
@@ -27,6 +27,7 @@ import org.springframework.http.server.ServerHttpResponse; import org.springframework.sockjs.AbstractSockJsSession; import org.springframework.sockjs.server.TransportHandler; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; import com.fasterxml.jackson.databind.JsonMappingException; @@ -53,7 +54,7 @@ public ObjectMapper getObjectMapper() { @Override public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response, - WebSocketHandler webSocketHandler, AbstractSockJsSession session) throws Exception { + HandlerProvider<WebSocketHandler> webSocketHandler, AbstractSockJsSession session) throws Exception { if (session == null) { response.setStatusCode(HttpStatus.NOT_FOUND);
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractHttpSendingTransportHandler.java
@@ -28,6 +28,7 @@ import org.springframework.sockjs.server.SockJsConfiguration; import org.springframework.sockjs.server.SockJsFrame; import org.springframework.sockjs.server.SockJsFrame.FrameFormat; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; /** @@ -55,7 +56,7 @@ public SockJsConfiguration getSockJsConfig() { @Override public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response, - WebSocketHandler webSocketHandler, AbstractSockJsSession session) throws Exception { + HandlerProvider<WebSocketHandler> webSocketHandler, AbstractSockJsSession session) throws Exception { // Set content type before writing response.getHeaders().setContentType(getContentType());
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractHttpServerSockJsSession.java
@@ -29,6 +29,7 @@ import org.springframework.sockjs.server.TransportHandler; import org.springframework.util.Assert; import org.springframework.websocket.CloseStatus; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; /** @@ -49,9 +50,9 @@ public abstract class AbstractHttpServerSockJsSession extends AbstractServerSock public AbstractHttpServerSockJsSession(String sessionId, SockJsConfiguration sockJsConfig, - WebSocketHandler webSocketHandler) { + HandlerProvider<WebSocketHandler> handler) { - super(sessionId, sockJsConfig, webSocketHandler); + super(sessionId, sockJsConfig, handler); } public void setFrameFormat(FrameFormat frameFormat) {
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractStreamingTransportHandler.java
@@ -20,6 +20,7 @@ import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.util.Assert; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; @@ -33,9 +34,9 @@ public abstract class AbstractStreamingTransportHandler extends AbstractHttpSend @Override - public StreamingServerSockJsSession createSession(String sessionId, WebSocketHandler webSocketHandler) { + public StreamingServerSockJsSession createSession(String sessionId, HandlerProvider<WebSocketHandler> handler) { Assert.notNull(getSockJsConfig(), "This transport requires SockJsConfiguration"); - return new StreamingServerSockJsSession(sessionId, getSockJsConfig(), webSocketHandler); + return new StreamingServerSockJsSession(sessionId, getSockJsConfig(), handler); } @Override
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/JsonpPollingTransportHandler.java
@@ -27,6 +27,7 @@ import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.web.util.JavaScriptUtils; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; @@ -50,9 +51,9 @@ protected MediaType getContentType() { } @Override - public PollingServerSockJsSession createSession(String sessionId, WebSocketHandler webSocketHandler) { + public PollingServerSockJsSession createSession(String sessionId, HandlerProvider<WebSocketHandler> handler) { Assert.notNull(getSockJsConfig(), "This transport requires SockJsConfiguration"); - return new PollingServerSockJsSession(sessionId, getSockJsConfig(), webSocketHandler); + return new PollingServerSockJsSession(sessionId, getSockJsConfig(), handler); } @Override
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/PollingServerSockJsSession.java
@@ -17,15 +17,16 @@ import org.springframework.sockjs.server.SockJsConfiguration; import org.springframework.sockjs.server.SockJsFrame; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; public class PollingServerSockJsSession extends AbstractHttpServerSockJsSession { public PollingServerSockJsSession(String sessionId, SockJsConfiguration sockJsConfig, - WebSocketHandler webSocketHandler) { + HandlerProvider<WebSocketHandler> handler) { - super(sessionId, sockJsConfig, webSocketHandler); + super(sessionId, sockJsConfig, handler); } @Override
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/SockJsWebSocketHandler.java
@@ -17,8 +17,6 @@ package org.springframework.sockjs.server.transport; import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -29,6 +27,7 @@ import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.websocket.CloseStatus; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.TextMessage; import org.springframework.websocket.TextMessageHandler; import org.springframework.websocket.WebSocketHandler; @@ -38,8 +37,8 @@ /** - * A SockJS implementation of {@link WebSocketHandler}. Delegates messages to and from a - * {@link SockJsHandler} and adds SockJS message framing. + * A wrapper around a {@link WebSocketHandler} instance that parses and adds SockJS + * messages frames as well as sends SockJS heartbeat messages. * * @author Rossen Stoyanchev * @since 4.0 @@ -50,34 +49,28 @@ public class SockJsWebSocketHandler implements TextMessageHandler { private final SockJsConfiguration sockJsConfig; - private final WebSocketHandler webSocketHandler; + private final HandlerProvider<WebSocketHandler> handlerProvider; - private final Map<WebSocketSession, AbstractSockJsSession> sessions = - new ConcurrentHashMap<WebSocketSession, AbstractSockJsSession>(); + private AbstractSockJsSession session; // TODO: JSON library used must be configurable private final ObjectMapper objectMapper = new ObjectMapper(); - public SockJsWebSocketHandler(SockJsConfiguration sockJsConfig, WebSocketHandler webSocketHandler) { - Assert.notNull(sockJsConfig, "sockJsConfig is required"); - Assert.notNull(webSocketHandler, "webSocketHandler is required"); - this.sockJsConfig = sockJsConfig; - this.webSocketHandler = webSocketHandler; + public SockJsWebSocketHandler(SockJsConfiguration config, HandlerProvider<WebSocketHandler> handlerProvider) { + Assert.notNull(config, "sockJsConfig is required"); + Assert.notNull(handlerProvider, "handlerProvider is required"); + this.sockJsConfig = config; + this.handlerProvider = handlerProvider; } protected SockJsConfiguration getSockJsConfig() { return this.sockJsConfig; } - protected AbstractSockJsSession getSockJsSession(WebSocketSession wsSession) { - return this.sessions.get(wsSession); - } - @Override public void afterConnectionEstablished(WebSocketSession wsSession) throws Exception { - AbstractSockJsSession session = new WebSocketServerSockJsSession(wsSession, getSockJsConfig()); - this.sessions.put(wsSession, session); + this.session = new WebSocketServerSockJsSession(wsSession, getSockJsConfig()); } @Override @@ -89,8 +82,7 @@ public void handleTextMessage(TextMessage message, WebSocketSession wsSession) t } try { String[] messages = this.objectMapper.readValue(payload, String[].class); - AbstractSockJsSession session = getSockJsSession(wsSession); - session.delegateMessages(messages); + this.session.delegateMessages(messages); } catch (IOException e) { logger.error("Broken data received. Terminating WebSocket connection abruptly", e); @@ -100,14 +92,12 @@ public void handleTextMessage(TextMessage message, WebSocketSession wsSession) t @Override public void afterConnectionClosed(CloseStatus status, WebSocketSession wsSession) throws Exception { - AbstractSockJsSession session = this.sessions.remove(wsSession); - session.delegateConnectionClosed(status); + this.session.delegateConnectionClosed(status); } @Override public void handleError(Throwable exception, WebSocketSession webSocketSession) { - AbstractSockJsSession session = getSockJsSession(webSocketSession); - session.delegateError(exception); + this.session.delegateError(exception); } private static String getSockJsSessionId(WebSocketSession wsSession) { @@ -127,7 +117,7 @@ private class WebSocketServerSockJsSession extends AbstractServerSockJsSession { public WebSocketServerSockJsSession(WebSocketSession wsSession, SockJsConfiguration sockJsConfig) throws Exception { - super(getSockJsSessionId(wsSession), sockJsConfig, SockJsWebSocketHandler.this.webSocketHandler); + super(getSockJsSessionId(wsSession), sockJsConfig, SockJsWebSocketHandler.this.handlerProvider); this.wsSession = wsSession; TextMessage message = new TextMessage(SockJsFrame.openFrame().getContent()); this.wsSession.sendMessage(message);
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/StreamingServerSockJsSession.java
@@ -20,6 +20,7 @@ import org.springframework.http.server.ServerHttpResponse; import org.springframework.sockjs.server.SockJsConfiguration; import org.springframework.sockjs.server.SockJsFrame; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; @@ -29,9 +30,9 @@ public class StreamingServerSockJsSession extends AbstractHttpServerSockJsSessio public StreamingServerSockJsSession(String sessionId, SockJsConfiguration sockJsConfig, - WebSocketHandler webSocketHandler) { + HandlerProvider<WebSocketHandler> handler) { - super(sessionId, sockJsConfig, webSocketHandler); + super(sessionId, sockJsConfig, handler); } protected void flushCache() throws Exception {
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/WebSocketTransportHandler.java
@@ -24,8 +24,10 @@ import org.springframework.sockjs.server.TransportHandler; import org.springframework.sockjs.server.TransportType; import org.springframework.util.Assert; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; import org.springframework.websocket.server.HandshakeHandler; +import org.springframework.websocket.support.SimpleHandlerProvider; /** @@ -60,26 +62,19 @@ public void setSockJsConfiguration(SockJsConfiguration sockJsConfig) { @Override public void handleRequest(ServerHttpRequest request, ServerHttpResponse response, - WebSocketHandler webSocketHandler, AbstractSockJsSession session) throws Exception { + HandlerProvider<WebSocketHandler> handler, AbstractSockJsSession session) throws Exception { - this.handshakeHandler.doHandshake(request, response, adaptSockJsHandler(webSocketHandler)); - } - - /** - * Adapt the {@link SockJsHandler} to the {@link WebSocketHandler} contract for - * exchanging SockJS message over WebSocket. - */ - protected WebSocketHandler adaptSockJsHandler(WebSocketHandler handler) { - return new SockJsWebSocketHandler(this.sockJsConfig, handler); + WebSocketHandler sockJsWrapper = new SockJsWebSocketHandler(this.sockJsConfig, handler); + this.handshakeHandler.doHandshake(request, response, new SimpleHandlerProvider<WebSocketHandler>(sockJsWrapper)); } // HandshakeHandler methods @Override public boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, - WebSocketHandler webSocketHandler) throws Exception { + HandlerProvider<WebSocketHandler> handler) throws Exception { - return this.handshakeHandler.doHandshake(request, response, webSocketHandler); + return this.handshakeHandler.doHandshake(request, response, handler); } }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/XhrPollingTransportHandler.java
@@ -23,6 +23,7 @@ import org.springframework.sockjs.server.SockJsFrame.FrameFormat; import org.springframework.sockjs.server.TransportType; import org.springframework.util.Assert; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; @@ -50,9 +51,9 @@ protected FrameFormat getFrameFormat(ServerHttpRequest request) { return new DefaultFrameFormat("%s\n"); } - public PollingServerSockJsSession createSession(String sessionId, WebSocketHandler webSocketHandler) { + public PollingServerSockJsSession createSession(String sessionId, HandlerProvider<WebSocketHandler> handler) { Assert.notNull(getSockJsConfig(), "This transport requires SockJsConfiguration"); - return new PollingServerSockJsSession(sessionId, getSockJsConfig(), webSocketHandler); + return new PollingServerSockJsSession(sessionId, getSockJsConfig(), handler); } }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/websocket/HandlerProvider.java
@@ -5,90 +5,44 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.websocket; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.config.AutowireCapableBeanFactory; -import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; - /** + * A strategy for obtaining a handler instance that is scoped to external lifecycle events + * such as the opening and closing of a WebSocket connection. * * @author Rossen Stoyanchev * @since 4.0 */ -public class HandlerProvider<T> implements BeanFactoryAware { - - private Log logger = LogFactory.getLog(this.getClass()); - - private final T handlerBean; - - private final Class<? extends T> handlerClass; - - private AutowireCapableBeanFactory beanFactory; - - - public HandlerProvider(T handlerBean) { - Assert.notNull(handlerBean, "handlerBean is required"); - this.handlerBean = handlerBean; - this.handlerClass = null; - } - - public HandlerProvider(Class<? extends T> handlerClass) { - Assert.notNull(handlerClass, "handlerClass is required"); - this.handlerBean = null; - this.handlerClass = handlerClass; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - if (beanFactory instanceof AutowireCapableBeanFactory) { - this.beanFactory = (AutowireCapableBeanFactory) beanFactory; - } - } - - public void setLogger(Log logger) { - this.logger = logger; - } - - public boolean isSingleton() { - return (this.handlerBean != null); - } - - @SuppressWarnings("unchecked") - public Class<? extends T> getHandlerType() { - if (this.handlerClass != null) { - return this.handlerClass; - } - return (Class<? extends T>) ClassUtils.getUserClass(this.handlerBean.getClass()); - } - - public T getHandler() { - if (this.handlerBean != null) { - if (logger != null && logger.isTraceEnabled()) { - logger.trace("Returning handler singleton " + this.handlerBean); - } - return this.handlerBean; - } - Assert.isTrue(this.beanFactory != null, "BeanFactory is required to initialize handler instances."); - if (logger != null && logger.isTraceEnabled()) { - logger.trace("Creating handler of type " + this.handlerClass); - } - return this.beanFactory.createBean(this.handlerClass); - } +public interface HandlerProvider<T> { + + /** + * Whether the provided handler is a shared instance or not. + */ + boolean isSingleton(); + + /** + * The type of handler provided. + */ + Class<?> getHandlerType(); + + /** + * Obtain the handler instance, either shared or created every time. + */ + T getHandler(); + + /** + * Callback to destroy a previously created handler instance if it is not shared. + */ + void destroy(T handler); }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/websocket/client/WebSocketClient.java
@@ -18,6 +18,7 @@ import java.net.URI; import org.springframework.http.HttpHeaders; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; import org.springframework.websocket.WebSocketSession; @@ -36,13 +37,10 @@ public interface WebSocketClient { - WebSocketSession doHandshake(WebSocketHandler handler, String uriTemplate, Object... uriVariables) - throws WebSocketConnectFailureException; - - WebSocketSession doHandshake(WebSocketHandler handler, URI uri) - throws WebSocketConnectFailureException; + WebSocketSession doHandshake(HandlerProvider<WebSocketHandler> handler, + String uriTemplate, Object... uriVariables) throws WebSocketConnectFailureException; - WebSocketSession doHandshake(WebSocketHandler handler, HttpHeaders headers, URI uri) + WebSocketSession doHandshake(HandlerProvider<WebSocketHandler> handler, HttpHeaders headers, URI uri) throws WebSocketConnectFailureException; }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/websocket/client/WebSocketConnectionManager.java
@@ -21,6 +21,7 @@ import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; import org.springframework.websocket.WebSocketSession; +import org.springframework.websocket.support.SimpleHandlerProvider; /** @@ -32,7 +33,7 @@ public class WebSocketConnectionManager extends AbstractWebSocketConnectionManag private final WebSocketClient client; - private final HandlerProvider<WebSocketHandler> webSocketHandlerProvider; + private final HandlerProvider<WebSocketHandler> handlerProvider; private WebSocketSession webSocketSession; @@ -43,8 +44,16 @@ public WebSocketConnectionManager(WebSocketClient webSocketClient, WebSocketHandler webSocketHandler, String uriTemplate, Object... uriVariables) { super(uriTemplate, uriVariables); - this.webSocketHandlerProvider = new HandlerProvider<WebSocketHandler>(webSocketHandler); this.client = webSocketClient; + this.handlerProvider = new SimpleHandlerProvider<WebSocketHandler>(webSocketHandler); + } + + public WebSocketConnectionManager(WebSocketClient webSocketClient, + HandlerProvider<WebSocketHandler> handlerProvider, String uriTemplate, Object... uriVariables) { + + super(uriTemplate, uriVariables); + this.client = webSocketClient; + this.handlerProvider = handlerProvider; } public void setSubProtocols(List<String> subProtocols) { @@ -57,10 +66,9 @@ public List<String> getSubProtocols() { @Override protected void openConnection() throws Exception { - WebSocketHandler webSocketHandler = this.webSocketHandlerProvider.getHandler(); HttpHeaders headers = new HttpHeaders(); headers.setSecWebSocketProtocol(this.subProtocols); - this.webSocketSession = this.client.doHandshake(webSocketHandler, headers, getUri()); + this.webSocketSession = this.client.doHandshake(this.handlerProvider, headers, getUri()); } @Override
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/websocket/client/endpoint/AnnotatedEndpointConnectionManager.java
@@ -22,6 +22,8 @@ import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.websocket.HandlerProvider; +import org.springframework.websocket.support.BeanCreatingHandlerProvider; +import org.springframework.websocket.support.SimpleHandlerProvider; /** @@ -32,28 +34,29 @@ public class AnnotatedEndpointConnectionManager extends EndpointConnectionManagerSupport implements BeanFactoryAware { - private final HandlerProvider<Object> endpointProvider; + private final HandlerProvider<Object> handlerProvider; - public AnnotatedEndpointConnectionManager(Class<?> endpointClass, String uriTemplate, Object... uriVariables) { + public AnnotatedEndpointConnectionManager(Object endpointBean, String uriTemplate, Object... uriVariables) { super(uriTemplate, uriVariables); - this.endpointProvider = new HandlerProvider<Object>(endpointClass); + this.handlerProvider = new SimpleHandlerProvider<Object>(endpointBean); } - public AnnotatedEndpointConnectionManager(Object endpointBean, String uriTemplate, Object... uriVariables) { + public AnnotatedEndpointConnectionManager(Class<?> endpointClass, String uriTemplate, Object... uriVariables) { super(uriTemplate, uriVariables); - this.endpointProvider = new HandlerProvider<Object>(endpointBean); + this.handlerProvider = new BeanCreatingHandlerProvider<Object>(endpointClass); } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.endpointProvider.setBeanFactory(beanFactory); + if (this.handlerProvider instanceof BeanFactoryAware) { + ((BeanFactoryAware) this.handlerProvider).setBeanFactory(beanFactory); + } } - @Override protected void openConnection() throws Exception { - Object endpoint = this.endpointProvider.getHandler(); + Object endpoint = this.handlerProvider.getHandler(); Session session = getWebSocketContainer().connectToServer(endpoint, getUri()); updateSession(session); }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/websocket/client/endpoint/EndpointConnectionManager.java
@@ -32,6 +32,8 @@ import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.util.Assert; import org.springframework.websocket.HandlerProvider; +import org.springframework.websocket.support.BeanCreatingHandlerProvider; +import org.springframework.websocket.support.SimpleHandlerProvider; /** @@ -43,19 +45,19 @@ public class EndpointConnectionManager extends EndpointConnectionManagerSupport private final ClientEndpointConfig.Builder configBuilder = ClientEndpointConfig.Builder.create(); - private final HandlerProvider<Endpoint> endpointProvider; + private final HandlerProvider<Endpoint> handlerProvider; public EndpointConnectionManager(Endpoint endpointBean, String uriTemplate, Object... uriVariables) { super(uriTemplate, uriVariables); Assert.notNull(endpointBean, "endpointBean is required"); - this.endpointProvider = new HandlerProvider<Endpoint>(endpointBean); + this.handlerProvider = new SimpleHandlerProvider<Endpoint>(endpointBean); } public EndpointConnectionManager(Class<? extends Endpoint> endpointClass, String uriTemplate, Object... uriVars) { super(uriTemplate, uriVars); Assert.notNull(endpointClass, "endpointClass is required"); - this.endpointProvider = new HandlerProvider<Endpoint>(endpointClass); + this.handlerProvider = new BeanCreatingHandlerProvider<Endpoint>(endpointClass); } public void setSubProtocols(String... subprotocols) { @@ -80,12 +82,14 @@ public void setConfigurator(Configurator configurator) { @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.endpointProvider.setBeanFactory(beanFactory); + if (this.handlerProvider instanceof BeanFactoryAware) { + ((BeanFactoryAware) this.handlerProvider).setBeanFactory(beanFactory); + } } @Override protected void openConnection() throws Exception { - Endpoint endpoint = this.endpointProvider.getHandler(); + Endpoint endpoint = this.handlerProvider.getHandler(); ClientEndpointConfig endpointConfig = this.configBuilder.build(); Session session = getWebSocketContainer().connectToServer(endpoint, endpointConfig, getUri()); updateSession(session);
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/websocket/client/endpoint/StandardWebSocketClient.java
@@ -31,6 +31,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.web.util.UriComponentsBuilder; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; import org.springframework.websocket.WebSocketSession; import org.springframework.websocket.client.WebSocketClient; @@ -40,6 +41,7 @@ /** + * A standard Java {@link WebSocketClient}. * * @author Rossen Stoyanchev * @since 4.0 @@ -57,21 +59,16 @@ public void setWebSocketContainer(WebSocketContainer container) { this.webSocketContainer = container; } - public WebSocketSession doHandshake(WebSocketHandler handler, String uriTemplate, - Object... uriVariables) throws WebSocketConnectFailureException { + public WebSocketSession doHandshake(HandlerProvider<WebSocketHandler> handler, + String uriTemplate, Object... uriVariables) throws WebSocketConnectFailureException { URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(uriVariables).encode().toUri(); - return doHandshake(handler, uri); - } - - @Override - public WebSocketSession doHandshake(WebSocketHandler handler, URI uri) throws WebSocketConnectFailureException { return doHandshake(handler, null, uri); } @Override - public WebSocketSession doHandshake(WebSocketHandler handler, final HttpHeaders httpHeaders, URI uri) - throws WebSocketConnectFailureException { + public WebSocketSession doHandshake(HandlerProvider<WebSocketHandler> handler, + final HttpHeaders httpHeaders, URI uri) throws WebSocketConnectFailureException { Endpoint endpoint = new WebSocketHandlerEndpoint(handler);
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/websocket/endpoint/WebSocketHandlerEndpoint.java
@@ -16,9 +16,6 @@ package org.springframework.websocket.endpoint; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - import javax.websocket.CloseReason; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; @@ -27,14 +24,15 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.util.Assert; -import org.springframework.websocket.CloseStatus; import org.springframework.websocket.BinaryMessage; import org.springframework.websocket.BinaryMessageHandler; +import org.springframework.websocket.CloseStatus; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.PartialMessageHandler; -import org.springframework.websocket.WebSocketHandler; -import org.springframework.websocket.WebSocketSession; import org.springframework.websocket.TextMessage; import org.springframework.websocket.TextMessageHandler; +import org.springframework.websocket.WebSocketHandler; +import org.springframework.websocket.WebSocketSession; /** @@ -47,14 +45,17 @@ public class WebSocketHandlerEndpoint extends Endpoint { private static Log logger = LogFactory.getLog(WebSocketHandlerEndpoint.class); - private final WebSocketHandler webSocketHandler; + private final HandlerProvider<WebSocketHandler> handlerProvider; - private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<String, WebSocketSession>(); + private final WebSocketHandler handler; + private WebSocketSession webSocketSession; - public WebSocketHandlerEndpoint(WebSocketHandler handler) { - Assert.notNull(handler, "webSocketHandler is required"); - this.webSocketHandler = handler; + + public WebSocketHandlerEndpoint(HandlerProvider<WebSocketHandler> handlerProvider) { + Assert.notNull(handlerProvider, "handlerProvider is required"); + this.handlerProvider = handlerProvider; + this.handler = handlerProvider.getHandler(); } @Override @@ -63,19 +64,18 @@ public void onOpen(final javax.websocket.Session session, EndpointConfig config) logger.debug("Client connected, WebSocket session id=" + session.getId() + ", uri=" + session.getRequestURI()); } try { - WebSocketSession webSocketSession = new StandardWebSocketSession(session); - this.sessions.put(session.getId(), webSocketSession); + this.webSocketSession = new StandardWebSocketSession(session); - if (this.webSocketHandler instanceof TextMessageHandler) { + if (this.handler instanceof TextMessageHandler) { session.addMessageHandler(new MessageHandler.Whole<String>() { @Override public void onMessage(String message) { handleTextMessage(session, message); } }); } - else if (this.webSocketHandler instanceof BinaryMessageHandler) { - if (this.webSocketHandler instanceof PartialMessageHandler) { + else if (this.handler instanceof BinaryMessageHandler) { + if (this.handler instanceof PartialMessageHandler) { session.addMessageHandler(new MessageHandler.Partial<byte[]>() { @Override public void onMessage(byte[] messagePart, boolean isLast) { @@ -93,10 +93,10 @@ public void onMessage(byte[] message) { } } else { - logger.warn("WebSocketHandler handles neither text nor binary messages: " + this.webSocketHandler); + logger.warn("WebSocketHandler handles neither text nor binary messages: " + this.handler); } - this.webSocketHandler.afterConnectionEstablished(webSocketSession); + this.handler.afterConnectionEstablished(this.webSocketSession); } catch (Throwable ex) { // TODO @@ -108,11 +108,9 @@ private void handleTextMessage(javax.websocket.Session session, String message) if (logger.isTraceEnabled()) { logger.trace("Received message for WebSocket session id=" + session.getId() + ": " + message); } - WebSocketSession wsSession = getWebSocketSession(session); - Assert.notNull(wsSession, "WebSocketSession not found"); try { TextMessage textMessage = new TextMessage(message); - ((TextMessageHandler) webSocketHandler).handleTextMessage(textMessage, wsSession); + ((TextMessageHandler) handler).handleTextMessage(textMessage, this.webSocketSession); } catch (Throwable ex) { // TODO @@ -124,11 +122,9 @@ private void handleBinaryMessage(javax.websocket.Session session, byte[] message if (logger.isTraceEnabled()) { logger.trace("Received binary data for WebSocket session id=" + session.getId()); } - WebSocketSession wsSession = getWebSocketSession(session); - Assert.notNull(wsSession, "WebSocketSession not found"); try { BinaryMessage binaryMessage = new BinaryMessage(message, isLast); - ((BinaryMessageHandler) webSocketHandler).handleBinaryMessage(binaryMessage, wsSession); + ((BinaryMessageHandler) handler).handleBinaryMessage(binaryMessage, this.webSocketSession); } catch (Throwable ex) { // TODO @@ -142,41 +138,28 @@ public void onClose(javax.websocket.Session session, CloseReason reason) { logger.debug("Client disconnected, WebSocket session id=" + session.getId() + ", " + reason); } try { - WebSocketSession wsSession = this.sessions.remove(session.getId()); - if (wsSession != null) { - CloseStatus closeStatus = new CloseStatus(reason.getCloseCode().getCode(), reason.getReasonPhrase()); - this.webSocketHandler.afterConnectionClosed(closeStatus, wsSession); - } - else { - Assert.notNull(wsSession, "No WebSocket session"); - } + CloseStatus closeStatus = new CloseStatus(reason.getCloseCode().getCode(), reason.getReasonPhrase()); + this.handler.afterConnectionClosed(closeStatus, this.webSocketSession); } catch (Throwable ex) { // TODO logger.error("Error while processing session closing", ex); } + finally { + this.handlerProvider.destroy(this.handler); + } } @Override public void onError(javax.websocket.Session session, Throwable exception) { logger.error("Error for WebSocket session id=" + session.getId(), exception); try { - WebSocketSession wsSession = getWebSocketSession(session); - if (wsSession != null) { - this.webSocketHandler.handleError(exception, wsSession); - } - else { - logger.warn("WebSocketSession not found. Perhaps onError was called after onClose?"); - } + this.handler.handleError(exception, this.webSocketSession); } catch (Throwable ex) { // TODO logger.error("Failed to handle error", ex); } } - private WebSocketSession getWebSocketSession(javax.websocket.Session session) { - return this.sessions.get(session.getId()); - } - }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/websocket/server/DefaultHandshakeHandler.java
@@ -35,6 +35,7 @@ import org.springframework.http.server.ServerHttpResponse; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; @@ -87,7 +88,7 @@ public String[] getSupportedProtocols() { @Override public final boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, - WebSocketHandler webSocketHandler) throws Exception { + HandlerProvider<WebSocketHandler> handler) throws Exception { logger.debug("Starting handshake for " + request.getURI()); @@ -135,10 +136,10 @@ public final boolean doHandshake(ServerHttpRequest request, ServerHttpResponse r response.flush(); if (logger.isTraceEnabled()) { - logger.trace("Upgrading with " + webSocketHandler); + logger.trace("Upgrading with " + handler); } - this.requestUpgradeStrategy.upgrade(request, response, selectedProtocol, webSocketHandler); + this.requestUpgradeStrategy.upgrade(request, response, selectedProtocol, handler); return true; }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/websocket/server/HandshakeHandler.java
@@ -18,6 +18,7 @@ import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; @@ -29,16 +30,8 @@ */ public interface HandshakeHandler { - /** - * - * @param request the HTTP request - * @param response the HTTP response - * @param webSocketMessageHandler the handler to process WebSocket messages with - * @return a boolean indicating whether the handshake negotiation was successful - * - * @throws Exception - */ - boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler) - throws Exception; + + boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, + HandlerProvider<WebSocketHandler> handler) throws Exception; }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/websocket/server/RequestUpgradeStrategy.java
@@ -18,6 +18,7 @@ import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; @@ -39,9 +40,9 @@ public interface RequestUpgradeStrategy { * Perform runtime specific steps to complete the upgrade. * Invoked only if the handshake is successful. * - * @param webSocketHandler the handler for WebSocket messages + * @param handler the handler for WebSocket messages */ void upgrade(ServerHttpRequest request, ServerHttpResponse response, String selectedProtocol, - WebSocketHandler webSocketHandler) throws Exception; + HandlerProvider<WebSocketHandler> handler) throws Exception; }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/websocket/server/endpoint/EndpointRegistration.java
@@ -37,6 +37,8 @@ import org.springframework.util.Assert; import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.endpoint.WebSocketHandlerEndpoint; +import org.springframework.websocket.support.BeanCreatingHandlerProvider; +import org.springframework.websocket.support.SimpleHandlerProvider; /** @@ -54,11 +56,9 @@ */ public class EndpointRegistration implements ServerEndpointConfig, BeanFactoryAware { - private static Log logger = LogFactory.getLog(EndpointRegistration.class); - private final String path; - private final HandlerProvider<Endpoint> endpointProvider; + private final HandlerProvider<Endpoint> handlerProvider; private List<Class<? extends Encoder>> encoders = new ArrayList<Class<? extends Encoder>>(); @@ -84,16 +84,14 @@ public EndpointRegistration(String path, Class<? extends Endpoint> endpointClass Assert.hasText(path, "path must not be empty"); Assert.notNull(endpointClass, "endpointClass is required"); this.path = path; - this.endpointProvider = new HandlerProvider<Endpoint>(endpointClass); - this.endpointProvider.setLogger(logger); + this.handlerProvider = new BeanCreatingHandlerProvider<Endpoint>(endpointClass); } public EndpointRegistration(String path, Endpoint endpointBean) { Assert.hasText(path, "path must not be empty"); Assert.notNull(endpointBean, "endpointBean is required"); this.path = path; - this.endpointProvider = new HandlerProvider<Endpoint>(endpointBean); - this.endpointProvider.setLogger(logger); + this.handlerProvider = new SimpleHandlerProvider<Endpoint>(endpointBean); } @Override @@ -102,12 +100,13 @@ public String getPath() { } @Override + @SuppressWarnings("unchecked") public Class<? extends Endpoint> getEndpointClass() { - return this.endpointProvider.getHandlerType(); + return (Class<? extends Endpoint>) this.handlerProvider.getHandlerType(); } public Endpoint getEndpoint() { - return this.endpointProvider.getHandler(); + return this.handlerProvider.getHandler(); } public void setSubprotocols(List<String> subprotocols) { @@ -193,7 +192,9 @@ public List<Extension> getNegotiatedExtensions(List<Extension> installed, List<E @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.endpointProvider.setBeanFactory(beanFactory); + if (this.handlerProvider instanceof BeanFactoryAware) { + ((BeanFactoryAware) this.handlerProvider).setBeanFactory(beanFactory); + } } }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/websocket/server/support/AbstractEndpointContainerFactoryBean.java
@@ -1,88 +0,0 @@ -/* - * Copyright 2002-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.websocket.server.support; - -import javax.websocket.WebSocketContainer; - -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.InitializingBean; - - -/** -* -* @author Rossen Stoyanchev -* @since 4.0 -*/ -public abstract class AbstractEndpointContainerFactoryBean implements FactoryBean<WebSocketContainer>, InitializingBean { - - private WebSocketContainer container; - - - public void setAsyncSendTimeout(long timeoutInMillis) { - this.container.setAsyncSendTimeout(timeoutInMillis); - } - - public long getAsyncSendTimeout() { - return this.container.getDefaultAsyncSendTimeout(); - } - - public void setMaxSessionIdleTimeout(long timeoutInMillis) { - this.container.setDefaultMaxSessionIdleTimeout(timeoutInMillis); - } - - public long getMaxSessionIdleTimeout() { - return this.container.getDefaultMaxSessionIdleTimeout(); - } - - public void setMaxTextMessageBufferSize(int bufferSize) { - this.container.setDefaultMaxTextMessageBufferSize(bufferSize); - } - - public int getMaxTextMessageBufferSize() { - return this.container.getDefaultMaxTextMessageBufferSize(); - } - - public void setMaxBinaryMessageBufferSize(int bufferSize) { - this.container.setDefaultMaxBinaryMessageBufferSize(bufferSize); - } - - public int getMaxBinaryMessageBufferSize() { - return this.container.getDefaultMaxBinaryMessageBufferSize(); - } - - @Override - public void afterPropertiesSet() throws Exception { - this.container = getContainer(); - } - - protected abstract WebSocketContainer getContainer(); - - @Override - public WebSocketContainer getObject() throws Exception { - return this.container; - } - - @Override - public Class<?> getObjectType() { - return WebSocketContainer.class; - } - - @Override - public boolean isSingleton() { - return true; - } - -}
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/websocket/server/support/AbstractEndpointUpgradeStrategy.java
@@ -22,6 +22,7 @@ import org.apache.commons.logging.LogFactory; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; +import org.springframework.websocket.HandlerProvider; import org.springframework.websocket.WebSocketHandler; import org.springframework.websocket.endpoint.WebSocketHandlerEndpoint; import org.springframework.websocket.server.RequestUpgradeStrategy; @@ -41,12 +42,12 @@ public abstract class AbstractEndpointUpgradeStrategy implements RequestUpgradeS @Override public void upgrade(ServerHttpRequest request, ServerHttpResponse response, - String protocol, WebSocketHandler webSocketHandler) throws Exception { + String protocol, HandlerProvider<WebSocketHandler> handler) throws Exception { - upgradeInternal(request, response, protocol, adaptWebSocketHandler(webSocketHandler)); + upgradeInternal(request, response, protocol, adaptWebSocketHandler(handler)); } - protected Endpoint adaptWebSocketHandler(WebSocketHandler handler) { + protected Endpoint adaptWebSocketHandler(HandlerProvider<WebSocketHandler> handler) { return new WebSocketHandlerEndpoint(handler); }
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/websocket/server/support/WebSocketHttpRequestHandler.java
@@ -22,9 +22,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; @@ -36,6 +33,7 @@ import org.springframework.websocket.WebSocketHandler; import org.springframework.websocket.server.DefaultHandshakeHandler; import org.springframework.websocket.server.HandshakeHandler; +import org.springframework.websocket.support.SimpleHandlerProvider; /** @@ -44,7 +42,7 @@ * @author Rossen Stoyanchev * @since 4.0 */ -public class WebSocketHttpRequestHandler implements HttpRequestHandler, BeanFactoryAware { +public class WebSocketHttpRequestHandler implements HttpRequestHandler { private HandshakeHandler handshakeHandler; @@ -53,25 +51,20 @@ public class WebSocketHttpRequestHandler implements HttpRequestHandler, BeanFact public WebSocketHttpRequestHandler(WebSocketHandler webSocketHandler) { Assert.notNull(webSocketHandler, "webSocketHandler is required"); - this.handlerProvider = new HandlerProvider<WebSocketHandler>(webSocketHandler); + this.handlerProvider = new SimpleHandlerProvider<WebSocketHandler>(webSocketHandler); this.handshakeHandler = new DefaultHandshakeHandler(); } - public WebSocketHttpRequestHandler( Class<? extends WebSocketHandler> webSocketHandlerClass) { - Assert.notNull(webSocketHandlerClass, "webSocketHandlerClass is required"); - this.handlerProvider = new HandlerProvider<WebSocketHandler>(webSocketHandlerClass); + public WebSocketHttpRequestHandler( HandlerProvider<WebSocketHandler> handlerProvider) { + Assert.notNull(handlerProvider, "handlerProvider is required"); + this.handlerProvider = handlerProvider; } public void setHandshakeHandler(HandshakeHandler handshakeHandler) { Assert.notNull(handshakeHandler, "handshakeHandler is required"); this.handshakeHandler = handshakeHandler; } - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.handlerProvider.setBeanFactory(beanFactory); - } - @Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { @@ -80,8 +73,7 @@ public void handleRequest(HttpServletRequest request, HttpServletResponse respon ServerHttpResponse httpResponse = new ServletServerHttpResponse(response); try { - WebSocketHandler webSocketHandler = this.handlerProvider.getHandler(); - this.handshakeHandler.doHandshake(httpRequest, httpResponse, webSocketHandler); + this.handshakeHandler.doHandshake(httpRequest, httpResponse, this.handlerProvider); } catch (Exception e) { // TODO
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/websocket/support/BeanCreatingHandlerProvider.java
@@ -0,0 +1,94 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.websocket.support; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.util.Assert; +import org.springframework.websocket.HandlerProvider; + + +/** + * A {@link HandlerProvider} that uses {@link AutowireCapableBeanFactory#createBean(Class) + * creating a fresh instance every time #getHandler() is called. + * + * @author Rossen Stoyanchev + * @since 4.0 + */ +public class BeanCreatingHandlerProvider<T> implements HandlerProvider<T>, BeanFactoryAware { + + private static final Log logger = LogFactory.getLog(BeanCreatingHandlerProvider.class); + + private final Class<? extends T> handlerClass; + + private AutowireCapableBeanFactory beanFactory; + + + public BeanCreatingHandlerProvider(Class<? extends T> handlerClass) { + Assert.notNull(handlerClass, "handlerClass is required"); + this.handlerClass = handlerClass; + } + + @Override + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + if (beanFactory instanceof AutowireCapableBeanFactory) { + this.beanFactory = (AutowireCapableBeanFactory) beanFactory; + } + } + + public boolean isSingleton() { + return false; + } + + public Class<? extends T> getHandlerType() { + return this.handlerClass; + } + + public T getHandler() { + if (logger.isTraceEnabled()) { + logger.trace("Creating instance for handler type " + this.handlerClass); + } + if (this.beanFactory == null) { + logger.warn("No BeanFactory available, attempting to use default constructor"); + return BeanUtils.instantiate(this.handlerClass); + } + else { + return this.beanFactory.createBean(this.handlerClass); + } + } + + @Override + public void destroy(T handler) { + if (this.beanFactory != null) { + if (logger.isTraceEnabled()) { + logger.trace("Destroying handler instance " + handler); + } + this.beanFactory.destroyBean(handler); + } + } + + @Override + public String toString() { + return "BeanCreatingHandlerProvider [handlerClass=" + handlerClass + "]"; + } + +}
true
Other
spring-projects
spring-framework
84089bf3968443e4f6bb9239dace0692734d6578.json
Add HandlerProvider interface HandlerProvider is now an interface that can be used to plug in WebSocket handlers with per-connection scope semantics. There are two implementations, of the interface, one simple and a second that creates handler instances through AutowireCapableBeanFactory. HandlerProvider also provides a destroy method that is used to apply a destroy callback whenever a client connection closes.
spring-websocket/src/main/java/org/springframework/websocket/support/SimpleHandlerProvider.java
@@ -0,0 +1,61 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.websocket.support; + +import org.springframework.util.ClassUtils; +import org.springframework.websocket.HandlerProvider; + + +/** + * A {@link HandlerProvider} that returns a singleton instance. + * + * @author Rossen Stoyanchev + * @since 4.0 + */ +public class SimpleHandlerProvider<T> implements HandlerProvider<T> { + + private final T handler; + + + public SimpleHandlerProvider(T handler) { + this.handler = handler; + } + + @Override + public boolean isSingleton() { + return true; + } + + @Override + public Class<?> getHandlerType() { + return ClassUtils.getUserClass(this.handler); + } + + @Override + public T getHandler() { + return this.handler; + } + + @Override + public void destroy(T handler) { + } + + @Override + public String toString() { + return "SimpleHandlerProvider [handler=" + handler + "]"; + } + +}
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/HandlerProvider.java
@@ -17,6 +17,7 @@ package org.springframework.websocket; import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; @@ -32,14 +33,14 @@ */ public class HandlerProvider<T> implements BeanFactoryAware { + private Log logger = LogFactory.getLog(this.getClass()); + private final T handlerBean; private final Class<? extends T> handlerClass; private AutowireCapableBeanFactory beanFactory; - private Log logger; - public HandlerProvider(T handlerBean) { Assert.notNull(handlerBean, "handlerBean is required");
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/WebSocketHandshakeRequest.java
@@ -0,0 +1,48 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.websocket; + +import java.net.URI; + +import org.springframework.http.HttpHeaders; + + +/** + * + * @author Rossen Stoyanchev + * @since 4.0 + */ +public class WebSocketHandshakeRequest { + + private final URI uri; + + private final HttpHeaders headers; + + + public WebSocketHandshakeRequest(HttpHeaders headers, URI uri) { + this.headers = HttpHeaders.readOnlyHttpHeaders(headers); + this.uri = uri; + } + + public URI getUri() { + return this.uri; + } + + public HttpHeaders getHeaders() { + return this.headers; + } + +}
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/client/AbstractWebSocketConnectionManager.java
@@ -5,25 +5,18 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.websocket.client; -import java.io.IOException; import java.net.URI; -import javax.websocket.ContainerProvider; -import javax.websocket.DeploymentException; -import javax.websocket.Session; -import javax.websocket.WebSocketContainer; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.SmartLifecycle; @@ -37,7 +30,7 @@ * @author Rossen Stoyanchev * @since 4.0 */ -public abstract class AbstractEndpointConnectionManager implements SmartLifecycle { +public abstract class AbstractWebSocketConnectionManager implements SmartLifecycle { protected final Log logger = LogFactory.getLog(getClass()); @@ -47,35 +40,15 @@ public abstract class AbstractEndpointConnectionManager implements SmartLifecycl private int phase = Integer.MAX_VALUE; - private final WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer(); - - private Session session; - private TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor("EndpointConnectionManager-"); private final Object lifecycleMonitor = new Object(); - public AbstractEndpointConnectionManager(String uriTemplate, Object... uriVariables) { + public AbstractWebSocketConnectionManager(String uriTemplate, Object... uriVariables) { this.uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(uriVariables).encode().toUri(); } - public void setAsyncSendTimeout(long timeoutInMillis) { - this.webSocketContainer.setAsyncSendTimeout(timeoutInMillis); - } - - public void setMaxSessionIdleTimeout(long timeoutInMillis) { - this.webSocketContainer.setDefaultMaxSessionIdleTimeout(timeoutInMillis); - } - - public void setMaxTextMessageBufferSize(int bufferSize) { - this.webSocketContainer.setDefaultMaxTextMessageBufferSize(bufferSize); - } - - public void setMaxBinaryMessageBufferSize(Integer bufferSize) { - this.webSocketContainer.setDefaultMaxBinaryMessageBufferSize(bufferSize); - } - /** * Set whether to auto-connect to the remote endpoint after this connection manager * has been initialized and the Spring context has been refreshed. @@ -117,27 +90,24 @@ protected URI getUri() { return this.uri; } - protected WebSocketContainer getWebSocketContainer() { - return this.webSocketContainer; - } - /** - * Auto-connects to the configured {@link #setDefaultUri(URI) default URI}. + * Connect to the configured {@link #setDefaultUri(URI) default URI}. If already + * connected, the method has no impact. */ - public void start() { + public final void start() { synchronized (this.lifecycleMonitor) { if (!isRunning()) { this.taskExecutor.execute(new Runnable() { @Override public void run() { synchronized (lifecycleMonitor) { try { - logger.info("Connecting to endpoint at URI " + uri); - session = connect(); + logger.info("Connecting to WebSocket at " + uri); + openConnection(); logger.info("Successfully connected"); } catch (Throwable ex) { - logger.error("Failed to connect to endpoint at " + uri, ex); + logger.error("Failed to connect", ex); } } } @@ -146,25 +116,26 @@ public void run() { } } - protected abstract Session connect() throws DeploymentException, IOException; + protected abstract void openConnection() throws Exception; /** - * Deactivates the configured message endpoint. + * Closes the configured message WebSocket connection. */ - public void stop() { + public final void stop() { synchronized (this.lifecycleMonitor) { if (isRunning()) { try { - this.session.close(); + closeConnection(); } - catch (IOException e) { - // ignore + catch (Throwable e) { + logger.error("Failed to stop WebSocket connection", e); } } - this.session = null; } } + protected abstract void closeConnection() throws Exception; + public void stop(Runnable callback) { synchronized (this.lifecycleMonitor) { this.stop(); @@ -177,12 +148,10 @@ public void stop(Runnable callback) { */ public boolean isRunning() { synchronized (this.lifecycleMonitor) { - if ((this.session != null) && this.session.isOpen()) { - return true; - } - this.session = null; - return false; + return isConnected(); } } + protected abstract boolean isConnected(); + }
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/client/WebSocketClient.java
@@ -0,0 +1,48 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.websocket.client; + +import java.net.URI; + +import org.springframework.http.HttpHeaders; +import org.springframework.websocket.WebSocketHandler; +import org.springframework.websocket.WebSocketSession; + + +/** + * Contract for starting a WebSocket handshake request. + * + * <p>To automatically start a WebSocket connection when the application starts, see + * {@link WebSocketConnectionManager}. + * + * @author Rossen Stoyanchev + * @since 4.0 + * + * @see WebSocketConnectionManager + */ +public interface WebSocketClient { + + + WebSocketSession doHandshake(WebSocketHandler handler, String uriTemplate, Object... uriVariables) + throws WebSocketConnectFailureException; + + WebSocketSession doHandshake(WebSocketHandler handler, URI uri) + throws WebSocketConnectFailureException; + + WebSocketSession doHandshake(WebSocketHandler handler, HttpHeaders headers, URI uri) + throws WebSocketConnectFailureException; + +}
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/client/WebSocketConnectFailureException.java
@@ -0,0 +1,38 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.websocket.client; + +import org.springframework.core.NestedRuntimeException; + + +/** + * + * @author Rossen Stoyanchev + * @since 4.0 + */ +@SuppressWarnings("serial") +public class WebSocketConnectFailureException extends NestedRuntimeException { + + + public WebSocketConnectFailureException(String msg, Throwable cause) { + super(msg, cause); + } + + public WebSocketConnectFailureException(String msg) { + super(msg); + } + +}
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/client/WebSocketConnectionManager.java
@@ -0,0 +1,76 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.websocket.client; + +import java.util.List; + +import org.springframework.http.HttpHeaders; +import org.springframework.websocket.HandlerProvider; +import org.springframework.websocket.WebSocketHandler; +import org.springframework.websocket.WebSocketSession; + + +/** + * + * @author Rossen Stoyanchev + * @since 4.0 + */ +public class WebSocketConnectionManager extends AbstractWebSocketConnectionManager { + + private final WebSocketClient client; + + private final HandlerProvider<WebSocketHandler> webSocketHandlerProvider; + + private WebSocketSession webSocketSession; + + private List<String> subProtocols; + + + public WebSocketConnectionManager(WebSocketClient webSocketClient, + WebSocketHandler webSocketHandler, String uriTemplate, Object... uriVariables) { + + super(uriTemplate, uriVariables); + this.webSocketHandlerProvider = new HandlerProvider<WebSocketHandler>(webSocketHandler); + this.client = webSocketClient; + } + + public void setSubProtocols(List<String> subProtocols) { + this.subProtocols = subProtocols; + } + + public List<String> getSubProtocols() { + return this.subProtocols; + } + + @Override + protected void openConnection() throws Exception { + WebSocketHandler webSocketHandler = this.webSocketHandlerProvider.getHandler(); + HttpHeaders headers = new HttpHeaders(); + headers.setSecWebSocketProtocol(this.subProtocols); + this.webSocketSession = this.client.doHandshake(webSocketHandler, headers, getUri()); + } + + @Override + protected void closeConnection() throws Exception { + this.webSocketSession.close(); + } + + @Override + protected boolean isConnected() { + return ((this.webSocketSession != null) && (this.webSocketSession.isOpen())); + } + +}
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/client/endpoint/AnnotatedEndpointConnectionManager.java
@@ -14,15 +14,10 @@ * limitations under the License. */ -package org.springframework.websocket.client; +package org.springframework.websocket.client.endpoint; -import java.io.IOException; - -import javax.websocket.DeploymentException; import javax.websocket.Session; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; @@ -34,35 +29,33 @@ * @author Rossen Stoyanchev * @since 4.0 */ -public class AnnotatedEndpointConnectionManager extends AbstractEndpointConnectionManager +public class AnnotatedEndpointConnectionManager extends EndpointConnectionManagerSupport implements BeanFactoryAware { - private static Log logger = LogFactory.getLog(AnnotatedEndpointConnectionManager.class); - private final HandlerProvider<Object> endpointProvider; public AnnotatedEndpointConnectionManager(Class<?> endpointClass, String uriTemplate, Object... uriVariables) { super(uriTemplate, uriVariables); this.endpointProvider = new HandlerProvider<Object>(endpointClass); - this.endpointProvider.setLogger(logger); } public AnnotatedEndpointConnectionManager(Object endpointBean, String uriTemplate, Object... uriVariables) { super(uriTemplate, uriVariables); this.endpointProvider = new HandlerProvider<Object>(endpointBean); - this.endpointProvider.setLogger(logger); } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.endpointProvider.setBeanFactory(beanFactory); } + @Override - protected Session connect() throws DeploymentException, IOException { + protected void openConnection() throws Exception { Object endpoint = this.endpointProvider.getHandler(); - return getWebSocketContainer().connectToServer(endpoint, getUri()); + Session session = getWebSocketContainer().connectToServer(endpoint, getUri()); + updateSession(session); } }
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/client/endpoint/EndpointConnectionManager.java
@@ -14,23 +14,19 @@ * limitations under the License. */ -package org.springframework.websocket.client; +package org.springframework.websocket.client.endpoint; -import java.io.IOException; import java.util.Arrays; import java.util.List; import javax.websocket.ClientEndpointConfig; import javax.websocket.ClientEndpointConfig.Configurator; import javax.websocket.Decoder; -import javax.websocket.DeploymentException; import javax.websocket.Encoder; import javax.websocket.Endpoint; import javax.websocket.Extension; import javax.websocket.Session; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; @@ -43,27 +39,23 @@ * @author Rossen Stoyanchev * @since 4.0 */ -public class EndpointConnectionManager extends AbstractEndpointConnectionManager implements BeanFactoryAware { - - private static Log logger = LogFactory.getLog(EndpointConnectionManager.class); +public class EndpointConnectionManager extends EndpointConnectionManagerSupport implements BeanFactoryAware { private final ClientEndpointConfig.Builder configBuilder = ClientEndpointConfig.Builder.create(); private final HandlerProvider<Endpoint> endpointProvider; - public EndpointConnectionManager(Class<? extends Endpoint> endpointClass, String uriTemplate, Object... uriVariables) { - super(uriTemplate, uriVariables); - Assert.notNull(endpointClass, "endpointClass is required"); - this.endpointProvider = new HandlerProvider<Endpoint>(endpointClass); - this.endpointProvider.setLogger(logger); - } - public EndpointConnectionManager(Endpoint endpointBean, String uriTemplate, Object... uriVariables) { super(uriTemplate, uriVariables); Assert.notNull(endpointBean, "endpointBean is required"); this.endpointProvider = new HandlerProvider<Endpoint>(endpointBean); - this.endpointProvider.setLogger(logger); + } + + public EndpointConnectionManager(Class<? extends Endpoint> endpointClass, String uriTemplate, Object... uriVars) { + super(uriTemplate, uriVars); + Assert.notNull(endpointClass, "endpointClass is required"); + this.endpointProvider = new HandlerProvider<Endpoint>(endpointClass); } public void setSubProtocols(String... subprotocols) { @@ -92,10 +84,11 @@ public void setBeanFactory(BeanFactory beanFactory) throws BeansException { } @Override - protected Session connect() throws DeploymentException, IOException { - Endpoint typedEndpoint = this.endpointProvider.getHandler(); + protected void openConnection() throws Exception { + Endpoint endpoint = this.endpointProvider.getHandler(); ClientEndpointConfig endpointConfig = this.configBuilder.build(); - return getWebSocketContainer().connectToServer(typedEndpoint, endpointConfig, getUri()); + Session session = getWebSocketContainer().connectToServer(endpoint, endpointConfig, getUri()); + updateSession(session); } }
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/client/endpoint/EndpointConnectionManagerSupport.java
@@ -0,0 +1,71 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.websocket.client.endpoint; + +import javax.websocket.ContainerProvider; +import javax.websocket.Session; +import javax.websocket.WebSocketContainer; + +import org.springframework.websocket.client.AbstractWebSocketConnectionManager; + + +/** + * + * @author Rossen Stoyanchev + * @since 4.0 + */ +public abstract class EndpointConnectionManagerSupport extends AbstractWebSocketConnectionManager { + + private WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer(); + + private Session session; + + + public EndpointConnectionManagerSupport(String uriTemplate, Object... uriVariables) { + super(uriTemplate, uriVariables); + } + + public void setWebSocketContainer(WebSocketContainer webSocketContainer) { + this.webSocketContainer = webSocketContainer; + } + + public WebSocketContainer getWebSocketContainer() { + return this.webSocketContainer; + } + + protected void updateSession(Session session) { + this.session = session; + } + + @Override + protected void closeConnection() throws Exception { + try { + if (isConnected()) { + this.session.close(); + } + } + finally { + this.session = null; + } + } + + @Override + protected boolean isConnected() { + return ((this.session != null) && this.session.isOpen()); + } + +}
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/client/endpoint/StandardWebSocketClient.java
@@ -0,0 +1,105 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.websocket.client.endpoint; + +import java.net.URI; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.websocket.ClientEndpointConfig; +import javax.websocket.ClientEndpointConfig.Configurator; +import javax.websocket.ContainerProvider; +import javax.websocket.Endpoint; +import javax.websocket.Session; +import javax.websocket.WebSocketContainer; + +import org.springframework.http.HttpHeaders; +import org.springframework.web.util.UriComponentsBuilder; +import org.springframework.websocket.WebSocketHandler; +import org.springframework.websocket.WebSocketSession; +import org.springframework.websocket.client.WebSocketClient; +import org.springframework.websocket.client.WebSocketConnectFailureException; +import org.springframework.websocket.endpoint.StandardWebSocketSession; +import org.springframework.websocket.endpoint.WebSocketHandlerEndpoint; + + +/** + * + * @author Rossen Stoyanchev + * @since 4.0 + */ +public class StandardWebSocketClient implements WebSocketClient { + + private static final Set<String> EXCLUDED_HEADERS = new HashSet<String>( + Arrays.asList("Sec-WebSocket-Accept", "Sec-WebSocket-Extensions", "Sec-WebSocket-Key", + "Sec-WebSocket-Protocol", "Sec-WebSocket-Version")); + + private WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer(); + + + public void setWebSocketContainer(WebSocketContainer container) { + this.webSocketContainer = container; + } + + public WebSocketSession doHandshake(WebSocketHandler handler, String uriTemplate, + Object... uriVariables) throws WebSocketConnectFailureException { + + URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(uriVariables).encode().toUri(); + return doHandshake(handler, uri); + } + + @Override + public WebSocketSession doHandshake(WebSocketHandler handler, URI uri) throws WebSocketConnectFailureException { + return doHandshake(handler, null, uri); + } + + @Override + public WebSocketSession doHandshake(WebSocketHandler handler, final HttpHeaders httpHeaders, URI uri) + throws WebSocketConnectFailureException { + + Endpoint endpoint = new WebSocketHandlerEndpoint(handler); + + ClientEndpointConfig.Builder configBuidler = ClientEndpointConfig.Builder.create(); + if (httpHeaders != null) { + List<String> protocols = httpHeaders.getSecWebSocketProtocol(); + if (!protocols.isEmpty()) { + configBuidler.preferredSubprotocols(protocols); + } + configBuidler.configurator(new Configurator() { + @Override + public void beforeRequest(Map<String, List<String>> headers) { + for (String headerName : httpHeaders.keySet()) { + if (!EXCLUDED_HEADERS.contains(headerName)) { + headers.put(headerName, httpHeaders.get(headerName)); + } + } + } + }); + } + + try { + Session session = this.webSocketContainer.connectToServer(endpoint, configBuidler.build(), uri); + return new StandardWebSocketSession(session); + } + catch (Exception e) { + throw new WebSocketConnectFailureException("Failed to connect to " + uri, e); + } + } + +}
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/client/endpoint/WebSocketContainerFactoryBean.java
@@ -0,0 +1,84 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.websocket.client.endpoint; + +import javax.websocket.ContainerProvider; +import javax.websocket.WebSocketContainer; + +import org.springframework.beans.factory.FactoryBean; + + +/** + * A FactoryBean for creating and configuring a {@link javax.websocket.WebSocketContainer} + * through Spring XML configuration. In Java configuration, ignore this class and use + * {@code ContainerProvider.getWebSocketContainer()} instead. + * + * @author Rossen Stoyanchev + * @since 4.0 + */ +public class WebSocketContainerFactoryBean implements FactoryBean<WebSocketContainer> { + + private final WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer(); + + + public void setAsyncSendTimeout(long timeoutInMillis) { + this.webSocketContainer.setAsyncSendTimeout(timeoutInMillis); + } + + public long getAsyncSendTimeout() { + return this.webSocketContainer.getDefaultAsyncSendTimeout(); + } + + public void setMaxSessionIdleTimeout(long timeoutInMillis) { + this.webSocketContainer.setDefaultMaxSessionIdleTimeout(timeoutInMillis); + } + + public long getMaxSessionIdleTimeout() { + return this.webSocketContainer.getDefaultMaxSessionIdleTimeout(); + } + + public void setMaxTextMessageBufferSize(int bufferSize) { + this.webSocketContainer.setDefaultMaxTextMessageBufferSize(bufferSize); + } + + public int getMaxTextMessageBufferSize() { + return this.webSocketContainer.getDefaultMaxTextMessageBufferSize(); + } + + public void setMaxBinaryMessageBufferSize(int bufferSize) { + this.webSocketContainer.setDefaultMaxBinaryMessageBufferSize(bufferSize); + } + + public int getMaxBinaryMessageBufferSize() { + return this.webSocketContainer.getDefaultMaxBinaryMessageBufferSize(); + } + + @Override + public WebSocketContainer getObject() throws Exception { + return this.webSocketContainer; + } + + @Override + public Class<?> getObjectType() { + return WebSocketContainer.class; + } + + @Override + public boolean isSingleton() { + return true; + } + +}
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/client/endpoint/package-info.java
@@ -0,0 +1,8 @@ +/** + * Client-side classes for use with standard Java WebSocket endpoints including + * {@link org.springframework.websocket.client.endpoint.EndpointConnectionManager} and + * {@link org.springframework.websocket.client.endpoint.AnnotatedEndpointConnectionManager} + * for connecting to server endpoints using type-based or annotated endpoints respectively. + */ +package org.springframework.websocket.client.endpoint; +
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/client/package-info.java
@@ -1,6 +1,5 @@ - /** - * Client-side support for WebSocket applications. + * Server-side abstractions for WebSocket applications. * */ package org.springframework.websocket.client;
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/endpoint/WebSocketHandlerEndpoint.java
@@ -54,8 +54,7 @@ public WebSocketHandlerEndpoint(WebSocketHandler webSocketHandler) { @Override public void onOpen(javax.websocket.Session session, EndpointConfig config) { if (logger.isDebugEnabled()) { - logger.debug("Client connected, WebSocket session id=" + session.getId() - + ", path=" + session.getRequestURI().getPath()); + logger.debug("Client connected, WebSocket session id=" + session.getId() + ", uri=" + session.getRequestURI()); } try { WebSocketSession webSocketSession = new StandardWebSocketSession(session);
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/server/endpoint/EndpointExporter.java
@@ -15,6 +15,10 @@ */ package org.springframework.websocket.server.endpoint; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import java.util.Map; import javax.websocket.DeploymentException; @@ -25,13 +29,13 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; import org.springframework.util.Assert; -import org.springframework.util.ObjectUtils; +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; /** * BeanPostProcessor that detects beans of type @@ -43,114 +47,79 @@ * @author Rossen Stoyanchev * @since 4.0 */ -public abstract class EndpointExporter implements InitializingBean, BeanPostProcessor, BeanFactoryAware { +public class EndpointExporter implements InitializingBean, BeanPostProcessor, ApplicationContextAware { - private static Log logger = LogFactory.getLog(EndpointExporter.class); + private static final boolean isServletApiPresent = + ClassUtils.isPresent("javax.servlet.ServletContext", EndpointExporter.class.getClassLoader()); - private Class<?>[] annotatedEndpointClasses; + private static Log logger = LogFactory.getLog(EndpointExporter.class); - private Long maxSessionIdleTimeout; + private final List<Class<?>> annotatedEndpointClasses = new ArrayList<Class<?>>(); - private Integer maxTextMessageBufferSize; + private final List<Class<?>> annotatedEndpointBeanTypes = new ArrayList<Class<?>>(); - private Integer maxBinaryMessageBufferSize; + private ApplicationContext applicationContext; + private ServerContainer serverContainer; /** * TODO * @param annotatedEndpointClasses */ public void setAnnotatedEndpointClasses(Class<?>... annotatedEndpointClasses) { - this.annotatedEndpointClasses = annotatedEndpointClasses; + this.annotatedEndpointClasses.clear(); + this.annotatedEndpointClasses.addAll(Arrays.asList(annotatedEndpointClasses)); } - /** - * If this property set it is in turn used to configure - * {@link ServerContainer#setDefaultMaxSessionIdleTimeout(long)}. - */ - public void setMaxSessionIdleTimeout(long maxSessionIdleTimeout) { - this.maxSessionIdleTimeout = maxSessionIdleTimeout; - } + @Override + public void setApplicationContext(ApplicationContext applicationContext) { - public Long getMaxSessionIdleTimeout() { - return this.maxSessionIdleTimeout; - } + this.applicationContext = applicationContext; - /** - * If this property set it is in turn used to configure - * {@link ServerContainer#setDefaultMaxTextMessageBufferSize(int)} - */ - public void setMaxTextMessageBufferSize(int maxTextMessageBufferSize) { - this.maxTextMessageBufferSize = maxTextMessageBufferSize; - } - - public Integer getMaxTextMessageBufferSize() { - return this.maxTextMessageBufferSize; - } + this.serverContainer = getServerContainer(); - /** - * If this property set it is in turn used to configure - * {@link ServerContainer#setDefaultMaxBinaryMessageBufferSize(int)}. - */ - public void setMaxBinaryMessageBufferSize(int maxBinaryMessageBufferSize) { - this.maxBinaryMessageBufferSize = maxBinaryMessageBufferSize; + Map<String, Object> beans = applicationContext.getBeansWithAnnotation(ServerEndpoint.class); + for (String beanName : beans.keySet()) { + Class<?> beanType = applicationContext.getType(beanName); + if (logger.isInfoEnabled()) { + logger.info("Detected @ServerEndpoint bean '" + beanName + "', registering it as an endpoint by type"); + } + this.annotatedEndpointBeanTypes.add(beanType); + } } - public Integer getMaxBinaryMessageBufferSize() { - return this.maxBinaryMessageBufferSize; - } + protected ServerContainer getServerContainer() { + if (isServletApiPresent) { + try { + Method getter = ReflectionUtils.findMethod(this.applicationContext.getClass(), "getServletContext"); + Object servletContext = getter.invoke(this.applicationContext); - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - if (beanFactory instanceof ListableBeanFactory) { - ListableBeanFactory lbf = (ListableBeanFactory) beanFactory; - Map<String, Object> annotatedEndpoints = lbf.getBeansWithAnnotation(ServerEndpoint.class); - for (String beanName : annotatedEndpoints.keySet()) { - Class<?> beanType = lbf.getType(beanName); - try { - if (logger.isInfoEnabled()) { - logger.info("Detected @ServerEndpoint bean '" + beanName + "', registering it as an endpoint by type"); - } - getServerContainer().addEndpoint(beanType); - } - catch (DeploymentException e) { - throw new IllegalStateException("Failed to register @ServerEndpoint bean type " + beanName, e); - } + Method attrMethod = ReflectionUtils.findMethod(servletContext.getClass(), "getAttribute", String.class); + return (ServerContainer) attrMethod.invoke(servletContext, "javax.websocket.server.ServerContainer"); + } + catch (Exception ex) { + throw new IllegalStateException( + "Failed to get javax.websocket.server.ServerContainer via ServletContext attribute", ex); } } + return null; } - /** - * Return the {@link ServerContainer} instance, a process which is undefined outside - * of standalone containers (section 6.4 of the spec). - */ - protected abstract ServerContainer getServerContainer(); - @Override public void afterPropertiesSet() throws Exception { - ServerContainer serverContainer = getServerContainer(); Assert.notNull(serverContainer, "javax.websocket.server.ServerContainer not available"); - if (this.maxSessionIdleTimeout != null) { - serverContainer.setDefaultMaxSessionIdleTimeout(this.maxSessionIdleTimeout); - } - if (this.maxTextMessageBufferSize != null) { - serverContainer.setDefaultMaxTextMessageBufferSize(this.maxTextMessageBufferSize); - } - if (this.maxBinaryMessageBufferSize != null) { - serverContainer.setDefaultMaxBinaryMessageBufferSize(this.maxBinaryMessageBufferSize); - } + List<Class<?>> allClasses = new ArrayList<Class<?>>(this.annotatedEndpointClasses); + allClasses.addAll(this.annotatedEndpointBeanTypes); - if (!ObjectUtils.isEmpty(this.annotatedEndpointClasses)) { - for (Class<?> clazz : this.annotatedEndpointClasses) { - try { - logger.info("Registering @ServerEndpoint type " + clazz); - serverContainer.addEndpoint(clazz); - } - catch (DeploymentException e) { - throw new IllegalStateException("Failed to register @ServerEndpoint type " + clazz, e); - } + for (Class<?> clazz : allClasses) { + try { + logger.info("Registering @ServerEndpoint type " + clazz); + this.serverContainer.addEndpoint(clazz); + } + catch (DeploymentException e) { + throw new IllegalStateException("Failed to register @ServerEndpoint type " + clazz, e); } } }
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/server/endpoint/ServletEndpointExporter.java
@@ -1,60 +0,0 @@ -/* - * Copyright 2002-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.websocket.server.endpoint; - -import javax.servlet.ServletContext; -import javax.websocket.server.ServerContainer; -import javax.websocket.server.ServerContainerProvider; - -import org.springframework.util.Assert; -import org.springframework.web.context.ServletContextAware; - - -/** - * A sub-class of {@link EndpointExporter} for use with a Servlet container runtime. - * - * @author Rossen Stoyanchev - * @since 4.0 - */ -public class ServletEndpointExporter extends EndpointExporter implements ServletContextAware { - - private static final String SERVER_CONTAINER_ATTR_NAME = "javax.websocket.server.ServerContainer"; - - private ServletContext servletContext; - - - @Override - public void setServletContext(ServletContext servletContext) { - this.servletContext = servletContext; - } - - public ServletContext getServletContext() { - return this.servletContext; - } - - @Override - protected ServerContainer getServerContainer() { - Assert.notNull(this.servletContext, "A ServletContext is needed to access the WebSocket ServerContainer"); - ServerContainer container = (ServerContainer) this.servletContext.getAttribute(SERVER_CONTAINER_ATTR_NAME); - if (container == null) { - // Remove when Tomcat has caught up to http://java.net/jira/browse/WEBSOCKET_SPEC-165 - return ServerContainerProvider.getServerContainer(); - } - return container; - } - -}
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/server/endpoint/ServletServerContainerFactoryBean.java
@@ -0,0 +1,133 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.websocket.server.endpoint; + +import javax.servlet.ServletContext; +import javax.websocket.WebSocketContainer; +import javax.websocket.server.ServerContainer; + +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.sockjs.server.SockJsService; +import org.springframework.util.Assert; +import org.springframework.web.context.ServletContextAware; +import org.springframework.websocket.server.DefaultHandshakeHandler; + + +/** + * A FactoryBean for {@link javax.websocket.server.ServerContainer}. Since + * there is only one {@code ServerContainer} instance accessible under a well-known + * {@code javax.servlet.ServletContext} attribute, simply declaring this FactoryBean and + * using its setters allows configuring the {@code ServerContainer} through Spring + * configuration. This is useful even if the ServerContainer is not injected into any + * other bean. For example, an application can configure a {@link DefaultHandshakeHandler} + * , a {@link SockJsService}, or {@link EndpointExporter}, and separately declare this + * FactoryBean in order to customize the properties of the (one and only) + * {@code ServerContainer} instance. + * + * @author Rossen Stoyanchev + * @since 4.0 + */ +public class ServletServerContainerFactoryBean + implements FactoryBean<WebSocketContainer>, InitializingBean, ServletContextAware { + + private static final String SERVER_CONTAINER_ATTR_NAME = "javax.websocket.server.ServerContainer"; + + private Long asyncSendTimeout; + + private Long maxSessionIdleTimeout; + + private Integer maxTextMessageBufferSize; + + private Integer maxBinaryMessageBufferSize; + + + private ServerContainer serverContainer; + + + public void setAsyncSendTimeout(long timeoutInMillis) { + this.asyncSendTimeout = timeoutInMillis; + } + + public long getAsyncSendTimeout() { + return this.asyncSendTimeout; + } + + public void setMaxSessionIdleTimeout(long timeoutInMillis) { + this.maxSessionIdleTimeout = timeoutInMillis; + } + + public Long getMaxSessionIdleTimeout() { + return this.maxSessionIdleTimeout; + } + + public void setMaxTextMessageBufferSize(int bufferSize) { + this.maxTextMessageBufferSize = bufferSize; + } + + public Integer getMaxTextMessageBufferSize() { + return this.maxTextMessageBufferSize; + } + + public void setMaxBinaryMessageBufferSize(int bufferSize) { + this.maxBinaryMessageBufferSize = bufferSize; + } + + public Integer getMaxBinaryMessageBufferSize() { + return this.maxBinaryMessageBufferSize; + } + + @Override + public void setServletContext(ServletContext servletContext) { + this.serverContainer = (ServerContainer) servletContext.getAttribute(SERVER_CONTAINER_ATTR_NAME); + } + + @Override + public ServerContainer getObject() { + return this.serverContainer; + } + + @Override + public Class<?> getObjectType() { + return ServerContainer.class; + } + + @Override + public boolean isSingleton() { + return false; + } + + @Override + public void afterPropertiesSet() throws Exception { + + Assert.notNull(this.serverContainer, + "A ServletContext is required to access the javax.websocket.server.ServerContainer instance"); + + if (this.asyncSendTimeout != null) { + this.serverContainer.setAsyncSendTimeout(this.asyncSendTimeout); + } + if (this.maxSessionIdleTimeout != null) { + this.serverContainer.setDefaultMaxSessionIdleTimeout(this.maxSessionIdleTimeout); + } + if (this.maxTextMessageBufferSize != null) { + this.serverContainer.setDefaultMaxTextMessageBufferSize(this.maxTextMessageBufferSize); + } + if (this.maxBinaryMessageBufferSize != null) { + this.serverContainer.setDefaultMaxBinaryMessageBufferSize(this.maxBinaryMessageBufferSize); + } + } + +}
true
Other
spring-projects
spring-framework
2046629945d288944b13401958f5d27e04bbe835.json
Add WebSocketClient and WebSocketConnectionManager This change adds a WebSocketClient abstraction and enables the use of WebSocketHandler on the client side.
spring-websocket/src/main/java/org/springframework/websocket/server/support/AbstractEndpointContainerFactoryBean.java
@@ -0,0 +1,88 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.websocket.server.support; + +import javax.websocket.WebSocketContainer; + +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; + + +/** +* +* @author Rossen Stoyanchev +* @since 4.0 +*/ +public abstract class AbstractEndpointContainerFactoryBean implements FactoryBean<WebSocketContainer>, InitializingBean { + + private WebSocketContainer container; + + + public void setAsyncSendTimeout(long timeoutInMillis) { + this.container.setAsyncSendTimeout(timeoutInMillis); + } + + public long getAsyncSendTimeout() { + return this.container.getDefaultAsyncSendTimeout(); + } + + public void setMaxSessionIdleTimeout(long timeoutInMillis) { + this.container.setDefaultMaxSessionIdleTimeout(timeoutInMillis); + } + + public long getMaxSessionIdleTimeout() { + return this.container.getDefaultMaxSessionIdleTimeout(); + } + + public void setMaxTextMessageBufferSize(int bufferSize) { + this.container.setDefaultMaxTextMessageBufferSize(bufferSize); + } + + public int getMaxTextMessageBufferSize() { + return this.container.getDefaultMaxTextMessageBufferSize(); + } + + public void setMaxBinaryMessageBufferSize(int bufferSize) { + this.container.setDefaultMaxBinaryMessageBufferSize(bufferSize); + } + + public int getMaxBinaryMessageBufferSize() { + return this.container.getDefaultMaxBinaryMessageBufferSize(); + } + + @Override + public void afterPropertiesSet() throws Exception { + this.container = getContainer(); + } + + protected abstract WebSocketContainer getContainer(); + + @Override + public WebSocketContainer getObject() throws Exception { + return this.container; + } + + @Override + public Class<?> getObjectType() { + return WebSocketContainer.class; + } + + @Override + public boolean isSingleton() { + return true; + } + +}
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/sockjs/SockJsHandler.java
@@ -16,21 +16,36 @@ package org.springframework.sockjs; +import org.springframework.websocket.CloseStatus; + /** + * A handler for SockJS messages. * * @author Rossen Stoyanchev * @since 4.0 */ public interface SockJsHandler { - void newSession(SockJsSession session) throws Exception; - - void handleMessage(SockJsSession session, String message) throws Exception; - - void handleException(SockJsSession session, Throwable exception); - - void sessionClosed(SockJsSession session); + /** + * A new connection was opened and is ready for use. + */ + void afterConnectionEstablished(SockJsSession session) throws Exception; + + /** + * Handle an incoming message. + */ + void handleMessage(String message, SockJsSession session) throws Exception; + + /** + * TODO + */ + void handleError(Throwable exception, SockJsSession session); + + /** + * A connection has been closed. + */ + void afterConnectionClosed(CloseStatus status, SockJsSession session); }
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/sockjs/SockJsHandlerAdapter.java
@@ -16,6 +16,8 @@ package org.springframework.sockjs; +import org.springframework.websocket.CloseStatus; + /** * @@ -25,19 +27,19 @@ public class SockJsHandlerAdapter implements SockJsHandler { @Override - public void newSession(SockJsSession session) throws Exception { + public void afterConnectionEstablished(SockJsSession session) throws Exception { } @Override - public void handleMessage(SockJsSession session, String message) throws Exception { + public void handleMessage(String message, SockJsSession session) throws Exception { } @Override - public void handleException(SockJsSession session, Throwable exception) { + public void handleError(Throwable exception, SockJsSession session) { } @Override - public void sessionClosed(SockJsSession session) { + public void afterConnectionClosed(CloseStatus status, SockJsSession session) { } }
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/sockjs/SockJsSession.java
@@ -18,19 +18,45 @@ import java.io.IOException; +import org.springframework.websocket.CloseStatus; + /** + * Allows sending SockJS messages as well as closing the underlying connection. * * @author Rossen Stoyanchev * @since 4.0 */ public interface SockJsSession { + /** + * Return a unique SockJS session identifier. + */ String getId(); + /** + * Return whether the connection is still open. + */ + boolean isOpen(); + + /** + * Send a message. + */ void sendMessage(String text) throws IOException; - void close(); + /** + * Close the underlying connection with status 1000, i.e. equivalent to: + * <pre> + * session.close(CloseStatus.NORMAL); + * </pre> + */ + void close() throws IOException; + + /** + * Close the underlying connection with the given close status. + */ + void close(CloseStatus status) throws IOException; + }
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/sockjs/SockJsSessionFactory.java
@@ -18,6 +18,7 @@ /** + * A factory for creating a SockJS session. * * @author Rossen Stoyanchev * @since 4.0
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/sockjs/SockJsSessionSupport.java
@@ -16,9 +16,12 @@ package org.springframework.sockjs; +import java.io.IOException; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.util.Assert; +import org.springframework.websocket.CloseStatus; /** @@ -99,33 +102,78 @@ protected void updateLastActiveTime() { this.timeLastActive = System.currentTimeMillis(); } - public void connectionInitialized() throws Exception { + public void delegateConnectionEstablished() throws Exception { this.state = State.OPEN; - this.sockJsHandler.newSession(this); + this.sockJsHandler.afterConnectionEstablished(this); } - public void delegateMessages(String... messages) throws Exception { + public void delegateMessages(String[] messages) throws Exception { for (String message : messages) { - this.sockJsHandler.handleMessage(this, message); + this.sockJsHandler.handleMessage(message, this); } } - public void delegateException(Throwable ex) { - this.sockJsHandler.handleException(this, ex); + public void delegateError(Throwable ex) { + this.sockJsHandler.handleError(ex, this); + } + + /** + * Invoked in reaction to the underlying connection being closed by the remote side + * (or the WebSocket container) in order to perform cleanup and notify the + * {@link SockJsHandler}. This is in contrast to {@link #close()} that pro-actively + * closes the connection. + */ + public final void delegateConnectionClosed(CloseStatus status) { + if (!isClosed()) { + if (logger.isDebugEnabled()) { + logger.debug(this + " was closed, " + status); + } + try { + connectionClosedInternal(status); + } + finally { + this.state = State.CLOSED; + this.sockJsHandler.afterConnectionClosed(status, this); + } + } } - public void connectionClosed() { - this.state = State.CLOSED; - this.sockJsHandler.sessionClosed(this); + protected void connectionClosedInternal(CloseStatus status) { } - public void close() { - this.state = State.CLOSED; - this.sockJsHandler.sessionClosed(this); + /** + * {@inheritDoc} + * <p>Performs cleanup and notifies the {@link SockJsHandler}. + */ + public final void close() throws IOException { + close(CloseStatus.NORMAL); } + /** + * {@inheritDoc} + * <p>Performs cleanup and notifies the {@link SockJsHandler}. + */ + public final void close(CloseStatus status) throws IOException { + if (!isClosed()) { + if (logger.isDebugEnabled()) { + logger.debug("Closing " + this + ", " + status); + } + try { + closeInternal(status); + } + finally { + this.state = State.CLOSED; + this.sockJsHandler.afterConnectionClosed(status, this); + } + } + } + + protected abstract void closeInternal(CloseStatus status) throws IOException; + + + @Override public String toString() { - return getClass().getSimpleName() + " [id=" + sessionId + "]"; + return "SockJS session id=" + this.sessionId; }
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractServerSockJsSession.java
@@ -26,6 +26,7 @@ import org.springframework.sockjs.SockJsSession; import org.springframework.sockjs.SockJsSessionSupport; import org.springframework.util.Assert; +import org.springframework.websocket.CloseStatus; /** @@ -42,9 +43,9 @@ public abstract class AbstractServerSockJsSession extends SockJsSessionSupport { private ScheduledFuture<?> heartbeatTask; - public AbstractServerSockJsSession(String sessionId, SockJsConfiguration sockJsConfig, SockJsHandler sockJsHandler) { + public AbstractServerSockJsSession(String sessionId, SockJsConfiguration config, SockJsHandler sockJsHandler) { super(sessionId, sockJsHandler); - this.sockJsConfig = sockJsConfig; + this.sockJsConfig = config; } protected SockJsConfiguration getSockJsConfig() { @@ -60,36 +61,34 @@ public final synchronized void sendMessage(String message) throws IOException { @Override - public void connectionClosed() { - logger.debug("Session closed"); - super.close(); + public void connectionClosedInternal(CloseStatus status) { + updateLastActiveTime(); cancelHeartbeat(); } @Override - public final synchronized void close() { - if (!isClosed()) { - logger.debug("Closing session"); - if (isActive()) { - // deliver messages "in flight" before sending close frame - try { - writeFrame(SockJsFrame.closeFrameGoAway()); - } - catch (Exception e) { - // ignore - } + public final synchronized void closeInternal(CloseStatus status) throws IOException { + if (isActive()) { + // TODO: deliver messages "in flight" before sending close frame + try { + // bypass writeFrame + writeFrameInternal(SockJsFrame.closeFrame(status.getCode(), status.getReason())); + } + catch (Throwable ex) { + logger.warn("Failed to send SockJS close frame: " + ex.getMessage()); } - super.close(); - cancelHeartbeat(); - closeInternal(); } + updateLastActiveTime(); + cancelHeartbeat(); + disconnect(status); } - protected abstract void closeInternal(); + // TODO: close status/reason + protected abstract void disconnect(CloseStatus status) throws IOException; /** * For internal use within a TransportHandler and the (TransportHandler-specific) - * session sub-class. The frame is written only if the connection is active. + * session sub-class. */ protected void writeFrame(SockJsFrame frame) throws IOException { if (logger.isTraceEnabled()) { @@ -103,29 +102,20 @@ protected void writeFrame(SockJsFrame frame) throws IOException { logger.warn("Client went away. Terminating connection"); } else { - logger.warn("Failed to send message. Terminating connection: " + ex.getMessage()); + logger.warn("Terminating connection due to failure to send message: " + ex.getMessage()); } - deactivate(); close(); throw ex; } - catch (Throwable t) { - logger.warn("Failed to send message. Terminating connection: " + t.getMessage()); - deactivate(); + catch (Throwable ex) { + logger.warn("Terminating connection due to failure to send message: " + ex.getMessage()); close(); - throw new NestedSockJsRuntimeException("Failed to write frame " + frame, t); + throw new NestedSockJsRuntimeException("Failed to write frame " + frame, ex); } } protected abstract void writeFrameInternal(SockJsFrame frame) throws IOException; - /** - * Some {@link TransportHandler} types cannot detect if a client connection is closed - * or lost and will eventually fail to send messages. When that happens, we need a way - * to disconnect the underlying connection before calling {@link #close()}. - */ - protected abstract void deactivate(); - public synchronized void sendHeartbeat() throws IOException { if (isActive()) { writeFrame(SockJsFrame.heartbeatFrame());
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractSockJsService.java
@@ -56,7 +56,7 @@ private static final int ONE_YEAR = 365 * 24 * 60 * 60; - private String name = getClass().getSimpleName() + "@" + Integer.toHexString(hashCode()); + private String name = getClass().getSimpleName() + "@" + ObjectUtils.getIdentityHexString(this); private String clientLibraryUrl = "https://d1fxtkz8shb9d2.cloudfront.net/sockjs-0.3.4.min.js";
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractHttpSendingTransportHandler.java
@@ -92,7 +92,7 @@ protected void handleNewSession(ServerHttpRequest request, ServerHttpResponse re logger.debug("Opening " + getTransportType() + " connection"); session.setFrameFormat(getFrameFormat(request)); session.writeFrame(response, SockJsFrame.openFrame()); - session.connectionInitialized(); + session.delegateConnectionEstablished(); } protected abstract MediaType getContentType();
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractHttpServerSockJsSession.java
@@ -29,6 +29,7 @@ import org.springframework.sockjs.server.SockJsFrame.FrameFormat; import org.springframework.sockjs.server.TransportHandler; import org.springframework.util.Assert; +import org.springframework.websocket.CloseStatus; /** * An abstract base class for use with HTTP-based transports. @@ -109,14 +110,22 @@ private void tryFlushCache() throws IOException { protected abstract void flushCache() throws IOException; @Override - public void connectionClosed() { - super.connectionClosed(); + protected void disconnect(CloseStatus status) { resetRequest(); } - @Override - protected void closeInternal() { - resetRequest(); + protected synchronized void resetRequest() { + updateLastActiveTime(); + if (isActive()) { + try { + this.asyncRequest.completeAsync(); + } + catch (Throwable ex) { + logger.warn("Failed to complete async request: " + ex.getMessage()); + } + } + this.asyncRequest = null; + this.response = null; } protected synchronized void writeFrameInternal(SockJsFrame frame) throws IOException { @@ -138,20 +147,4 @@ public void writeFrame(ServerHttpResponse response, SockJsFrame frame) throws IO response.getBody().write(frame.getContentBytes()); } - @Override - protected void deactivate() { - this.asyncRequest = null; - this.response = null; - updateLastActiveTime(); - } - - protected synchronized void resetRequest() { - if (isActive()) { - this.asyncRequest.completeAsync(); - } - this.asyncRequest = null; - this.response = null; - updateLastActiveTime(); - } - }
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/SockJsWebSocketHandler.java
@@ -17,7 +17,6 @@ package org.springframework.sockjs.server.transport; import java.io.IOException; -import java.io.InputStream; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -30,6 +29,7 @@ import org.springframework.sockjs.server.SockJsFrame; import org.springframework.util.Assert; import org.springframework.util.StringUtils; +import org.springframework.websocket.CloseStatus; import org.springframework.websocket.WebSocketHandler; import org.springframework.websocket.WebSocketSession; @@ -78,21 +78,15 @@ protected SockJsSessionSupport getSockJsSession(WebSocketSession wsSession) { } @Override - public void newSession(WebSocketSession wsSession) throws Exception { - if (logger.isDebugEnabled()) { - logger.debug("New session: " + wsSession); - } + public void afterConnectionEstablished(WebSocketSession wsSession) throws Exception { SockJsSessionSupport session = new WebSocketServerSockJsSession(wsSession, getSockJsConfig()); this.sessions.put(wsSession, session); } @Override - public void handleTextMessage(WebSocketSession wsSession, String message) throws Exception { - if (logger.isTraceEnabled()) { - logger.trace("Received payload " + message + " for " + wsSession); - } + public void handleTextMessage(String message, WebSocketSession wsSession) throws Exception { if (StringUtils.isEmpty(message)) { - logger.trace("Ignoring empty payload"); + logger.trace("Ignoring empty message"); return; } try { @@ -107,41 +101,50 @@ public void handleTextMessage(WebSocketSession wsSession, String message) throws } @Override - public void handleBinaryMessage(WebSocketSession session, InputStream message) throws Exception { - // should not happen - throw new UnsupportedOperationException(); + public void handleBinaryMessage(byte[] message, WebSocketSession session) throws Exception { + logger.warn("Unexpected binary message for " + session); + session.close(CloseStatus.NOT_ACCEPTABLE); } @Override - public void handleException(WebSocketSession webSocketSession, Throwable exception) { - SockJsSessionSupport session = getSockJsSession(webSocketSession); - session.delegateException(exception); + public void afterConnectionClosed(CloseStatus status, WebSocketSession wsSession) throws Exception { + SockJsSessionSupport session = this.sessions.remove(wsSession); + session.delegateConnectionClosed(status); } @Override - public void sessionClosed(WebSocketSession webSocketSession, int statusCode, String reason) throws Exception { - logger.debug("WebSocket session closed " + webSocketSession); - SockJsSessionSupport session = this.sessions.remove(webSocketSession); - session.connectionClosed(); + public void handleError(Throwable exception, WebSocketSession webSocketSession) { + SockJsSessionSupport session = getSockJsSession(webSocketSession); + session.delegateError(exception); + } + + private static String getSockJsSessionId(WebSocketSession wsSession) { + Assert.notNull(wsSession, "wsSession is required"); + String path = wsSession.getURI().getPath(); + String[] segments = StringUtils.tokenizeToStringArray(path, "/"); + Assert.isTrue(segments.length > 3, "SockJS request should have at least 3 patgh segments: " + path); + return segments[segments.length-2]; } private class WebSocketServerSockJsSession extends AbstractServerSockJsSession { - private WebSocketSession webSocketSession; + private final WebSocketSession wsSession; + + public WebSocketServerSockJsSession(WebSocketSession wsSession, SockJsConfiguration sockJsConfig) + throws Exception { - public WebSocketServerSockJsSession(WebSocketSession wsSession, SockJsConfiguration sockJsConfig) throws Exception { - super(String.valueOf(wsSession.hashCode()), sockJsConfig, getSockJsHandler()); - this.webSocketSession = wsSession; - this.webSocketSession.sendText(SockJsFrame.openFrame().getContent()); + super(getSockJsSessionId(wsSession), sockJsConfig, getSockJsHandler()); + this.wsSession = wsSession; + this.wsSession.sendTextMessage(SockJsFrame.openFrame().getContent()); scheduleHeartbeat(); - connectionInitialized(); + delegateConnectionEstablished(); } @Override public boolean isActive() { - return ((this.webSocketSession != null) && this.webSocketSession.isOpen()); + return this.wsSession.isOpen(); } @Override @@ -156,27 +159,12 @@ protected void writeFrameInternal(SockJsFrame frame) throws IOException { if (logger.isTraceEnabled()) { logger.trace("Write " + frame); } - this.webSocketSession.sendText(frame.getContent()); + this.wsSession.sendTextMessage(frame.getContent()); } @Override - public void connectionClosed() { - super.connectionClosed(); - this.webSocketSession = null; - } - - @Override - public void closeInternal() { - deactivate(); - updateLastActiveTime(); - } - - @Override - protected void deactivate() { - if (this.webSocketSession != null) { - this.webSocketSession.close(); - this.webSocketSession = null; - } + protected void disconnect(CloseStatus status) throws IOException { + this.wsSession.close(status); } }
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/WebSocketSockJsHandlerAdapter.java
@@ -17,7 +17,6 @@ package org.springframework.sockjs.server.transport; import java.io.IOException; -import java.io.InputStream; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -27,14 +26,15 @@ import org.springframework.sockjs.SockJsSessionSupport; import org.springframework.sockjs.server.SockJsConfiguration; import org.springframework.util.Assert; +import org.springframework.websocket.CloseStatus; import org.springframework.websocket.WebSocketHandler; import org.springframework.websocket.WebSocketSession; /** - * A {@link WebSocketHandler} that merely delegates to a {@link SockJsHandler} without any - * SockJS message framing. For use with raw WebSocket communication at SockJS path - * "/websocket". + * A plain {@link WebSocketHandler} to {@link SockJsHandler} adapter that merely delegates + * without any additional SockJS message framing. Used for raw WebSocket communication at + * SockJS path "/websocket". * * @author Rossen Stoyanchev * @since 4.0 @@ -71,79 +71,61 @@ protected SockJsSessionSupport getSockJsSession(WebSocketSession wsSession) { } @Override - public void newSession(WebSocketSession wsSession) throws Exception { - if (logger.isDebugEnabled()) { - logger.debug("New session: " + wsSession); - } + public void afterConnectionEstablished(WebSocketSession wsSession) throws Exception { SockJsSessionSupport session = new SockJsWebSocketSessionAdapter(wsSession); this.sessions.put(wsSession, session); } @Override - public void handleTextMessage(WebSocketSession wsSession, String message) throws Exception { - if (logger.isTraceEnabled()) { - logger.trace("Received payload " + message); - } + public void handleTextMessage(String message, WebSocketSession wsSession) throws Exception { SockJsSessionSupport session = getSockJsSession(wsSession); - session.delegateMessages(message); + session.delegateMessages(new String[] { message }); } @Override - public void handleBinaryMessage(WebSocketSession session, InputStream message) throws Exception { - // should not happen - throw new UnsupportedOperationException(); + public void handleBinaryMessage(byte[] message, WebSocketSession session) throws Exception { + logger.warn("Unexpected binary message for " + session); + session.close(CloseStatus.NOT_ACCEPTABLE); } @Override - public void handleException(WebSocketSession webSocketSession, Throwable exception) { - SockJsSessionSupport session = getSockJsSession(webSocketSession); - session.delegateException(exception); + public void afterConnectionClosed(CloseStatus status, WebSocketSession wsSession) throws Exception { + SockJsSessionSupport session = this.sessions.remove(wsSession); + session.delegateConnectionClosed(status); } @Override - public void sessionClosed(WebSocketSession webSocketSession, int statusCode, String reason) throws Exception { - logger.debug("WebSocket session closed " + webSocketSession); - SockJsSessionSupport session = this.sessions.remove(webSocketSession); - session.connectionClosed(); + public void handleError(Throwable exception, WebSocketSession wsSession) { + logger.error("Error for " + wsSession); + SockJsSessionSupport session = getSockJsSession(wsSession); + session.delegateError(exception); } private class SockJsWebSocketSessionAdapter extends SockJsSessionSupport { - private WebSocketSession wsSession; + private final WebSocketSession wsSession; public SockJsWebSocketSessionAdapter(WebSocketSession wsSession) throws Exception { - super(String.valueOf(wsSession.hashCode()), getSockJsHandler()); + super(wsSession.getId(), getSockJsHandler()); this.wsSession = wsSession; - connectionInitialized(); + delegateConnectionEstablished(); } @Override public boolean isActive() { - return (!isClosed() && this.wsSession.isOpen()); + return this.wsSession.isOpen(); } @Override public void sendMessage(String message) throws IOException { - this.wsSession.sendText(message); - } - - @Override - public void connectionClosed() { - logger.debug("Session closed"); - super.connectionClosed(); - this.wsSession = null; + this.wsSession.sendTextMessage(message); } @Override - public void close() { - if (!isClosed()) { - logger.debug("Closing session"); - super.close(); - this.wsSession.close(); - this.wsSession = null; - } + public void closeInternal(CloseStatus status) throws IOException { + this.wsSession.close(status); } }
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/WebSocketTransportHandler.java
@@ -50,9 +50,9 @@ public class WebSocketTransportHandler implements ConfigurableTransportHandler, private SockJsConfiguration sockJsConfig; - private final Map<SockJsHandler, WebSocketHandler> sockJsHandlers = new HashMap<SockJsHandler, WebSocketHandler>(); + private final Map<SockJsHandler, WebSocketHandler> sockJsHandlerCache = new HashMap<SockJsHandler, WebSocketHandler>(); - private final Collection<WebSocketHandler> rawWebSocketHandlers = new ArrayList<WebSocketHandler>(); + private final Collection<WebSocketHandler> rawWebSocketHandlerCache = new ArrayList<WebSocketHandler>(); public WebSocketTransportHandler(HandshakeHandler handshakeHandler) { @@ -72,9 +72,9 @@ public void setSockJsConfiguration(SockJsConfiguration sockJsConfig) { @Override public void registerSockJsHandlers(Collection<SockJsHandler> sockJsHandlers) { - this.sockJsHandlers.clear(); + this.sockJsHandlerCache.clear(); for (SockJsHandler sockJsHandler : sockJsHandlers) { - this.sockJsHandlers.put(sockJsHandler, adaptSockJsHandler(sockJsHandler)); + this.sockJsHandlerCache.put(sockJsHandler, adaptSockJsHandler(sockJsHandler)); } this.handshakeHandler.registerWebSocketHandlers(getAllWebSocketHandlers()); } @@ -89,16 +89,16 @@ protected WebSocketHandler adaptSockJsHandler(SockJsHandler sockJsHandler) { private Collection<WebSocketHandler> getAllWebSocketHandlers() { Set<WebSocketHandler> handlers = new HashSet<WebSocketHandler>(); - handlers.addAll(this.sockJsHandlers.values()); - handlers.addAll(this.rawWebSocketHandlers); + handlers.addAll(this.sockJsHandlerCache.values()); + handlers.addAll(this.rawWebSocketHandlerCache); return handlers; } @Override public void handleRequest(ServerHttpRequest request, ServerHttpResponse response, SockJsHandler sockJsHandler, SockJsSessionSupport session) throws Exception { - WebSocketHandler webSocketHandler = this.sockJsHandlers.get(sockJsHandler); + WebSocketHandler webSocketHandler = this.sockJsHandlerCache.get(sockJsHandler); if (webSocketHandler == null) { webSocketHandler = adaptSockJsHandler(sockJsHandler); } @@ -110,8 +110,8 @@ public void handleRequest(ServerHttpRequest request, ServerHttpResponse response @Override public void registerWebSocketHandlers(Collection<WebSocketHandler> webSocketHandlers) { - this.rawWebSocketHandlers.clear(); - this.rawWebSocketHandlers.addAll(webSocketHandlers); + this.rawWebSocketHandlerCache.clear(); + this.rawWebSocketHandlerCache.addAll(webSocketHandlers); this.handshakeHandler.registerWebSocketHandlers(getAllWebSocketHandlers()); }
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/websocket/CloseStatus.java
@@ -0,0 +1,192 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.websocket; + +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; + + +/** + * Represents a WebSocket close status code and reason. Status codes in the 1xxx range are + * pre-defined by the protocol. Optionally, a status code may be sent with a reason. + * <p> + * See <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1">RFC 6455, Section 7.4.1 + * "Defined Status Codes"</a>. + * + * @author Rossen Stoyanchev + * @since 4.0 + * + */ +public final class CloseStatus { + + /** + * "1000 indicates a normal closure, meaning that the purpose for which the connection + * was established has been fulfilled." + */ + public static final CloseStatus NORMAL = new CloseStatus(1000); + + /** + * "1001 indicates that an endpoint is "going away", such as a server going down or a + * browser having navigated away from a page." + */ + public static final CloseStatus GOING_AWAY = new CloseStatus(1001); + + /** + * "1002 indicates that an endpoint is terminating the connection due to a protocol + * error." + */ + public static final CloseStatus PROTOCOL_ERROR = new CloseStatus(1002); + + /** + * "1003 indicates that an endpoint is terminating the connection because it has + * received a type of data it cannot accept (e.g., an endpoint that understands only + * text data MAY send this if it receives a binary message)." + */ + public static final CloseStatus NOT_ACCEPTABLE = new CloseStatus(1003); + + // 10004: Reserved. + // The specific meaning might be defined in the future. + + /** + * "1005 is a reserved value and MUST NOT be set as a status code in a Close control + * frame by an endpoint. It is designated for use in applications expecting a status + * code to indicate that no status code was actually present." + */ + public static final CloseStatus NO_STATUS_CODE = new CloseStatus(1005); + + /** + * "1006 is a reserved value and MUST NOT be set as a status code in a Close control + * frame by an endpoint. It is designated for use in applications expecting a status + * code to indicate that the connection was closed abnormally, e.g., without sending + * or receiving a Close control frame." + */ + public static final CloseStatus NO_CLOSE_FRAME = new CloseStatus(1006); + + /** + * "1007 indicates that an endpoint is terminating the connection because it has + * received data within a message that was not consistent with the type of the message + * (e.g., non-UTF-8 [RFC3629] data within a text message)." + */ + public static final CloseStatus BAD_DATA = new CloseStatus(1007); + + /** + * "1008 indicates that an endpoint is terminating the connection because it has + * received a message that violates its policy. This is a generic status code that can + * be returned when there is no other more suitable status code (e.g., 1003 or 1009) + * or if there is a need to hide specific details about the policy." + */ + public static final CloseStatus POLICY_VIOLATION = new CloseStatus(1008); + + /** + * "1009 indicates that an endpoint is terminating the connection because it has + * received a message that is too big for it to process." + */ + public static final CloseStatus TOO_BIG_TO_PROCESS = new CloseStatus(1009); + + /** + * "1010 indicates that an endpoint (client) is terminating the connection because it + * has expected the server to negotiate one or more extension, but the server didn't + * return them in the response message of the WebSocket handshake. The list of + * extensions that are needed SHOULD appear in the /reason/ part of the Close frame. + * Note that this status code is not used by the server, because it can fail the + * WebSocket handshake instead." + */ + public static final CloseStatus REQUIRED_EXTENSION = new CloseStatus(1010); + + /** + * "1011 indicates that a server is terminating the connection because it encountered + * an unexpected condition that prevented it from fulfilling the request." + */ + public static final CloseStatus SERVER_ERROR = new CloseStatus(1011); + + /** + * 1012 indicates that the service is restarted. A client may reconnect, and if it + * choses to do, should reconnect using a randomized delay of 5 - 30s. + * <p>See <a href="https://www.ietf.org/mail-archive/web/hybi/current/msg09649.html"> + * [hybi] Additional WebSocket Close Error Codes</a> + */ + public static final CloseStatus SERVICE_RESTARTED = new CloseStatus(1012); + + /** + * 1013 indicates that the service is experiencing overload. A client should only + * connect to a different IP (when there are multiple for the target) or reconnect to + * the same IP upon user action. + * <p>See <a href="https://www.ietf.org/mail-archive/web/hybi/current/msg09649.html"> + * [hybi] Additional WebSocket Close Error Codes</a> + */ + public static final CloseStatus SERVICE_OVERLOAD = new CloseStatus(1013); + + /** + * "1015 is a reserved value and MUST NOT be set as a status code in a Close control + * frame by an endpoint. It is designated for use in applications expecting a status + * code to indicate that the connection was closed due to a failure to perform a TLS + * handshake (e.g., the server certificate can't be verified)." + */ + public static final CloseStatus TLS_HANDSHAKE_FAILURE = new CloseStatus(1015); + + + + private final int code; + + private final String reason; + + + public CloseStatus(int code) { + this(code, null); + } + + public CloseStatus(int code, String reason) { + Assert.isTrue((code >= 1000 && code < 5000), "Invalid code"); + this.code = code; + this.reason = reason; + } + + public int getCode() { + return this.code; + } + + public String getReason() { + return this.reason; + } + + public CloseStatus withReason(String reason) { + Assert.hasText(reason, "Expected non-empty reason"); + return new CloseStatus(this.code, reason); + } + + @Override + public int hashCode() { + return this.code * 29 + ObjectUtils.nullSafeHashCode(this.reason); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof CloseStatus)) { + return false; + } + CloseStatus otherStatus = (CloseStatus) other; + return (this.code == otherStatus.code && ObjectUtils.nullSafeEquals(this.reason, otherStatus.reason)); + } + + @Override + public String toString() { + return "CloseStatus [code=" + this.code + ", reason=" + this.reason + "]"; + } + +}
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/websocket/WebSocketHandler.java
@@ -16,24 +16,39 @@ package org.springframework.websocket; -import java.io.InputStream; /** + * A handler for WebSocket messages. * * @author Rossen Stoyanchev * @since 4.0 */ public interface WebSocketHandler { - void newSession(WebSocketSession session) throws Exception; - - void handleTextMessage(WebSocketSession session, String message) throws Exception; - - void handleBinaryMessage(WebSocketSession session, InputStream message) throws Exception; - - void handleException(WebSocketSession session, Throwable exception); - - void sessionClosed(WebSocketSession session, int statusCode, String reason) throws Exception; + /** + * A new WebSocket connection has been opened and is ready to be used. + */ + void afterConnectionEstablished(WebSocketSession session) throws Exception; + + /** + * Handle an incoming text message. + */ + void handleTextMessage(String message, WebSocketSession session) throws Exception; + + /** + * Handle an incoming binary message. + */ + void handleBinaryMessage(byte[] bytes, WebSocketSession session) throws Exception; + + /** + * TODO + */ + void handleError(Throwable exception, WebSocketSession session); + + /** + * A WebSocket connection has been closed. + */ + void afterConnectionClosed(CloseStatus closeStatus, WebSocketSession session) throws Exception; }
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/websocket/WebSocketHandlerAdapter.java
@@ -16,7 +16,6 @@ package org.springframework.websocket; -import java.io.InputStream; /** * @@ -26,23 +25,23 @@ public class WebSocketHandlerAdapter implements WebSocketHandler { @Override - public void newSession(WebSocketSession session) throws Exception { + public void afterConnectionEstablished(WebSocketSession session) throws Exception { } @Override - public void handleTextMessage(WebSocketSession session, String message) throws Exception { + public void handleTextMessage(String message, WebSocketSession session) throws Exception { } @Override - public void handleBinaryMessage(WebSocketSession session, InputStream message) throws Exception { + public void handleBinaryMessage(byte[] message, WebSocketSession session) throws Exception { } @Override - public void handleException(WebSocketSession session, Throwable exception) { + public void handleError(Throwable exception, WebSocketSession session) { } @Override - public void sessionClosed(WebSocketSession session, int statusCode, String reason) throws Exception { + public void afterConnectionClosed(CloseStatus status, WebSocketSession session) throws Exception { } }
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/websocket/WebSocketSession.java
@@ -17,24 +17,60 @@ package org.springframework.websocket; import java.io.IOException; +import java.net.URI; +import java.nio.ByteBuffer; /** + * Allows sending messages over a WebSocket connection as well as closing it. * * @author Rossen Stoyanchev * @since 4.0 */ public interface WebSocketSession { + /** + * Return a unique session identifier. + */ String getId(); + /** + * Return whether the connection is still open. + */ boolean isOpen(); - void sendText(String text) throws IOException; + /** + * Return whether the underlying socket is using a secure transport. + */ + boolean isSecure(); - void close(); + /** + * Return the URI used to open the WebSocket connection. + */ + URI getURI(); - void close(int code, String reason); + /** + * Send a text message. + */ + void sendTextMessage(String message) throws IOException; + + /** + * Send a binary message. + */ + void sendBinaryMessage(ByteBuffer message) throws IOException; + + /** + * Close the WebSocket connection with status 1000, i.e. equivalent to: + * <pre> + * session.close(CloseStatus.NORMAL); + * </pre> + */ + void close() throws IOException; + + /** + * Close the WebSocket connection with the given close status. + */ + void close(CloseStatus status) throws IOException; }
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/websocket/endpoint/StandardWebSocketSession.java
@@ -17,14 +17,22 @@ package org.springframework.websocket.endpoint; import java.io.IOException; +import java.net.URI; +import java.nio.ByteBuffer; + +import javax.websocket.CloseReason; +import javax.websocket.CloseReason.CloseCodes; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.springframework.util.Assert; +import org.springframework.websocket.CloseStatus; import org.springframework.websocket.WebSocketSession; /** - * A {@link WebSocketSession} that delegates to a {@link javax.websocket.Session}. + * A standard Java implementation of {@link WebSocketSession} that delegates to + * {@link javax.websocket.Session}. * * @author Rossen Stoyanchev * @since 4.0 @@ -33,10 +41,11 @@ public class StandardWebSocketSession implements WebSocketSession { private static Log logger = LogFactory.getLog(StandardWebSocketSession.class); - private javax.websocket.Session session; + private final javax.websocket.Session session; public StandardWebSocketSession(javax.websocket.Session session) { + Assert.notNull(session, "session is required"); this.session = session; } @@ -47,25 +56,53 @@ public String getId() { @Override public boolean isOpen() { - return ((this.session != null) && this.session.isOpen()); + return this.session.isOpen(); + } + + @Override + public boolean isSecure() { + return this.session.isSecure(); + } + + @Override + public URI getURI() { + return this.session.getRequestURI(); } @Override - public void sendText(String text) throws IOException { - logger.trace("Sending text message: " + text); - // TODO: check closed + public void sendTextMessage(String text) throws IOException { + if (logger.isTraceEnabled()) { + logger.trace("Sending text message: " + text + ", " + this); + } + Assert.isTrue(isOpen(), "Cannot send message after connection closed."); this.session.getBasicRemote().sendText(text); } @Override - public void close() { - // TODO: delegate with code and reason - this.session = null; + public void sendBinaryMessage(ByteBuffer message) throws IOException { + if (logger.isTraceEnabled()) { + logger.trace("Sending binary message, " + this); + } + Assert.isTrue(isOpen(), "Cannot send message after connection closed."); + this.session.getBasicRemote().sendBinary(message); + } + + @Override + public void close() throws IOException { + close(CloseStatus.NORMAL); + } + + @Override + public void close(CloseStatus status) throws IOException { + if (logger.isDebugEnabled()) { + logger.debug("Closing " + this); + } + this.session.close(new CloseReason(CloseCodes.getCloseCode(status.getCode()), status.getReason())); } @Override - public void close(int code, String reason) { - this.session = null; + public String toString() { + return "WebSocket session id=" + getId(); } }
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/websocket/endpoint/WebSocketHandlerEndpoint.java
@@ -27,6 +27,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.util.Assert; +import org.springframework.websocket.CloseStatus; import org.springframework.websocket.WebSocketSession; import org.springframework.websocket.WebSocketHandler; @@ -53,13 +54,14 @@ public WebSocketHandlerEndpoint(WebSocketHandler webSocketHandler) { @Override public void onOpen(javax.websocket.Session session, EndpointConfig config) { if (logger.isDebugEnabled()) { - logger.debug("New session: " + session); + logger.debug("Client connected, WebSocket session id=" + session.getId() + + ", path=" + session.getRequestURI().getPath()); } try { WebSocketSession webSocketSession = new StandardWebSocketSession(session); this.sessions.put(session.getId(), webSocketSession); session.addMessageHandler(new StandardMessageHandler(session)); - this.webSocketHandler.newSession(webSocketSession); + this.webSocketHandler.afterConnectionEstablished(webSocketSession); } catch (Throwable ex) { // TODO @@ -68,16 +70,15 @@ public void onOpen(javax.websocket.Session session, EndpointConfig config) { } @Override - public void onClose(javax.websocket.Session session, CloseReason closeReason) { + public void onClose(javax.websocket.Session session, CloseReason reason) { if (logger.isDebugEnabled()) { - logger.debug("Session closed: " + session + ", " + closeReason); + logger.debug("Client disconnected, WebSocket session id=" + session.getId() + ", " + reason); } try { WebSocketSession wsSession = this.sessions.remove(session.getId()); if (wsSession != null) { - int code = closeReason.getCloseCode().getCode(); - String reason = closeReason.getReasonPhrase(); - this.webSocketHandler.sessionClosed(wsSession, code, reason); + CloseStatus closeStatus = new CloseStatus(reason.getCloseCode().getCode(), reason.getReasonPhrase()); + this.webSocketHandler.afterConnectionClosed(closeStatus, wsSession); } else { Assert.notNull(wsSession, "No WebSocket session"); @@ -91,11 +92,11 @@ public void onClose(javax.websocket.Session session, CloseReason closeReason) { @Override public void onError(javax.websocket.Session session, Throwable exception) { - logger.error("Error for WebSocket session: " + session.getId(), exception); + logger.error("Error for WebSocket session id=" + session.getId(), exception); try { WebSocketSession wsSession = getWebSocketSession(session); if (wsSession != null) { - this.webSocketHandler.handleException(wsSession, exception); + this.webSocketHandler.handleError(exception, wsSession); } else { logger.warn("WebSocketSession not found. Perhaps onError was called after onClose?"); @@ -123,12 +124,12 @@ public StandardMessageHandler(javax.websocket.Session session) { @Override public void onMessage(String message) { if (logger.isTraceEnabled()) { - logger.trace("Message for session [" + this.session + "]: " + message); + logger.trace("Received message for WebSocket session id=" + this.session.getId() + ": " + message); } WebSocketSession wsSession = getWebSocketSession(this.session); Assert.notNull(wsSession, "WebSocketSession not found"); try { - WebSocketHandlerEndpoint.this.webSocketHandler.handleTextMessage(wsSession, message); + WebSocketHandlerEndpoint.this.webSocketHandler.handleTextMessage(message, wsSession); } catch (Throwable ex) { // TODO
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/websocket/server/support/AbstractEndpointUpgradeStrategy.java
@@ -75,6 +75,6 @@ public void upgrade(ServerHttpRequest request, ServerHttpResponse response, } protected abstract void upgradeInternal(ServerHttpRequest request, ServerHttpResponse response, - String protocol, Endpoint endpoint) throws Exception; + String selectedProtocol, Endpoint endpoint) throws Exception; }
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/websocket/server/support/GlassfishRequestUpgradeStrategy.java
@@ -18,6 +18,7 @@ import java.lang.reflect.Constructor; import java.net.URI; +import java.util.Arrays; import java.util.Random; import javax.servlet.http.HttpServletRequest; @@ -66,7 +67,7 @@ public String[] getSupportedVersions() { @Override public void upgradeInternal(ServerHttpRequest request, ServerHttpResponse response, - String protocol, Endpoint endpoint) throws Exception { + String selectedProtocol, Endpoint endpoint) throws Exception { Assert.isTrue(request instanceof ServletServerHttpRequest); HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); @@ -75,7 +76,7 @@ public void upgradeInternal(ServerHttpRequest request, ServerHttpResponse respon HttpServletResponse servletResponse = ((ServletServerHttpResponse) response).getServletResponse(); servletResponse = new AlreadyUpgradedResponseWrapper(servletResponse); - TyrusEndpoint tyrusEndpoint = createTyrusEndpoint(servletRequest, endpoint); + TyrusEndpoint tyrusEndpoint = createTyrusEndpoint(servletRequest, endpoint, selectedProtocol); WebSocketEngine engine = WebSocketEngine.getEngine(); engine.register(tyrusEndpoint); @@ -112,14 +113,15 @@ public void onWebSocketHolder(WebSocketEngine.WebSocketHolder webSocketHolder) { }); } - private TyrusEndpoint createTyrusEndpoint(HttpServletRequest request, Endpoint endpoint) { + private TyrusEndpoint createTyrusEndpoint(HttpServletRequest request, Endpoint endpoint, String selectedProtocol) { // Use randomized path String requestUri = request.getRequestURI(); String randomValue = String.valueOf(random.nextLong()); String endpointPath = requestUri.endsWith("/") ? requestUri + randomValue : requestUri + "/" + randomValue; EndpointRegistration endpointConfig = new EndpointRegistration(endpointPath, endpoint); + endpointConfig.setSubprotocols(Arrays.asList(selectedProtocol)); return new TyrusEndpoint(new EndpointWrapper(endpoint, endpointConfig, ComponentProviderService.create(), null, "/", new ErrorCollector(),
true
Other
spring-projects
spring-framework
ab5d60d343209832d3b27195fae8385b472a181b.json
Improve APIs for WebSocket and SockJS messages
spring-websocket/src/main/java/org/springframework/websocket/server/support/TomcatRequestUpgradeStrategy.java
@@ -51,7 +51,7 @@ public String[] getSupportedVersions() { @Override public void upgradeInternal(ServerHttpRequest request, ServerHttpResponse response, - String protocol, Endpoint endpoint) throws IOException { + String selectedProtocol, Endpoint endpoint) throws IOException { Assert.isTrue(request instanceof ServletServerHttpRequest); HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); @@ -74,7 +74,7 @@ public void upgradeInternal(ServerHttpRequest request, ServerHttpResponse respon ServerEndpointConfig endpointConfig = new EndpointRegistration("/shouldntmatter", endpoint); upgradeHandler.preInit(endpoint, endpointConfig, serverContainer, webSocketRequest, - protocol, Collections.<String, String> emptyMap(), servletRequest.isSecure()); + selectedProtocol, Collections.<String, String> emptyMap(), servletRequest.isSecure()); } }
true
Other
spring-projects
spring-framework
2794224b28430190c53c7cd284ccfe33c8eb5d1c.json
Add onClosed to SockJsSessionSupport sub-classes As opposed to close(), which actively closes the session, the onClosed method is called when the underlying connection has been closed or disconnected.
spring-websocket/src/main/java/org/springframework/sockjs/SockJsSession.java
@@ -27,6 +27,8 @@ */ public interface SockJsSession { + String getId(); + void sendMessage(String text) throws IOException; void close();
true
Other
spring-projects
spring-framework
2794224b28430190c53c7cd284ccfe33c8eb5d1c.json
Add onClosed to SockJsSessionSupport sub-classes As opposed to close(), which actively closes the session, the onClosed method is called when the underlying connection has been closed or disconnected.
spring-websocket/src/main/java/org/springframework/sockjs/SockJsSessionSupport.java
@@ -114,6 +114,11 @@ public void delegateException(Throwable ex) { this.sockJsHandler.handleException(this, ex); } + public void connectionClosed() { + this.state = State.CLOSED; + this.sockJsHandler.sessionClosed(this); + } + public void close() { this.state = State.CLOSED; this.sockJsHandler.sessionClosed(this);
true
Other
spring-projects
spring-framework
2794224b28430190c53c7cd284ccfe33c8eb5d1c.json
Add onClosed to SockJsSessionSupport sub-classes As opposed to close(), which actively closes the session, the onClosed method is called when the underlying connection has been closed or disconnected.
spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractServerSession.java
@@ -58,10 +58,18 @@ public final synchronized void sendMessage(String message) throws IOException { protected abstract void sendMessageInternal(String message) throws IOException; + + @Override + public void connectionClosed() { + logger.debug("Session closed"); + super.close(); + cancelHeartbeat(); + } + + @Override public final synchronized void close() { if (!isClosed()) { logger.debug("Closing session"); - if (isActive()) { // deliver messages "in flight" before sending close frame try { @@ -71,9 +79,7 @@ public final synchronized void close() { // ignore } } - super.close(); - cancelHeartbeat(); closeInternal(); }
true
Other
spring-projects
spring-framework
2794224b28430190c53c7cd284ccfe33c8eb5d1c.json
Add onClosed to SockJsSessionSupport sub-classes As opposed to close(), which actively closes the session, the onClosed method is called when the underlying connection has been closed or disconnected.
spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractSockJsService.java
@@ -40,7 +40,6 @@ import org.springframework.util.DigestUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; -import org.springframework.web.util.UriUtils; /** @@ -57,7 +56,7 @@ private static final int ONE_YEAR = 365 * 24 * 60 * 60; - private final String prefix; + private String name = getClass().getSimpleName() + "@" + Integer.toHexString(hashCode()); private String clientLibraryUrl = "https://d1fxtkz8shb9d2.cloudfront.net/sockjs-0.3.4.min.js"; @@ -74,31 +73,25 @@ private final TaskSchedulerHolder heartbeatSchedulerHolder; - /** - * Class constructor... - * - * @param prefix the path prefix for the SockJS service. All requests with a path - * that begins with the specified prefix will be handled by this service. In a - * Servlet container this is the path within the current servlet mapping. - */ - public AbstractSockJsService(String prefix) { - Assert.hasText(prefix, "prefix is required"); - this.prefix = prefix; + + public AbstractSockJsService() { this.heartbeatSchedulerHolder = new TaskSchedulerHolder("SockJs-heartbeat-"); } - public AbstractSockJsService(String prefix, TaskScheduler heartbeatScheduler) { - Assert.hasText(prefix, "prefix is required"); + public AbstractSockJsService(TaskScheduler heartbeatScheduler) { Assert.notNull(heartbeatScheduler, "heartbeatScheduler is required"); - this.prefix = prefix; this.heartbeatSchedulerHolder = new TaskSchedulerHolder(heartbeatScheduler); } /** - * The path prefix to which the SockJS service is mapped. + * A unique name for the service mainly for logging purposes. */ - public String getPrefix() { - return this.prefix; + public void setName(String name) { + this.name = name; + } + + public String getName() { + return this.name; } /** @@ -236,10 +229,6 @@ public final void handleRequest(ServerHttpRequest request, ServerHttpResponse re // Ignore invalid Content-Type (TODO) } - String path = UriUtils.decode(request.getURI().getPath(), "URF-8"); - int index = path.indexOf(this.prefix); - sockJsPath = path.substring(index + this.prefix.length()); - try { if (sockJsPath.equals("") || sockJsPath.equals("/")) { response.getHeaders().setContentType(new MediaType("text", "plain", Charset.forName("UTF-8")));
true
Other
spring-projects
spring-framework
2794224b28430190c53c7cd284ccfe33c8eb5d1c.json
Add onClosed to SockJsSessionSupport sub-classes As opposed to close(), which actively closes the session, the onClosed method is called when the underlying connection has been closed or disconnected.
spring-websocket/src/main/java/org/springframework/sockjs/server/SockJsService.java
@@ -31,8 +31,6 @@ */ public interface SockJsService { - String getPrefix(); - /** * Pre-register {@link SockJsHandler} instances so they can be adapted to * {@link WebSocketHandler} and hence re-used at runtime when
true
Other
spring-projects
spring-framework
2794224b28430190c53c7cd284ccfe33c8eb5d1c.json
Add onClosed to SockJsSessionSupport sub-classes As opposed to close(), which actively closes the session, the onClosed method is called when the underlying connection has been closed or disconnected.
spring-websocket/src/main/java/org/springframework/sockjs/server/support/DefaultSockJsService.java
@@ -70,13 +70,11 @@ public class DefaultSockJsService extends AbstractSockJsService implements Initi private final Map<SockJsHandler, WebSocketHandler> sockJsHandlers = new HashMap<SockJsHandler, WebSocketHandler>(); - public DefaultSockJsService(String prefix) { - super(prefix); + public DefaultSockJsService() { this.sessionTimeoutSchedulerHolder = new TaskSchedulerHolder("SockJs-sessionTimeout-"); } - public DefaultSockJsService(String prefix, TaskScheduler heartbeatScheduler, TaskScheduler sessionTimeoutScheduler) { - super(prefix, heartbeatScheduler); + public DefaultSockJsService(TaskScheduler heartbeatScheduler, TaskScheduler sessionTimeoutScheduler) { Assert.notNull(sessionTimeoutScheduler, "sessionTimeoutScheduler is required"); this.sessionTimeoutSchedulerHolder = new TaskSchedulerHolder(sessionTimeoutScheduler); } @@ -146,23 +144,23 @@ public void run() { try { int count = sessions.size(); if (logger.isTraceEnabled() && (count != 0)) { - logger.trace("Checking " + count + " session(s) for timeouts [" + getPrefix() + "]"); + logger.trace("Checking " + count + " session(s) for timeouts [" + getName() + "]"); } for (SockJsSessionSupport session : sessions.values()) { if (session.getTimeSinceLastActive() > getDisconnectDelay()) { if (logger.isTraceEnabled()) { - logger.trace("Removing " + session + " for [" + getPrefix() + "]"); + logger.trace("Removing " + session + " for [" + getName() + "]"); } session.close(); sessions.remove(session.getId()); } } if (logger.isTraceEnabled() && (count != 0)) { - logger.trace(sessions.size() + " remaining session(s) [" + getPrefix() + "]"); + logger.trace(sessions.size() + " remaining session(s) [" + getName() + "]"); } } catch (Throwable t) { - logger.error("Failed to complete session timeout checks for [" + getPrefix() + "]", t); + logger.error("Failed to complete session timeout checks for [" + getName() + "]", t); } } }, getDisconnectDelay());
true
Other
spring-projects
spring-framework
2794224b28430190c53c7cd284ccfe33c8eb5d1c.json
Add onClosed to SockJsSessionSupport sub-classes As opposed to close(), which actively closes the session, the onClosed method is called when the underlying connection has been closed or disconnected.
spring-websocket/src/main/java/org/springframework/sockjs/server/support/SockJsHttpRequestHandler.java
@@ -46,30 +46,59 @@ */ public class SockJsHttpRequestHandler implements HttpRequestHandler, BeanFactoryAware { + private final String prefix; + private final SockJsService sockJsService; private final HandlerProvider<SockJsHandler> handlerProvider; private final UrlPathHelper urlPathHelper = new UrlPathHelper(); - public SockJsHttpRequestHandler(SockJsService sockJsService, SockJsHandler sockJsHandler) { + /** + * Class constructor with {@link SockJsHandler} instance ... + * + * @param prefix the path prefix for the SockJS service. All requests with a path + * that begins with the specified prefix will be handled by this service. In a + * Servlet container this is the path within the current servlet mapping. + */ + public SockJsHttpRequestHandler(String prefix, SockJsService sockJsService, SockJsHandler sockJsHandler) { + + Assert.hasText(prefix, "prefix is required"); Assert.notNull(sockJsService, "sockJsService is required"); Assert.notNull(sockJsHandler, "sockJsHandler is required"); + + this.prefix = prefix; this.sockJsService = sockJsService; this.sockJsService.registerSockJsHandlers(Collections.singleton(sockJsHandler)); this.handlerProvider = new HandlerProvider<SockJsHandler>(sockJsHandler); } - public SockJsHttpRequestHandler(SockJsService sockJsService, Class<? extends SockJsHandler> sockJsHandlerClass) { + /** + * Class constructor with {@link SockJsHandler} type (per request) ... + * + * @param prefix the path prefix for the SockJS service. All requests with a path + * that begins with the specified prefix will be handled by this service. In a + * Servlet container this is the path within the current servlet mapping. + */ + public SockJsHttpRequestHandler(String prefix, SockJsService sockJsService, + Class<? extends SockJsHandler> sockJsHandlerClass) { + + Assert.hasText(prefix, "prefix is required"); Assert.notNull(sockJsService, "sockJsService is required"); Assert.notNull(sockJsHandlerClass, "sockJsHandlerClass is required"); + + this.prefix = prefix; this.sockJsService = sockJsService; this.handlerProvider = new HandlerProvider<SockJsHandler>(sockJsHandlerClass); } - public String getMappingPattern() { - return this.sockJsService.getPrefix() + "/**"; + public String getPrefix() { + return this.prefix; + } + + public String getPattern() { + return this.prefix + "/**"; } @Override @@ -82,10 +111,9 @@ public void handleRequest(HttpServletRequest request, HttpServletResponse respon throws ServletException, IOException { String lookupPath = this.urlPathHelper.getLookupPathForRequest(request); - String prefix = this.sockJsService.getPrefix(); - Assert.isTrue(lookupPath.startsWith(prefix), - "Request path does not match the prefix of the SockJsService " + prefix); + Assert.isTrue(lookupPath.startsWith(this.prefix), + "Request path does not match the prefix of the SockJsService " + this.prefix); String sockJsPath = lookupPath.substring(prefix.length());
true
Other
spring-projects
spring-framework
2794224b28430190c53c7cd284ccfe33c8eb5d1c.json
Add onClosed to SockJsSessionSupport sub-classes As opposed to close(), which actively closes the session, the onClosed method is called when the underlying connection has been closed or disconnected.
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractHttpServerSession.java
@@ -108,6 +108,13 @@ private void tryFlushCache() throws IOException { */ protected abstract void flushCache() throws IOException; + @Override + public void connectionClosed() { + super.connectionClosed(); + resetRequest(); + } + + @Override protected void closeInternal() { resetRequest(); }
true
Other
spring-projects
spring-framework
2794224b28430190c53c7cd284ccfe33c8eb5d1c.json
Add onClosed to SockJsSessionSupport sub-classes As opposed to close(), which actively closes the session, the onClosed method is called when the underlying connection has been closed or disconnected.
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractSockJsWebSocketHandler.java
@@ -1,108 +0,0 @@ -/* - * Copyright 2002-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.sockjs.server.transport; - -import java.io.InputStream; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.sockjs.SockJsHandler; -import org.springframework.sockjs.SockJsSessionSupport; -import org.springframework.sockjs.server.SockJsConfiguration; -import org.springframework.util.Assert; -import org.springframework.websocket.WebSocketHandler; -import org.springframework.websocket.WebSocketSession; - - -/** - * - * @author Rossen Stoyanchev - * @since 4.0 - */ -public abstract class AbstractSockJsWebSocketHandler implements WebSocketHandler { - - protected final Log logger = LogFactory.getLog(getClass()); - - private final SockJsConfiguration sockJsConfig; - - private final SockJsHandler sockJsHandler; - - private final Map<WebSocketSession, SockJsSessionSupport> sessions = - new ConcurrentHashMap<WebSocketSession, SockJsSessionSupport>(); - - - public AbstractSockJsWebSocketHandler(SockJsConfiguration sockJsConfig, SockJsHandler sockJsHandler) { - Assert.notNull(sockJsConfig, "sockJsConfig is required"); - Assert.notNull(sockJsHandler, "sockJsHandler is required"); - this.sockJsConfig = sockJsConfig; - this.sockJsHandler = sockJsHandler; - } - - protected SockJsConfiguration getSockJsConfig() { - return this.sockJsConfig; - } - - protected SockJsHandler getSockJsHandler() { - return this.sockJsHandler; - } - - protected SockJsSessionSupport getSockJsSession(WebSocketSession wsSession) { - return this.sessions.get(wsSession); - } - - @Override - public void newSession(WebSocketSession wsSession) throws Exception { - if (logger.isDebugEnabled()) { - logger.debug("New session: " + wsSession); - } - SockJsSessionSupport session = createSockJsSession(wsSession); - this.sessions.put(wsSession, session); - } - - protected abstract SockJsSessionSupport createSockJsSession(WebSocketSession wsSession) throws Exception; - - @Override - public void handleTextMessage(WebSocketSession wsSession, String message) throws Exception { - if (logger.isTraceEnabled()) { - logger.trace("Received payload " + message); - } - SockJsSessionSupport session = getSockJsSession(wsSession); - session.delegateMessages(message); - } - - @Override - public void handleBinaryMessage(WebSocketSession session, InputStream message) throws Exception { - // should not happen - throw new UnsupportedOperationException(); - } - - @Override - public void handleException(WebSocketSession webSocketSession, Throwable exception) { - SockJsSessionSupport session = getSockJsSession(webSocketSession); - session.delegateException(exception); - } - - @Override - public void sessionClosed(WebSocketSession webSocketSession, int statusCode, String reason) throws Exception { - logger.debug("WebSocket connection closed " + webSocketSession); - SockJsSessionSupport session = this.sessions.remove(webSocketSession); - session.close(); - } - -}
true
Other
spring-projects
spring-framework
2794224b28430190c53c7cd284ccfe33c8eb5d1c.json
Add onClosed to SockJsSessionSupport sub-classes As opposed to close(), which actively closes the session, the onClosed method is called when the underlying connection has been closed or disconnected.
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/SockJsWebSocketHandler.java
@@ -17,12 +17,18 @@ package org.springframework.sockjs.server.transport; import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.springframework.sockjs.SockJsHandler; import org.springframework.sockjs.SockJsSessionSupport; import org.springframework.sockjs.server.AbstractServerSession; import org.springframework.sockjs.server.SockJsConfiguration; import org.springframework.sockjs.server.SockJsFrame; +import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.websocket.WebSocketHandler; import org.springframework.websocket.WebSocketSession; @@ -37,19 +43,47 @@ * @author Rossen Stoyanchev * @since 4.0 */ -public class SockJsWebSocketHandler extends AbstractSockJsWebSocketHandler { +public class SockJsWebSocketHandler implements WebSocketHandler { + + private static final Log logger = LogFactory.getLog(SockJsWebSocketHandler.class); + + private final SockJsConfiguration sockJsConfig; + + private final SockJsHandler sockJsHandler; + + private final Map<WebSocketSession, SockJsSessionSupport> sessions = + new ConcurrentHashMap<WebSocketSession, SockJsSessionSupport>(); // TODO: JSON library used must be configurable private final ObjectMapper objectMapper = new ObjectMapper(); public SockJsWebSocketHandler(SockJsConfiguration sockJsConfig, SockJsHandler sockJsHandler) { - super(sockJsConfig, sockJsHandler); + Assert.notNull(sockJsConfig, "sockJsConfig is required"); + Assert.notNull(sockJsHandler, "sockJsHandler is required"); + this.sockJsConfig = sockJsConfig; + this.sockJsHandler = sockJsHandler; + } + + protected SockJsConfiguration getSockJsConfig() { + return this.sockJsConfig; + } + + protected SockJsHandler getSockJsHandler() { + return this.sockJsHandler; + } + + protected SockJsSessionSupport getSockJsSession(WebSocketSession wsSession) { + return this.sessions.get(wsSession); } @Override - protected SockJsSessionSupport createSockJsSession(WebSocketSession wsSession) throws Exception { - return new WebSocketServerSession(wsSession, getSockJsConfig()); + public void newSession(WebSocketSession wsSession) throws Exception { + if (logger.isDebugEnabled()) { + logger.debug("New session: " + wsSession); + } + SockJsSessionSupport session = new WebSocketServerSession(wsSession, getSockJsConfig()); + this.sessions.put(wsSession, session); } @Override @@ -72,6 +106,25 @@ public void handleTextMessage(WebSocketSession wsSession, String message) throws } } + @Override + public void handleBinaryMessage(WebSocketSession session, InputStream message) throws Exception { + // should not happen + throw new UnsupportedOperationException(); + } + + @Override + public void handleException(WebSocketSession webSocketSession, Throwable exception) { + SockJsSessionSupport session = getSockJsSession(webSocketSession); + session.delegateException(exception); + } + + @Override + public void sessionClosed(WebSocketSession webSocketSession, int statusCode, String reason) throws Exception { + logger.debug("WebSocket session closed " + webSocketSession); + SockJsSessionSupport session = this.sessions.remove(webSocketSession); + session.connectionClosed(); + } + private class WebSocketServerSession extends AbstractServerSession { @@ -107,15 +160,23 @@ protected void writeFrameInternal(SockJsFrame frame) throws IOException { } @Override - public void closeInternal() { - this.webSocketSession.close(); + public void connectionClosed() { + super.connectionClosed(); this.webSocketSession = null; + } + + @Override + public void closeInternal() { + deactivate(); updateLastActiveTime(); } @Override protected void deactivate() { - this.webSocketSession.close(); + if (this.webSocketSession != null) { + this.webSocketSession.close(); + this.webSocketSession = null; + } } }
true
Other
spring-projects
spring-framework
2794224b28430190c53c7cd284ccfe33c8eb5d1c.json
Add onClosed to SockJsSessionSupport sub-classes As opposed to close(), which actively closes the session, the onClosed method is called when the underlying connection has been closed or disconnected.
spring-websocket/src/main/java/org/springframework/sockjs/server/transport/WebSocketSockJsHandlerAdapter.java
@@ -17,10 +17,16 @@ package org.springframework.sockjs.server.transport; import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.springframework.sockjs.SockJsHandler; import org.springframework.sockjs.SockJsSessionSupport; import org.springframework.sockjs.server.SockJsConfiguration; +import org.springframework.util.Assert; import org.springframework.websocket.WebSocketHandler; import org.springframework.websocket.WebSocketSession; @@ -33,22 +39,78 @@ * @author Rossen Stoyanchev * @since 4.0 */ -public class WebSocketSockJsHandlerAdapter extends AbstractSockJsWebSocketHandler { +public class WebSocketSockJsHandlerAdapter implements WebSocketHandler { + + private static final Log logger = LogFactory.getLog(WebSocketSockJsHandlerAdapter.class); + + private final SockJsConfiguration sockJsConfig; + + private final SockJsHandler sockJsHandler; + + private final Map<WebSocketSession, SockJsSessionSupport> sessions = + new ConcurrentHashMap<WebSocketSession, SockJsSessionSupport>(); public WebSocketSockJsHandlerAdapter(SockJsConfiguration sockJsConfig, SockJsHandler sockJsHandler) { - super(sockJsConfig, sockJsHandler); + Assert.notNull(sockJsConfig, "sockJsConfig is required"); + Assert.notNull(sockJsHandler, "sockJsHandler is required"); + this.sockJsConfig = sockJsConfig; + this.sockJsHandler = sockJsHandler; + } + + protected SockJsConfiguration getSockJsConfig() { + return this.sockJsConfig; + } + + protected SockJsHandler getSockJsHandler() { + return this.sockJsHandler; + } + + protected SockJsSessionSupport getSockJsSession(WebSocketSession wsSession) { + return this.sessions.get(wsSession); + } + + @Override + public void newSession(WebSocketSession wsSession) throws Exception { + if (logger.isDebugEnabled()) { + logger.debug("New session: " + wsSession); + } + SockJsSessionSupport session = new WebSocketSessionAdapter(wsSession); + this.sessions.put(wsSession, session); } @Override - protected SockJsSessionSupport createSockJsSession(WebSocketSession wsSession) throws Exception { - return new WebSocketSessionAdapter(wsSession); + public void handleTextMessage(WebSocketSession wsSession, String message) throws Exception { + if (logger.isTraceEnabled()) { + logger.trace("Received payload " + message); + } + SockJsSessionSupport session = getSockJsSession(wsSession); + session.delegateMessages(message); + } + + @Override + public void handleBinaryMessage(WebSocketSession session, InputStream message) throws Exception { + // should not happen + throw new UnsupportedOperationException(); + } + + @Override + public void handleException(WebSocketSession webSocketSession, Throwable exception) { + SockJsSessionSupport session = getSockJsSession(webSocketSession); + session.delegateException(exception); + } + + @Override + public void sessionClosed(WebSocketSession webSocketSession, int statusCode, String reason) throws Exception { + logger.debug("WebSocket session closed " + webSocketSession); + SockJsSessionSupport session = this.sessions.remove(webSocketSession); + session.connectionClosed(); } private class WebSocketSessionAdapter extends SockJsSessionSupport { - private final WebSocketSession wsSession; + private WebSocketSession wsSession; public WebSocketSessionAdapter(WebSocketSession wsSession) throws Exception { @@ -67,11 +129,20 @@ public void sendMessage(String message) throws IOException { this.wsSession.sendText(message); } + @Override + public void connectionClosed() { + logger.debug("Session closed"); + super.connectionClosed(); + this.wsSession = null; + } + + @Override public void close() { if (!isClosed()) { logger.debug("Closing session"); super.close(); this.wsSession.close(); + this.wsSession = null; } } }
true
Other
spring-projects
spring-framework
2794224b28430190c53c7cd284ccfe33c8eb5d1c.json
Add onClosed to SockJsSessionSupport sub-classes As opposed to close(), which actively closes the session, the onClosed method is called when the underlying connection has been closed or disconnected.
spring-websocket/src/main/java/org/springframework/websocket/WebSocketSession.java
@@ -27,6 +27,8 @@ */ public interface WebSocketSession { + String getId(); + boolean isOpen(); void sendText(String text) throws IOException;
true
Other
spring-projects
spring-framework
2794224b28430190c53c7cd284ccfe33c8eb5d1c.json
Add onClosed to SockJsSessionSupport sub-classes As opposed to close(), which actively closes the session, the onClosed method is called when the underlying connection has been closed or disconnected.
spring-websocket/src/main/java/org/springframework/websocket/endpoint/StandardWebSocketSession.java
@@ -40,6 +40,11 @@ public StandardWebSocketSession(javax.websocket.Session session) { this.session = session; } + @Override + public String getId() { + return this.session.getId(); + } + @Override public boolean isOpen() { return ((this.session != null) && this.session.isOpen());
true
Other
spring-projects
spring-framework
2794224b28430190c53c7cd284ccfe33c8eb5d1c.json
Add onClosed to SockJsSessionSupport sub-classes As opposed to close(), which actively closes the session, the onClosed method is called when the underlying connection has been closed or disconnected.
spring-websocket/src/main/java/org/springframework/websocket/endpoint/WebSocketHandlerEndpoint.java
@@ -58,7 +58,7 @@ public void onOpen(javax.websocket.Session session, EndpointConfig config) { try { WebSocketSession webSocketSession = new StandardWebSocketSession(session); this.sessions.put(session.getId(), webSocketSession); - session.addMessageHandler(new StandardMessageHandler(session.getId())); + session.addMessageHandler(new StandardMessageHandler(session)); this.webSocketHandler.newSession(webSocketSession); } catch (Throwable ex) { @@ -69,16 +69,19 @@ public void onOpen(javax.websocket.Session session, EndpointConfig config) { @Override public void onClose(javax.websocket.Session session, CloseReason closeReason) { - String id = session.getId(); if (logger.isDebugEnabled()) { - logger.debug("Closing session: " + session + ", " + closeReason); + logger.debug("Session closed: " + session + ", " + closeReason); } try { - WebSocketSession webSocketSession = getSession(id); - this.sessions.remove(id); - int code = closeReason.getCloseCode().getCode(); - String reason = closeReason.getReasonPhrase(); - this.webSocketHandler.sessionClosed(webSocketSession, code, reason); + WebSocketSession wsSession = this.sessions.remove(session.getId()); + if (wsSession != null) { + int code = closeReason.getCloseCode().getCode(); + String reason = closeReason.getReasonPhrase(); + this.webSocketHandler.sessionClosed(wsSession, code, reason); + } + else { + Assert.notNull(wsSession, "No WebSocket session"); + } } catch (Throwable ex) { // TODO @@ -90,38 +93,42 @@ public void onClose(javax.websocket.Session session, CloseReason closeReason) { public void onError(javax.websocket.Session session, Throwable exception) { logger.error("Error for WebSocket session: " + session.getId(), exception); try { - WebSocketSession webSocketSession = getSession(session.getId()); - this.webSocketHandler.handleException(webSocketSession, exception); + WebSocketSession wsSession = getWebSocketSession(session); + if (wsSession != null) { + this.webSocketHandler.handleException(wsSession, exception); + } + else { + logger.warn("WebSocketSession not found. Perhaps onError was called after onClose?"); + } } catch (Throwable ex) { // TODO logger.error("Failed to handle error", ex); } } - private WebSocketSession getSession(String sourceSessionId) { - WebSocketSession webSocketSession = this.sessions.get(sourceSessionId); - Assert.notNull(webSocketSession, "No session"); - return webSocketSession; + private WebSocketSession getWebSocketSession(javax.websocket.Session session) { + return this.sessions.get(session.getId()); } private class StandardMessageHandler implements MessageHandler.Whole<String> { - private final String sessionId; + private final javax.websocket.Session session; - public StandardMessageHandler(String sessionId) { - this.sessionId = sessionId; + public StandardMessageHandler(javax.websocket.Session session) { + this.session = session; } @Override public void onMessage(String message) { if (logger.isTraceEnabled()) { - logger.trace("Message for session [" + this.sessionId + "]: " + message); + logger.trace("Message for session [" + this.session + "]: " + message); } + WebSocketSession wsSession = getWebSocketSession(this.session); + Assert.notNull(wsSession, "WebSocketSession not found"); try { - WebSocketSession session = getSession(this.sessionId); - WebSocketHandlerEndpoint.this.webSocketHandler.handleTextMessage(session, message); + WebSocketHandlerEndpoint.this.webSocketHandler.handleTextMessage(wsSession, message); } catch (Throwable ex) { // TODO
true
Other
spring-projects
spring-framework
3a2c15b0fd5d370f80964b8f4d62b353823e06cf.json
Add flush method to ServerHttpResponse This is useful to make sure response headers are written to the underlying response. It is also useful in conjunction with long running, async requests and HTTP streaming, to ensure the Servlet response buffer is sent to the client without additional delay and also causes an IOException to be raised if the client has gone away.
spring-web/src/main/java/org/springframework/http/server/AsyncServletServerHttpRequest.java
@@ -116,21 +116,35 @@ public void completeAsync() { // Implementation of AsyncListener methods // --------------------------------------------------------------------- + @Override public void onStartAsync(AsyncEvent event) throws IOException { } + @Override public void onError(AsyncEvent event) throws IOException { } + @Override public void onTimeout(AsyncEvent event) throws IOException { - for (Runnable handler : this.timeoutHandlers) { - handler.run(); + try { + for (Runnable handler : this.timeoutHandlers) { + handler.run(); + } + } + catch (Throwable t) { + // ignore } } + @Override public void onComplete(AsyncEvent event) throws IOException { - for (Runnable handler : this.completionHandlers) { - handler.run(); + try { + for (Runnable handler : this.completionHandlers) { + handler.run(); + } + } + catch (Throwable t) { + // ignore } this.asyncContext = null; this.asyncCompleted.set(true);
true
Other
spring-projects
spring-framework
3a2c15b0fd5d370f80964b8f4d62b353823e06cf.json
Add flush method to ServerHttpResponse This is useful to make sure response headers are written to the underlying response. It is also useful in conjunction with long running, async requests and HTTP streaming, to ensure the Servlet response buffer is sent to the client without additional delay and also causes an IOException to be raised if the client has gone away.
spring-web/src/main/java/org/springframework/http/server/ServerHttpResponse.java
@@ -17,6 +17,7 @@ package org.springframework.http.server; import java.io.Closeable; +import java.io.IOException; import org.springframework.http.HttpOutputMessage; import org.springframework.http.HttpStatus; @@ -35,6 +36,11 @@ public interface ServerHttpResponse extends HttpOutputMessage, Closeable { */ void setStatusCode(HttpStatus status); + /** + * TODO + */ + void flush() throws IOException; + /** * Close this response, freeing any resources created. */
true
Other
spring-projects
spring-framework
3a2c15b0fd5d370f80964b8f4d62b353823e06cf.json
Add flush method to ServerHttpResponse This is useful to make sure response headers are written to the underlying response. It is also useful in conjunction with long running, async requests and HTTP streaming, to ensure the Servlet response buffer is sent to the client without additional delay and also causes an IOException to be raised if the client has gone away.
spring-web/src/main/java/org/springframework/http/server/ServletServerHttpResponse.java
@@ -80,6 +80,13 @@ public OutputStream getBody() throws IOException { return this.servletResponse.getOutputStream(); } + @Override + public void flush() throws IOException { + writeCookies(); + writeHeaders(); + this.servletResponse.flushBuffer(); + } + public void close() { writeCookies(); writeHeaders();
true
Other
spring-projects
spring-framework
3a2c15b0fd5d370f80964b8f4d62b353823e06cf.json
Add flush method to ServerHttpResponse This is useful to make sure response headers are written to the underlying response. It is also useful in conjunction with long running, async requests and HTTP streaming, to ensure the Servlet response buffer is sent to the client without additional delay and also causes an IOException to be raised if the client has gone away.
spring-websocket/src/main/java/org/springframework/sockjs/SockJsSession.java
@@ -16,6 +16,8 @@ package org.springframework.sockjs; +import java.io.IOException; + /** @@ -25,7 +27,7 @@ */ public interface SockJsSession { - void sendMessage(String text) throws Exception; + void sendMessage(String text) throws IOException; void close();
true
Other
spring-projects
spring-framework
3a2c15b0fd5d370f80964b8f4d62b353823e06cf.json
Add flush method to ServerHttpResponse This is useful to make sure response headers are written to the underlying response. It is also useful in conjunction with long running, async requests and HTTP streaming, to ensure the Servlet response buffer is sent to the client without additional delay and also causes an IOException to be raised if the client has gone away.
spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractServerSession.java
@@ -17,6 +17,8 @@ package org.springframework.sockjs.server; import java.io.EOFException; +import java.io.IOException; +import java.net.SocketException; import java.util.Date; import java.util.concurrent.ScheduledFuture; @@ -54,20 +56,25 @@ protected SockJsConfiguration getSockJsConfig() { return this.sockJsConfig; } - public final synchronized void sendMessage(String message) { + public final synchronized void sendMessage(String message) throws IOException { Assert.isTrue(!isClosed(), "Cannot send a message, session has been closed"); sendMessageInternal(message); } - protected abstract void sendMessageInternal(String message); + protected abstract void sendMessageInternal(String message) throws IOException; public final synchronized void close() { if (!isClosed()) { logger.debug("Closing session"); if (isActive()) { // deliver messages "in flight" before sending close frame - writeFrame(SockJsFrame.closeFrameGoAway()); + try { + writeFrame(SockJsFrame.closeFrameGoAway()); + } + catch (Exception e) { + // ignore + } } super.close(); @@ -83,26 +90,33 @@ public final synchronized void close() { * For internal use within a TransportHandler and the (TransportHandler-specific) * session sub-class. The frame is written only if the connection is active. */ - protected void writeFrame(SockJsFrame frame) { + protected void writeFrame(SockJsFrame frame) throws IOException { if (logger.isTraceEnabled()) { logger.trace("Preparing to write " + frame); } try { writeFrameInternal(frame); } - catch (EOFException ex) { - logger.warn("Client went away. Terminating connection abruptly"); + catch (IOException ex) { + if (ex instanceof EOFException || ex instanceof SocketException) { + logger.warn("Client went away. Terminating connection"); + } + else { + logger.warn("Failed to send message. Terminating connection: " + ex.getMessage()); + } deactivate(); close(); + throw ex; } catch (Throwable t) { - logger.warn("Failed to send message. Terminating connection abruptly: " + t.getMessage()); + logger.warn("Failed to send message. Terminating connection: " + t.getMessage()); deactivate(); close(); + throw new NestedSockJsRuntimeException("Failed to write frame " + frame, t); } } - protected abstract void writeFrameInternal(SockJsFrame frame) throws Exception; + protected abstract void writeFrameInternal(SockJsFrame frame) throws IOException; /** * Some {@link TransportHandler} types cannot detect if a client connection is closed @@ -111,7 +125,7 @@ protected void writeFrame(SockJsFrame frame) { */ protected abstract void deactivate(); - public synchronized void sendHeartbeat() { + public synchronized void sendHeartbeat() throws IOException { if (isActive()) { writeFrame(SockJsFrame.heartbeatFrame()); scheduleHeartbeat(); @@ -127,7 +141,12 @@ protected void scheduleHeartbeat() { Date time = new Date(System.currentTimeMillis() + getSockJsConfig().getHeartbeatTime()); this.heartbeatTask = getSockJsConfig().getHeartbeatScheduler().schedule(new Runnable() { public void run() { - sendHeartbeat(); + try { + sendHeartbeat(); + } + catch (IOException e) { + // ignore + } } }, time); if (logger.isTraceEnabled()) {
true
Other
spring-projects
spring-framework
3a2c15b0fd5d370f80964b8f4d62b353823e06cf.json
Add flush method to ServerHttpResponse This is useful to make sure response headers are written to the underlying response. It is also useful in conjunction with long running, async requests and HTTP streaming, to ensure the Servlet response buffer is sent to the client without additional delay and also causes an IOException to be raised if the client has gone away.
spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractSockJsService.java
@@ -214,50 +214,57 @@ public final void handleRequest(ServerHttpRequest request, ServerHttpResponse re request.getHeaders(); } catch (IllegalArgumentException ex) { - // Ignore invalid Content-Type (TODO!!) + // Ignore invalid Content-Type (TODO) } - if (sockJsPath.equals("") || sockJsPath.equals("/")) { - response.getHeaders().setContentType(new MediaType("text", "plain", Charset.forName("UTF-8"))); - response.getBody().write("Welcome to SockJS!\n".getBytes("UTF-8")); - return; - } - else if (sockJsPath.equals("/info")) { - this.infoHandler.handle(request, response); - return; - } - else if (sockJsPath.matches("/iframe[0-9-.a-z_]*.html")) { - this.iframeHandler.handle(request, response); - return; - } - else if (sockJsPath.equals("/websocket")) { - handleRawWebSocket(request, response); - return; - } - - String[] pathSegments = StringUtils.tokenizeToStringArray(sockJsPath.substring(1), "/"); - if (pathSegments.length != 3) { - logger.debug("Expected /{server}/{session}/{transport} but got " + sockJsPath); - response.setStatusCode(HttpStatus.NOT_FOUND); - return; - } + try { + if (sockJsPath.equals("") || sockJsPath.equals("/")) { + response.getHeaders().setContentType(new MediaType("text", "plain", Charset.forName("UTF-8"))); + response.getBody().write("Welcome to SockJS!\n".getBytes("UTF-8")); + return; + } + else if (sockJsPath.equals("/info")) { + this.infoHandler.handle(request, response); + return; + } + else if (sockJsPath.matches("/iframe[0-9-.a-z_]*.html")) { + this.iframeHandler.handle(request, response); + return; + } + else if (sockJsPath.equals("/websocket")) { + handleRawWebSocket(request, response); + return; + } - String serverId = pathSegments[0]; - String sessionId = pathSegments[1]; - String transport = pathSegments[2]; + String[] pathSegments = StringUtils.tokenizeToStringArray(sockJsPath.substring(1), "/"); + if (pathSegments.length != 3) { + logger.debug("Expected /{server}/{session}/{transport} but got " + sockJsPath); + response.setStatusCode(HttpStatus.NOT_FOUND); + return; + } - if (!validateRequest(serverId, sessionId, transport)) { - response.setStatusCode(HttpStatus.NOT_FOUND); - return; - } + String serverId = pathSegments[0]; + String sessionId = pathSegments[1]; + String transport = pathSegments[2]; - handleRequestInternal(request, response, sessionId, TransportType.fromValue(transport)); + if (!validateRequest(serverId, sessionId, transport)) { + response.setStatusCode(HttpStatus.NOT_FOUND); + return; + } + handleTransportRequest(request, response, sessionId, TransportType.fromValue(transport)); + } + finally { + response.flush(); + } } protected abstract void handleRawWebSocket(ServerHttpRequest request, ServerHttpResponse response) throws Exception; + protected abstract void handleTransportRequest(ServerHttpRequest request, ServerHttpResponse response, + String sessionId, TransportType transportType) throws Exception; + protected boolean validateRequest(String serverId, String sessionId, String transport) { if (!StringUtils.hasText(serverId) || !StringUtils.hasText(sessionId) || !StringUtils.hasText(transport)) { @@ -279,9 +286,6 @@ protected boolean validateRequest(String serverId, String sessionId, String tran return true; } - protected abstract void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response, - String sessionId, TransportType transportType) throws Exception; - protected void addCorsHeaders(ServerHttpRequest request, ServerHttpResponse response, HttpMethod... httpMethods) { String origin = request.getHeaders().getFirst("origin"); @@ -316,7 +320,6 @@ protected void sendMethodNotAllowed(ServerHttpResponse response, List<HttpMethod logger.debug("Sending Method Not Allowed (405)"); response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED); response.getHeaders().setAllow(new HashSet<HttpMethod>(httpMethods)); - response.getBody(); // ensure headers are flushed (TODO!) } @@ -350,8 +353,6 @@ else if (HttpMethod.OPTIONS.equals(request.getMethod())) { addCorsHeaders(request, response, HttpMethod.GET, HttpMethod.OPTIONS); addCacheHeaders(response); - - response.getBody(); // ensure headers are flushed (TODO!) } else { sendMethodNotAllowed(response, Arrays.asList(HttpMethod.OPTIONS, HttpMethod.GET));
true