Java Code Examples for org.springframework.web.socket.WebSocketHandler

The following examples show how to use org.springframework.web.socket.WebSocketHandler. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void openConnection() throws Exception {
	List<String> subprotocols = Arrays.asList("abc");

	TestLifecycleWebSocketClient client = new TestLifecycleWebSocketClient(false);
	WebSocketHandler handler = new TextWebSocketHandler();

	WebSocketConnectionManager manager = new WebSocketConnectionManager(client, handler , "/path/{id}", "123");
	manager.setSubProtocols(subprotocols);
	manager.openConnection();

	WebSocketHttpHeaders expectedHeaders = new WebSocketHttpHeaders();
	expectedHeaders.setSecWebSocketProtocol(subprotocols);

	assertEquals(expectedHeaders, client.headers);
	assertEquals(new URI("/path/123"), client.uri);

	WebSocketHandlerDecorator loggingHandler = (WebSocketHandlerDecorator) client.webSocketHandler;
	assertEquals(LoggingWebSocketHandlerDecorator.class, loggingHandler.getClass());

	assertSame(handler, loggingHandler.getDelegate());
}
 
Example 2
@Test
public void supportedSubProtocols() {
	this.handshakeHandler.setSupportedProtocols("stomp", "mqtt");
	given(this.upgradeStrategy.getSupportedVersions()).willReturn(new String[] {"13"});
	this.servletRequest.setMethod("GET");

	WebSocketHttpHeaders headers = new WebSocketHttpHeaders(this.request.getHeaders());
	headers.setUpgrade("WebSocket");
	headers.setConnection("Upgrade");
	headers.setSecWebSocketVersion("13");
	headers.setSecWebSocketKey("82/ZS2YHjEnUN97HLL8tbw==");
	headers.setSecWebSocketProtocol("STOMP");

	WebSocketHandler handler = new TextWebSocketHandler();
	Map<String, Object> attributes = Collections.emptyMap();
	this.handshakeHandler.doHandshake(this.request, this.response, handler, attributes);

	verify(this.upgradeStrategy).upgrade(this.request, this.response, "STOMP",
			Collections.emptyList(), null, handler, attributes);
}
 
Example 3
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
        WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {

    // Set ip attribute to WebSocket session
    attributes.put("ip", request.getRemoteAddress());

    // Set servlet request attribute to WebSocket session
    if (request instanceof ServletServerHttpRequest) {
        ServletServerHttpRequest servletServerRequest = (ServletServerHttpRequest) request;
        HttpServletRequest servletRequest = servletServerRequest.getServletRequest();
        attributes.put(UNDERLYING_SERVLET_REQUEST, servletRequest);
    }

    return true;
}
 
Example 4
@Test
public void delegateMessageException() throws Exception {
	StubSockJsServiceConfig sockJsConfig = new StubSockJsServiceConfig();
	this.servletRequest.setContent("[\"x\"]".getBytes("UTF-8"));

	WebSocketHandler wsHandler = mock(WebSocketHandler.class);
	TestHttpSockJsSession session = new TestHttpSockJsSession("1", sockJsConfig, wsHandler, null);
	session.delegateConnectionEstablished();

	willThrow(new Exception()).given(wsHandler).handleMessage(session, new TextMessage("x"));

	try {
		XhrReceivingTransportHandler transportHandler = new XhrReceivingTransportHandler();
		transportHandler.initialize(sockJsConfig);
		transportHandler.handleRequest(this.request, this.response, wsHandler, session);
		fail("Expected exception");
	}
	catch (SockJsMessageDeliveryException ex) {
		assertNull(session.getCloseStatus());
	}
}
 
Example 5
@Test
public void supportedExtensions() {
	WebSocketExtension extension1 = new WebSocketExtension("ext1");
	WebSocketExtension extension2 = new WebSocketExtension("ext2");

	given(this.upgradeStrategy.getSupportedVersions()).willReturn(new String[] {"13"});
	given(this.upgradeStrategy.getSupportedExtensions(this.request)).willReturn(Collections.singletonList(extension1));

	this.servletRequest.setMethod("GET");

	WebSocketHttpHeaders headers = new WebSocketHttpHeaders(this.request.getHeaders());
	headers.setUpgrade("WebSocket");
	headers.setConnection("Upgrade");
	headers.setSecWebSocketVersion("13");
	headers.setSecWebSocketKey("82/ZS2YHjEnUN97HLL8tbw==");
	headers.setSecWebSocketExtensions(Arrays.asList(extension1, extension2));

	WebSocketHandler handler = new TextWebSocketHandler();
	Map<String, Object> attributes = Collections.<String, Object>emptyMap();
	this.handshakeHandler.doHandshake(this.request, this.response, handler, attributes);

	verify(this.upgradeStrategy).upgrade(this.request, this.response, null,
			Collections.singletonList(extension1), null, handler, attributes);
}
 
Example 6
@Test
public void constructorWithAttributeNames() throws Exception {
	Map<String, Object> attributes = new HashMap<>();
	WebSocketHandler wsHandler = Mockito.mock(WebSocketHandler.class);

	this.servletRequest.setSession(new MockHttpSession(null, "123"));
	this.servletRequest.getSession().setAttribute("foo", "bar");
	this.servletRequest.getSession().setAttribute("bar", "baz");

	Set<String> names = Collections.singleton("foo");
	HttpSessionHandshakeInterceptor interceptor = new HttpSessionHandshakeInterceptor(names);
	interceptor.beforeHandshake(this.request, this.response, wsHandler, attributes);

	assertEquals(2, attributes.size());
	assertEquals("bar", attributes.get("foo"));
	assertEquals("123", attributes.get(HttpSessionHandshakeInterceptor.HTTP_SESSION_ID_ATTR_NAME));
}
 
Example 7
Source Project: artemis   Source File: WsIPBlackList.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
    try {
        if (ipBlackListEnabled.typedValue()) {
            String ip = InetSocketAddressHelper.getRemoteIP(request);
            for (String blackIp : ipBlackList.typedValue()) {
                if (ip.equalsIgnoreCase(blackIp)) {
                    return false;
                }
            }
        }
    } catch (Throwable ex) {
        logger.warn("process WebSocket ip black list failed" + ex.getMessage(), ex);
    }
    return true;
}
 
Example 8
@Test
public void handshakeHandlerPassedToSockJsRegistration() {
	WebSocketHandler handler = new TextWebSocketHandler();
	HandshakeHandler handshakeHandler = new DefaultHandshakeHandler();

	this.registration.addHandler(handler, "/foo").setHandshakeHandler(handshakeHandler).withSockJS();
	this.registration.getSockJsServiceRegistration().setTaskScheduler(this.taskScheduler);

	List<Mapping> mappings = this.registration.getMappings();
	assertEquals(1, mappings.size());

	Mapping mapping = mappings.get(0);
	assertEquals(handler, mapping.webSocketHandler);
	assertEquals("/foo/**", mapping.path);
	assertNotNull(mapping.sockJsService);

	WebSocketTransportHandler transportHandler =
			(WebSocketTransportHandler) mapping.sockJsService.getTransportHandlers().get(TransportType.WEBSOCKET);
	assertSame(handshakeHandler, transportHandler.getHandshakeHandler());
}
 
Example 9
Source Project: example-restful-project   Source File: WebSocketConfig.java    License: MIT License 6 votes vote down vote up
@Override
public boolean beforeHandshake(ServerHttpRequest request,
        ServerHttpResponse response, WebSocketHandler wsHandler,
        Map<String, Object> attributes) throws Exception {

    /* Retrieve original HTTP request */
    HttpServletRequest origRequest =
            ((ServletServerHttpRequest) request).getServletRequest();

    /* Retrieve template variables */
    Map<String, String> uriTemplateVars =
            (Map<String, String>) origRequest
                .getAttribute(
                    HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);

    /* Put template variables into WebSocket session attributes */
    if (uriTemplateVars != null) {
        attributes.putAll(uriTemplateVars);
    }

    return true;
}
 
Example 10
Source Project: spring4-understanding   Source File: WebSocketTransport.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<WebSocketSession> connect(TransportRequest request, WebSocketHandler handler) {
	final SettableListenableFuture<WebSocketSession> future = new SettableListenableFuture<WebSocketSession>();
	WebSocketClientSockJsSession session = new WebSocketClientSockJsSession(request, handler, future);
	handler = new ClientSockJsWebSocketHandler(session);
	request.addTimeoutTask(session.getTimeoutTask());

	URI url = request.getTransportUrl();
	WebSocketHttpHeaders headers = new WebSocketHttpHeaders(request.getHandshakeHeaders());
	if (logger.isDebugEnabled()) {
		logger.debug("Starting WebSocket session url=" + url);
	}
	this.webSocketClient.doHandshake(handler, headers, url).addCallback(
			new ListenableFutureCallback<WebSocketSession>() {
				@Override
				public void onSuccess(WebSocketSession webSocketSession) {
					// WebSocket session ready, SockJS Session not yet
				}
				@Override
				public void onFailure(Throwable ex) {
					future.setException(ex);
				}
			});
	return future;
}
 
Example 11
@Test
public void handshakeHandlerPassedToSockJsRegistration() {
	WebSocketHandler handler = new TextWebSocketHandler();
	HandshakeHandler handshakeHandler = new DefaultHandshakeHandler();

	this.registration.addHandler(handler, "/foo").setHandshakeHandler(handshakeHandler).withSockJS();

	List<Mapping> mappings = this.registration.getMappings();
	assertEquals(1, mappings.size());

	Mapping mapping = mappings.get(0);
	assertEquals(handler, mapping.webSocketHandler);
	assertEquals("/foo/**", mapping.path);
	assertNotNull(mapping.sockJsService);

	WebSocketTransportHandler transportHandler =
			(WebSocketTransportHandler) mapping.sockJsService.getTransportHandlers().get(TransportType.WEBSOCKET);
	assertSame(handshakeHandler, transportHandler.getHandshakeHandler());
}
 
Example 12
Source Project: spring-analysis-note   Source File: SockJsClient.java    License: MIT License 6 votes vote down vote up
@Override
public final ListenableFuture<WebSocketSession> doHandshake(
		WebSocketHandler handler, @Nullable WebSocketHttpHeaders headers, URI url) {

	Assert.notNull(handler, "WebSocketHandler is required");
	Assert.notNull(url, "URL is required");

	String scheme = url.getScheme();
	if (!supportedProtocols.contains(scheme)) {
		throw new IllegalArgumentException("Invalid scheme: '" + scheme + "'");
	}

	SettableListenableFuture<WebSocketSession> connectFuture = new SettableListenableFuture<>();
	try {
		SockJsUrlInfo sockJsUrlInfo = new SockJsUrlInfo(url);
		ServerInfo serverInfo = getServerInfo(sockJsUrlInfo, getHttpRequestHeaders(headers));
		createRequest(sockJsUrlInfo, headers, serverInfo).connect(handler, connectFuture);
	}
	catch (Throwable exception) {
		if (logger.isErrorEnabled()) {
			logger.error("Initial SockJS \"Info\" request to server failed, url=" + url, exception);
		}
		connectFuture.setException(exception);
	}
	return connectFuture;
}
 
Example 13
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                               Map<String, Object> attributes) throws Exception {
    if (request.getHeaders().containsKey("Sec-WebSocket-Extensions")) {
        request.getHeaders().set("Sec-WebSocket-Extensions", "permessage-deflate");
    }
    String ip = ((ServletServerHttpRequest) request).getServletRequest().getParameter("ip");
    String containerId = ((ServletServerHttpRequest) request).getServletRequest().getParameter("containerId");
    String width = ((ServletServerHttpRequest) request).getServletRequest().getParameter("width");
    String height = ((ServletServerHttpRequest) request).getServletRequest().getParameter("height");
    attributes.put("ip",ip);
    attributes.put("containerId",containerId);
    attributes.put("width",width);
    attributes.put("height",height);
    return super.beforeHandshake(request, response, wsHandler, attributes);
}
 
Example 14
@Test
public void interceptorsWithAllowedOrigins() {
	WebSocketHandler handler = new TextWebSocketHandler();
	HttpSessionHandshakeInterceptor interceptor = new HttpSessionHandshakeInterceptor();

	this.registration.addHandler(handler, "/foo").addInterceptors(interceptor).setAllowedOrigins("http://mydomain1.com");

	List<Mapping> mappings = this.registration.getMappings();
	assertEquals(1, mappings.size());

	Mapping mapping = mappings.get(0);
	assertEquals(handler, mapping.webSocketHandler);
	assertEquals("/foo", mapping.path);
	assertNotNull(mapping.interceptors);
	assertEquals(2, mapping.interceptors.length);
	assertEquals(interceptor, mapping.interceptors[0]);
	assertEquals(OriginHandshakeInterceptor.class, mapping.interceptors[1].getClass());
}
 
Example 15
@Test
public void interceptors() {
	WebSocketHandler handler = new TextWebSocketHandler();
	HttpSessionHandshakeInterceptor interceptor = new HttpSessionHandshakeInterceptor();

	this.registration.addHandler(handler, "/foo").addInterceptors(interceptor);

	List<Mapping> mappings = this.registration.getMappings();
	assertEquals(1, mappings.size());

	Mapping mapping = mappings.get(0);
	assertEquals(handler, mapping.webSocketHandler);
	assertEquals("/foo", mapping.path);
	assertNotNull(mapping.interceptors);
	assertEquals(2, mapping.interceptors.length);
	assertEquals(interceptor, mapping.interceptors[0]);
	assertEquals(OriginHandshakeInterceptor.class, mapping.interceptors[1].getClass());
}
 
Example 16
@Test
public void originMatchAll() throws Exception {
	Map<String, Object> attributes = new HashMap<>();
	WebSocketHandler wsHandler = Mockito.mock(WebSocketHandler.class);
	this.servletRequest.addHeader(HttpHeaders.ORIGIN, "https://mydomain1.com");
	OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor();
	interceptor.setAllowedOrigins(Collections.singletonList("*"));
	assertTrue(interceptor.beforeHandshake(request, response, wsHandler, attributes));
	assertNotEquals(servletResponse.getStatus(), HttpStatus.FORBIDDEN.value());
}
 
Example 17
public void connect(WebSocketHandler handler, SettableListenableFuture<WebSocketSession> future) {
	if (logger.isTraceEnabled()) {
		logger.trace("Starting " + this);
	}
	ConnectCallback connectCallback = new ConnectCallback(handler, future);
	scheduleConnectTimeoutTask(connectCallback);
	this.transport.connect(this, handler).addCallback(connectCallback);
}
 
Example 18
private void destroyHandler(WebSocketSession session) {
	WebSocketHandler handler = this.handlers.remove(session);
	try {
		if (handler != null) {
			this.provider.destroy(handler);
		}
	}
	catch (Throwable ex) {
		if (logger.isWarnEnabled()) {
			logger.warn("Error while destroying " + handler, ex);
		}
	}
}
 
Example 19
public Mapping(WebSocketHandler handler, String path, SockJsService sockJsService) {
	this.webSocketHandler = handler;
	this.path = path;
	this.handshakeHandler = null;
	this.interceptors = null;
	this.sockJsService = (DefaultSockJsService) sockJsService;
}
 
Example 20
Source Project: java-technology-stack   Source File: AbstractSockJsSessionTests.java    License: MIT License 5 votes vote down vote up
@Before
public void setUp() {
	this.webSocketHandler = mock(WebSocketHandler.class);
	this.taskScheduler = mock(TaskScheduler.class);

	this.sockJsConfig = new StubSockJsServiceConfig();
	this.sockJsConfig.setTaskScheduler(this.taskScheduler);

	this.session = initSockJsSession();
}
 
Example 21
Source Project: spring-analysis-note   Source File: AbstractWebSocketClient.java    License: MIT License 5 votes vote down vote up
@Override
public final ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler,
		@Nullable WebSocketHttpHeaders headers, URI uri) {

	Assert.notNull(webSocketHandler, "WebSocketHandler must not be null");
	assertUri(uri);

	if (logger.isDebugEnabled()) {
		logger.debug("Connecting to " + uri);
	}

	HttpHeaders headersToUse = new HttpHeaders();
	if (headers != null) {
		headers.forEach((header, values) -> {
			if (values != null && !specialHeaders.contains(header.toLowerCase())) {
				headersToUse.put(header, values);
			}
		});
	}

	List<String> subProtocols =
			(headers != null ? headers.getSecWebSocketProtocol() : Collections.emptyList());
	List<WebSocketExtension> extensions =
			(headers != null ? headers.getSecWebSocketExtensions() : Collections.emptyList());

	return doHandshakeInternal(webSocketHandler, headersToUse, uri, subProtocols, extensions,
			Collections.emptyMap());
}
 
Example 22
@Test
public void sameOriginMatchWithAllowedOrigins() throws Exception {
	Map<String, Object> attributes = new HashMap<String, Object>();
	WebSocketHandler wsHandler = Mockito.mock(WebSocketHandler.class);
	this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain2.com");
	this.servletRequest.setServerName("mydomain2.com");
	OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor(Arrays.asList("http://mydomain1.com"));
	assertTrue(interceptor.beforeHandshake(request, response, wsHandler, attributes));
	assertNotEquals(servletResponse.getStatus(), HttpStatus.FORBIDDEN.value());
}
 
Example 23
@Test
public void originValueNoMatch() throws Exception {
	Map<String, Object> attributes = new HashMap<>();
	WebSocketHandler wsHandler = Mockito.mock(WebSocketHandler.class);
	this.servletRequest.addHeader(HttpHeaders.ORIGIN, "https://mydomain1.com");
	List<String> allowed = Collections.singletonList("https://mydomain2.com");
	OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor(allowed);
	assertFalse(interceptor.beforeHandshake(request, response, wsHandler, attributes));
	assertEquals(servletResponse.getStatus(), HttpStatus.FORBIDDEN.value());
}
 
Example 24
Source Project: SpringBootBucket   Source File: WebSocketInterceptor.java    License: MIT License 5 votes vote down vote up
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse arg1,
                               WebSocketHandler arg2, Map<String, Object> arg3) throws Exception {
    // 将ServerHttpRequest转换成request请求相关的类,用来获取request域中的用户信息
    if (request instanceof ServletServerHttpRequest) {
        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
        HttpServletRequest httpRequest = servletRequest.getServletRequest();
    }
    logger.info("beforeHandshake完成");
    return true;
}
 
Example 25
private void handleRequestAndExpectFailure() throws Exception {
	resetResponse();

	WebSocketHandler wsHandler = mock(WebSocketHandler.class);
	AbstractSockJsSession session = new TestHttpSockJsSession("1", new StubSockJsServiceConfig(), wsHandler, null);

	new XhrReceivingTransportHandler().handleRequest(this.request, this.response, wsHandler, session);

	assertEquals(500, this.servletResponse.getStatus());
	verifyNoMoreInteractions(wsHandler);
}
 
Example 26
@Test
public void sameOriginMatchWithEmptyAllowedOrigins() throws Exception {
	Map<String, Object> attributes = new HashMap<>();
	WebSocketHandler wsHandler = Mockito.mock(WebSocketHandler.class);
	this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain2.com");
	this.servletRequest.setServerName("mydomain2.com");
	OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor(Collections.emptyList());
	assertTrue(interceptor.beforeHandshake(request, response, wsHandler, attributes));
	assertNotEquals(servletResponse.getStatus(), HttpStatus.FORBIDDEN.value());
}
 
Example 27
Source Project: java-technology-stack   Source File: AbstractHandshakeHandler.java    License: MIT License 5 votes vote down vote up
/**
 * Perform the sub-protocol negotiation based on requested and supported sub-protocols.
 * For the list of supported sub-protocols, this method first checks if the target
 * WebSocketHandler is a {@link SubProtocolCapable} and then also checks if any
 * sub-protocols have been explicitly configured with
 * {@link #setSupportedProtocols(String...)}.
 * @param requestedProtocols the requested sub-protocols
 * @param webSocketHandler the WebSocketHandler that will be used
 * @return the selected protocols or {@code null}
 * @see #determineHandlerSupportedProtocols(WebSocketHandler)
 */
@Nullable
protected String selectProtocol(List<String> requestedProtocols, WebSocketHandler webSocketHandler) {
	List<String> handlerProtocols = determineHandlerSupportedProtocols(webSocketHandler);
	for (String protocol : requestedProtocols) {
		if (handlerProtocols.contains(protocol.toLowerCase())) {
			return protocol;
		}
		if (this.supportedProtocols.contains(protocol.toLowerCase())) {
			return protocol;
		}
	}
	return null;
}
 
Example 28
@Test
public void clientLifecycle() throws Exception {
	TestLifecycleWebSocketClient client = new TestLifecycleWebSocketClient(false);
	WebSocketHandler handler = new TextWebSocketHandler();
	WebSocketConnectionManager manager = new WebSocketConnectionManager(client, handler , "/a");

	manager.startInternal();
	assertTrue(client.isRunning());

	manager.stopInternal();
	assertFalse(client.isRunning());
}
 
Example 29
@Bean
public HandlerMapping stompWebSocketHandlerMapping() {
	WebSocketHandler handler = decorateWebSocketHandler(subProtocolWebSocketHandler());
	WebMvcStompEndpointRegistry registry = new WebMvcStompEndpointRegistry(
			handler, getTransportRegistration(), messageBrokerTaskScheduler());
	ApplicationContext applicationContext = getApplicationContext();
	if (applicationContext != null) {
		registry.setApplicationContext(applicationContext);
	}
	registerStompEndpoints(registry);
	return registry.getHandlerMapping();
}
 
Example 30
@Override
public ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler handler,
		WebSocketHttpHeaders headers, URI uri) {

	this.webSocketHandler = handler;
	this.headers = headers;
	this.uri = uri;
	return new ListenableFutureTask<>(() -> null);
}