1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.shiro.test;
20
21 import com.gargoylesoftware.htmlunit.WebClient;
22 import static org.junit.Assert.assertTrue;
23 import org.junit.Before;
24 import org.junit.BeforeClass;
25 import org.mortbay.jetty.Connector;
26 import org.mortbay.jetty.Server;
27 import org.mortbay.jetty.nio.SelectChannelConnector;
28 import org.mortbay.jetty.webapp.WebAppContext;
29
30 import java.net.BindException;
31
32 public abstract class AbstractContainerTest {
33 public static final int MAX_PORT = 9200;
34
35 protected static PauseableServer server;
36
37 private static int port = 9180;
38
39 protected final WebClient webClient = new WebClient();
40
41 @BeforeClass
42 public static void startContainer() throws Exception {
43 while (server == null && port < MAX_PORT) {
44 try {
45 server = createAndStartServer(port);
46 } catch (BindException e) {
47 System.err.printf("Unable to listen on port %d. Trying next port.", port);
48 port++;
49 }
50 }
51 assertTrue(server.isStarted());
52 }
53
54 private static PauseableServer createAndStartServer(final int port) throws Exception {
55 PauseableServer server = new PauseableServer();
56 Connector connector = new SelectChannelConnector();
57 connector.setPort(port);
58 server.setConnectors(new Connector[]{connector});
59 server.setHandler(new WebAppContext("src/main/webapp", "/"));
60 server.start();
61 return server;
62 }
63
64 protected static String getBaseUri() {
65 return "http://localhost:" + port + "/";
66 }
67
68 @Before
69 public void beforeTest() {
70 webClient.setThrowExceptionOnFailingStatusCode(true);
71 }
72
73 public void pauseServer(boolean paused) {
74 if (server != null) server.pause(paused);
75 }
76
77 public static class PauseableServer extends Server {
78 public synchronized void pause(boolean paused) {
79 try {
80 if (paused) for (Connector connector : getConnectors())
81 connector.stop();
82 else for (Connector connector : getConnectors())
83 connector.start();
84 } catch (Exception e) {
85 }
86 }
87 }
88 }