View Javadoc
1   /*
2    * Copyright 2002-2014 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.web.socket;
18  
19  import java.util.EnumSet;
20  import javax.servlet.DispatcherType;
21  import javax.servlet.Filter;
22  
23  import org.eclipse.jetty.server.Server;
24  import org.eclipse.jetty.servlet.FilterHolder;
25  import org.eclipse.jetty.servlet.ServletContextHandler;
26  import org.eclipse.jetty.servlet.ServletHolder;
27  
28  import org.springframework.util.Assert;
29  import org.springframework.util.SocketUtils;
30  import org.springframework.web.context.WebApplicationContext;
31  import org.springframework.web.servlet.DispatcherServlet;
32  
33  /**
34   * Jetty based {@link WebSocketTestServer}.
35   *
36   * @author Rossen Stoyanchev
37   */
38  public class JettyWebSocketTestServer implements WebSocketTestServer {
39  
40  	private Server jettyServer;
41  
42  	private int port = -1;
43  
44  
45  	@Override
46  	public void setup() {
47  		this.port = SocketUtils.findAvailableTcpPort();
48  		this.jettyServer = new Server(this.port);
49  	}
50  
51  	@Override
52  	public int getPort() {
53  		return this.port;
54  	}
55  
56  	@Override
57  	public void deployConfig(WebApplicationContext cxt, Filter... filters) {
58  		Assert.state(this.port != -1, "setup() was never called.");
59  		ServletContextHandler contextHandler = new ServletContextHandler();
60  		ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(cxt));
61  		contextHandler.addServlet(servletHolder, "/");
62  		for (Filter filter : filters) {
63  			contextHandler.addFilter(new FilterHolder(filter), "/*", getDispatcherTypes());
64  		}
65  		this.jettyServer.setHandler(contextHandler);
66  	}
67  
68  	private EnumSet<DispatcherType> getDispatcherTypes() {
69  		return EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ASYNC);
70  	}
71  
72  	@Override
73  	public void undeployConfig() {
74  		// Stopping jetty will undeploy the servlet
75  	}
76  
77  	@Override
78  	public void start() throws Exception {
79  		this.jettyServer.start();
80  	}
81  
82  	@Override
83  	public void stop() throws Exception {
84  		if (this.jettyServer.isRunning()) {
85  			this.jettyServer.setStopTimeout(5000);
86  			this.jettyServer.stop();
87  		}
88  	}
89  
90  }