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