HandlersBeanDefinitionParserTests.java 13.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * 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.
 */

17
package org.springframework.web.socket.config;
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
37
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
import org.springframework.web.socket.server.HandshakeFailureException;
import org.springframework.web.socket.server.HandshakeHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.support.WebSocketHttpRequestHandler;
import org.springframework.web.socket.sockjs.SockJsHttpRequestHandler;
import org.springframework.web.socket.sockjs.SockJsService;
import org.springframework.web.socket.sockjs.transport.handler.DefaultSockJsService;
import org.springframework.web.socket.sockjs.transport.handler.EventSourceTransportHandler;
import org.springframework.web.socket.sockjs.transport.handler.HtmlFileTransportHandler;
import org.springframework.web.socket.sockjs.transport.handler.JsonpPollingTransportHandler;
import org.springframework.web.socket.sockjs.transport.handler.JsonpReceivingTransportHandler;
import org.springframework.web.socket.sockjs.transport.handler.WebSocketTransportHandler;
import org.springframework.web.socket.sockjs.transport.handler.XhrPollingTransportHandler;
import org.springframework.web.socket.sockjs.transport.handler.XhrReceivingTransportHandler;
import org.springframework.web.socket.sockjs.transport.handler.XhrStreamingTransportHandler;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

/**
 * Test fixture for HandlersBeanDefinitionParser.
R
Rossen Stoyanchev 已提交
67
 * See test configuration files websocket-config-handlers-*.xml.
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
 *
 * @author Brian Clozel
 */
public class HandlersBeanDefinitionParserTests {

	private GenericWebApplicationContext appContext;


	@Before
	public void setup() {
		appContext = new GenericWebApplicationContext();
	}

	@Test
	public void webSocketHandlers() {
		loadBeanDefinitions("websocket-config-handlers.xml");
		Map<String, HandlerMapping> handlersMap = appContext.getBeansOfType(HandlerMapping.class);
		assertNotNull(handlersMap);
		assertThat(handlersMap.values(), Matchers.hasSize(2));

		for(HandlerMapping handlerMapping : handlersMap.values()) {
			assertTrue(handlerMapping instanceof SimpleUrlHandlerMapping);
			SimpleUrlHandlerMapping urlHandlerMapping = (SimpleUrlHandlerMapping) handlerMapping;

			if(urlHandlerMapping.getUrlMap().keySet().contains("/foo")) {
				assertThat(urlHandlerMapping.getUrlMap().keySet(),Matchers.contains("/foo","/bar"));
				WebSocketHttpRequestHandler handler = (WebSocketHttpRequestHandler)
						urlHandlerMapping.getUrlMap().get("/foo");
				assertNotNull(handler);
				checkDelegateHandlerType(handler.getWebSocketHandler(), FooWebSocketHandler.class);
				HandshakeHandler handshakeHandler = (HandshakeHandler)
						new DirectFieldAccessor(handler).getPropertyValue("handshakeHandler");
				assertNotNull(handshakeHandler);
				assertTrue(handshakeHandler instanceof DefaultHandshakeHandler);
			}
			else {
				assertThat(urlHandlerMapping.getUrlMap().keySet(),Matchers.contains("/test"));
				WebSocketHttpRequestHandler handler = (WebSocketHttpRequestHandler)
						urlHandlerMapping.getUrlMap().get("/test");
				assertNotNull(handler);
				checkDelegateHandlerType(handler.getWebSocketHandler(), TestWebSocketHandler.class);
				HandshakeHandler handshakeHandler = (HandshakeHandler)
						new DirectFieldAccessor(handler).getPropertyValue("handshakeHandler");
				assertNotNull(handshakeHandler);
				assertTrue(handshakeHandler instanceof DefaultHandshakeHandler);
			}
		}
	}

	@Test
	public void websocketHandlersAttributes() {
		loadBeanDefinitions("websocket-config-handlers-attributes.xml");
		HandlerMapping handlerMapping = appContext.getBean(HandlerMapping.class);
		assertNotNull(handlerMapping);
		assertTrue(handlerMapping instanceof SimpleUrlHandlerMapping);

		SimpleUrlHandlerMapping urlHandlerMapping = (SimpleUrlHandlerMapping) handlerMapping;
		assertEquals(2, urlHandlerMapping.getOrder());

		WebSocketHttpRequestHandler handler = (WebSocketHttpRequestHandler) urlHandlerMapping.getUrlMap().get("/foo");
		assertNotNull(handler);
		checkDelegateHandlerType(handler.getWebSocketHandler(), FooWebSocketHandler.class);
		HandshakeHandler handshakeHandler = (HandshakeHandler)
				new DirectFieldAccessor(handler).getPropertyValue("handshakeHandler");
		assertNotNull(handshakeHandler);
		assertTrue(handshakeHandler instanceof TestHandshakeHandler);
		List<HandshakeInterceptor> handshakeInterceptorList = (List<HandshakeInterceptor>)
				new DirectFieldAccessor(handler).getPropertyValue("interceptors");
		assertNotNull(handshakeInterceptorList);
		assertThat(handshakeInterceptorList, Matchers.contains(
				Matchers.instanceOf(FooTestInterceptor.class), Matchers.instanceOf(BarTestInterceptor.class)));

		handler = (WebSocketHttpRequestHandler) urlHandlerMapping.getUrlMap().get("/test");
		assertNotNull(handler);
		checkDelegateHandlerType(handler.getWebSocketHandler(), TestWebSocketHandler.class);
		handshakeHandler = (HandshakeHandler) new DirectFieldAccessor(handler).getPropertyValue("handshakeHandler");
		assertNotNull(handshakeHandler);
		assertTrue(handshakeHandler instanceof TestHandshakeHandler);
		handshakeInterceptorList = (List<HandshakeInterceptor>)
				new DirectFieldAccessor(handler).getPropertyValue("interceptors");
		assertNotNull(handshakeInterceptorList);
		assertThat(handshakeInterceptorList, Matchers.contains(
				Matchers.instanceOf(FooTestInterceptor.class), Matchers.instanceOf(BarTestInterceptor.class)));

	}

	@Test
	public void sockJSSupport() {
		loadBeanDefinitions("websocket-config-handlers-sockjs.xml");
		SimpleUrlHandlerMapping handlerMapping = appContext.getBean(SimpleUrlHandlerMapping.class);
		assertNotNull(handlerMapping);
		SockJsHttpRequestHandler testHandler = (SockJsHttpRequestHandler) handlerMapping.getUrlMap().get("/test/**");
		assertNotNull(testHandler);
		checkDelegateHandlerType(testHandler.getWebSocketHandler(), TestWebSocketHandler.class);
		SockJsService testSockJsService = testHandler.getSockJsService();
		SockJsHttpRequestHandler fooHandler = (SockJsHttpRequestHandler) handlerMapping.getUrlMap().get("/foo/**");
		assertNotNull(fooHandler);
		checkDelegateHandlerType(fooHandler.getWebSocketHandler(), FooWebSocketHandler.class);

		SockJsService sockJsService = fooHandler.getSockJsService();
		assertNotNull(sockJsService);
		assertEquals(testSockJsService, sockJsService);

		assertThat(sockJsService, Matchers.instanceOf(DefaultSockJsService.class));
		DefaultSockJsService defaultSockJsService = (DefaultSockJsService) sockJsService;
		assertThat(defaultSockJsService.getTaskScheduler(), Matchers.instanceOf(ThreadPoolTaskScheduler.class));
		assertThat(defaultSockJsService.getTransportHandlers().values(), Matchers.containsInAnyOrder(
				Matchers.instanceOf(XhrPollingTransportHandler.class),
				Matchers.instanceOf(XhrReceivingTransportHandler.class),
				Matchers.instanceOf(JsonpPollingTransportHandler.class),
				Matchers.instanceOf(JsonpReceivingTransportHandler.class),
				Matchers.instanceOf(XhrStreamingTransportHandler.class),
				Matchers.instanceOf(EventSourceTransportHandler.class),
				Matchers.instanceOf(HtmlFileTransportHandler.class),
				Matchers.instanceOf(WebSocketTransportHandler.class)));

	}

	@Test
	public void sockJSAttributesSupport() {
		loadBeanDefinitions("websocket-config-handlers-sockjs-attributes.xml");
		SimpleUrlHandlerMapping handlerMapping = appContext.getBean(SimpleUrlHandlerMapping.class);
		assertNotNull(handlerMapping);
		SockJsHttpRequestHandler handler = (SockJsHttpRequestHandler) handlerMapping.getUrlMap().get("/test/**");
		assertNotNull(handler);
		checkDelegateHandlerType(handler.getWebSocketHandler(), TestWebSocketHandler.class);
		SockJsService sockJsService = handler.getSockJsService();
		assertNotNull(sockJsService);
		assertThat(sockJsService, Matchers.instanceOf(DefaultSockJsService.class));
		DefaultSockJsService defaultSockJsService = (DefaultSockJsService) sockJsService;
		assertThat(defaultSockJsService.getTaskScheduler(), Matchers.instanceOf(TestTaskScheduler.class));
		assertThat(defaultSockJsService.getTransportHandlers().values(), Matchers.containsInAnyOrder(
				Matchers.instanceOf(XhrPollingTransportHandler.class),
				Matchers.instanceOf(XhrStreamingTransportHandler.class)));

		assertEquals("testSockJsService", defaultSockJsService.getName());
		assertFalse(defaultSockJsService.isWebSocketEnabled());
		assertFalse(defaultSockJsService.isSessionCookieNeeded());
		assertEquals(2048, defaultSockJsService.getStreamBytesLimit());
		assertEquals(256, defaultSockJsService.getDisconnectDelay());
		assertEquals(1024, defaultSockJsService.getHttpMessageCacheSize());
		assertEquals(20, defaultSockJsService.getHeartbeatTime());
	}

	private void loadBeanDefinitions(String fileName) {
		XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
		ClassPathResource resource = new ClassPathResource(fileName, HandlersBeanDefinitionParserTests.class);
		reader.loadBeanDefinitions(resource);
		appContext.refresh();
	}

	private void checkDelegateHandlerType(WebSocketHandler handler, Class<?> handlerClass) {
		do {
			handler = (WebSocketHandler) new DirectFieldAccessor(handler).getPropertyValue("delegate");
		}
		while (new DirectFieldAccessor(handler).isReadableProperty("delegate"));
		assertTrue(handlerClass.isInstance(handler));
	}

}

class TestWebSocketHandler implements WebSocketHandler {
R
Rossen Stoyanchev 已提交
230

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {}

	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {}

	@Override
	public boolean supportsPartialMessages() { return false; }
}

class FooWebSocketHandler extends TestWebSocketHandler { }

class TestHandshakeHandler implements HandshakeHandler {
	@Override
	public boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response,
	                           WebSocketHandler wsHandler, Map<String, Object> attributes)
			throws HandshakeFailureException {
		return false;
	}
}

class FooTestInterceptor implements HandshakeInterceptor {
	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
	                               WebSocketHandler wsHandler, Map<String, Object> attributes)
			throws Exception {
		return false;
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
	                           WebSocketHandler wsHandler, Exception exception) {
	}
}

class BarTestInterceptor extends FooTestInterceptor {}

class TestTaskScheduler implements TaskScheduler {
	@Override
	public ScheduledFuture schedule(Runnable task, Trigger trigger) { return null; }

	@Override
	public ScheduledFuture schedule(Runnable task, Date startTime) { return null; }

	@Override
	public ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period) { return null; }

	@Override
	public ScheduledFuture scheduleAtFixedRate(Runnable task, long period) { return null; }

	@Override
	public ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay) { return null; }

	@Override
	public ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay) { return null; }
}