Add WebSocket scope

This change adds support for a custom "websocket" scope.

WebSocket-scoped beans may be injected into controllers with message
handling methods as well as channel interceptor registered on the
"inboundClientChannel".

Issue: SPR-11305
This commit is contained in:
Rossen Stoyanchev
2014-05-09 16:51:14 -04:00
parent 66c63c374b
commit 2c4cbb617e
18 changed files with 1090 additions and 26 deletions

View File

@@ -26,6 +26,7 @@ import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.messaging.MessageHandler;
@@ -175,6 +176,8 @@ public class MessageBrokerBeanDefinitionParserTests {
catch (NoSuchBeanDefinitionException ex) {
// expected
}
assertNotNull(this.appContext.getBean("webSocketScopeConfigurer", CustomScopeConfigurer.class));
}
@Test

View File

@@ -31,6 +31,8 @@ import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpAttributes;
import org.springframework.messaging.simp.SimpAttributesContextHolder;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.TestPrincipal;
@@ -48,6 +50,7 @@ import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.handler.TestWebSocketSession;
import org.springframework.web.socket.sockjs.transport.SockJsSession;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@@ -289,6 +292,41 @@ public class StompSubProtocolHandlerTests {
assertTrue(actual.getPayload().startsWith("ERROR"));
}
@Test
public void webSocketScope() {
Runnable runnable = Mockito.mock(Runnable.class);
SimpAttributes simpAttributes = new SimpAttributes(this.session.getId(), this.session.getAttributes());
simpAttributes.setAttribute("name", "value");
simpAttributes.registerDestructionCallback("name", runnable);
MessageChannel testChannel = new MessageChannel() {
@Override
public boolean send(Message<?> message) {
SimpAttributes simpAttributes = SimpAttributesContextHolder.currentAttributes();
assertThat(simpAttributes.getAttribute("name"), is("value"));
return true;
}
@Override
public boolean send(Message<?> message, long timeout) {
return false;
}
};
this.protocolHandler.afterSessionStarted(this.session, this.channel);
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders());
TextMessage textMessage = new TextMessage(new StompEncoder().encode(message));
this.protocolHandler.handleMessageFromClient(this.session, textMessage, testChannel);
assertEquals(Collections.emptyList(), session.getSentMessages());
this.protocolHandler.afterSessionEnded(this.session, CloseStatus.BAD_DATA, testChannel);
assertEquals(Collections.emptyList(), session.getSentMessages());
verify(runnable, times(1)).run();
}
private static class UniqueUser extends TestPrincipal implements DestinationUserNameProvider {

View File

@@ -34,6 +34,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.annotation.SendToUser;
@@ -97,11 +99,11 @@ public class StompWebSocketIntegrationTests extends AbstractWebSocketIntegration
@Test
public void sendMessageToControllerAndReceiveReplyViaTopic() throws Exception {
TextMessage message1 = create(StompCommand.SUBSCRIBE).headers(
"id:subs1", "destination:/topic/increment").build();
TextMessage message1 = create(StompCommand.SUBSCRIBE)
.headers("id:subs1", "destination:/topic/increment").build();
TextMessage message2 = create(StompCommand.SEND).headers(
"destination:/app/increment").body("5").build();
TextMessage message2 = create(StompCommand.SEND)
.headers("destination:/app/increment").body("5").build();
TestClientWebSocketHandler clientHandler = new TestClientWebSocketHandler(1, message1, message2);
WebSocketSession session = doHandshake(clientHandler, "/ws").get();
@@ -181,6 +183,37 @@ public class StompWebSocketIntegrationTests extends AbstractWebSocketIntegration
}
}
@Test
public void webSocketScope() throws Exception {
TextMessage message1 = create(StompCommand.SUBSCRIBE)
.headers("id:subs1", "destination:/topic/scopedBeanValue").build();
TextMessage message2 = create(StompCommand.SEND)
.headers("destination:/app/scopedBeanValue").build();
TestClientWebSocketHandler clientHandler = new TestClientWebSocketHandler(1, message1, message2);
WebSocketSession session = doHandshake(clientHandler, "/ws").get();
try {
assertTrue(clientHandler.latch.await(2, TimeUnit.SECONDS));
String payload = clientHandler.actual.get(0).getPayload();
assertTrue(payload.startsWith("MESSAGE\n"));
assertTrue(payload.contains("destination:/topic/scopedBeanValue\n"));
assertTrue(payload.endsWith("\"55\"\0"));
}
finally {
session.close();
}
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Controller
private @interface IntegrationTestController {
}
@IntegrationTestController
static class SimpleController {
@@ -218,6 +251,42 @@ public class StompWebSocketIntegrationTests extends AbstractWebSocketIntegration
}
}
@IntegrationTestController
static class ScopedBeanController {
private final ScopedBean scopedBean;
@Autowired
public ScopedBeanController(ScopedBean scopedBean) {
this.scopedBean = scopedBean;
}
@MessageMapping(value="/scopedBeanValue")
public String getValue() {
return this.scopedBean.getValue();
}
}
static interface ScopedBean {
String getValue();
}
static class ScopedBeanImpl implements ScopedBean {
private final String value;
public ScopedBeanImpl(String value) {
this.value = value;
}
@Override
public String getValue() {
return this.value;
}
}
private static class TestClientWebSocketHandler extends TextWebSocketHandler {
@@ -251,7 +320,8 @@ public class StompWebSocketIntegrationTests extends AbstractWebSocketIntegration
}
@Configuration
@ComponentScan(basePackageClasses=StompWebSocketIntegrationTests.class,
@ComponentScan(
basePackageClasses=StompWebSocketIntegrationTests.class,
useDefaultFilters=false,
includeFilters=@ComponentScan.Filter(IntegrationTestController.class))
static class TestMessageBrokerConfigurer extends AbstractWebSocketMessageBrokerConfigurer {
@@ -269,6 +339,12 @@ public class StompWebSocketIntegrationTests extends AbstractWebSocketIntegration
configurer.setApplicationDestinationPrefixes("/app");
configurer.enableSimpleBroker("/topic", "/queue");
}
@Bean
@Scope(value="websocket", proxyMode=ScopedProxyMode.INTERFACES)
public ScopedBean scopedBean() {
return new ScopedBeanImpl("55");
}
}
@Configuration
@@ -287,10 +363,4 @@ public class StompWebSocketIntegrationTests extends AbstractWebSocketIntegration
}
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Controller
private @interface IntegrationTestController {
}
}