You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AppServer.java 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. * Copyright (C) 2010, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.junit.http;
  44. import static org.junit.Assert.assertFalse;
  45. import static org.junit.Assert.assertTrue;
  46. import java.io.IOException;
  47. import java.net.InetAddress;
  48. import java.net.URI;
  49. import java.net.URISyntaxException;
  50. import java.net.UnknownHostException;
  51. import java.util.ArrayList;
  52. import java.util.List;
  53. import org.eclipse.jetty.http.security.Constraint;
  54. import org.eclipse.jetty.http.security.Password;
  55. import org.eclipse.jetty.security.Authenticator;
  56. import org.eclipse.jetty.security.ConstraintMapping;
  57. import org.eclipse.jetty.security.ConstraintSecurityHandler;
  58. import org.eclipse.jetty.security.MappedLoginService;
  59. import org.eclipse.jetty.security.authentication.BasicAuthenticator;
  60. import org.eclipse.jetty.server.Connector;
  61. import org.eclipse.jetty.server.Server;
  62. import org.eclipse.jetty.server.UserIdentity;
  63. import org.eclipse.jetty.server.handler.ContextHandlerCollection;
  64. import org.eclipse.jetty.server.nio.SelectChannelConnector;
  65. import org.eclipse.jetty.servlet.ServletContextHandler;
  66. import org.eclipse.jetty.util.thread.QueuedThreadPool;
  67. import org.eclipse.jgit.transport.URIish;
  68. /**
  69. * Tiny web application server for unit testing.
  70. * <p>
  71. * Tests should start the server in their {@code setUp()} method and stop the
  72. * server in their {@code tearDown()} method. Only while started the server's
  73. * URL and/or port number can be obtained.
  74. */
  75. public class AppServer {
  76. /** Realm name for the secure access areas. */
  77. public static final String realm = "Secure Area";
  78. /** Username for secured access areas. */
  79. public static final String username = "agitter";
  80. /** Password for {@link #username} in secured access areas. */
  81. public static final String password = "letmein";
  82. static {
  83. // Install a logger that throws warning messages.
  84. //
  85. final String prop = "org.eclipse.jetty.util.log.class";
  86. System.setProperty(prop, RecordingLogger.class.getName());
  87. }
  88. private final Server server;
  89. private final Connector connector;
  90. private final ContextHandlerCollection contexts;
  91. private final TestRequestLog log;
  92. public AppServer() {
  93. connector = new SelectChannelConnector();
  94. connector.setPort(0);
  95. try {
  96. final InetAddress me = InetAddress.getByName("localhost");
  97. connector.setHost(me.getHostAddress());
  98. } catch (UnknownHostException e) {
  99. throw new RuntimeException("Cannot find localhost", e);
  100. }
  101. // We need a handful of threads in the thread pool, otherwise
  102. // our tests will deadlock when they can't open enough requests.
  103. // In theory we only need 1 concurrent connection at a time, but
  104. // I suspect the JRE isn't doing request pipelining on existing
  105. // connections like we want it to.
  106. //
  107. final QueuedThreadPool pool = new QueuedThreadPool();
  108. pool.setMinThreads(1);
  109. pool.setMaxThreads(4);
  110. pool.setMaxQueued(8);
  111. contexts = new ContextHandlerCollection();
  112. log = new TestRequestLog();
  113. log.setHandler(contexts);
  114. server = new Server();
  115. server.setConnectors(new Connector[] { connector });
  116. server.setThreadPool(pool);
  117. server.setHandler(log);
  118. server.setStopAtShutdown(false);
  119. server.setGracefulShutdown(0);
  120. }
  121. /**
  122. * Create a new servlet context within the server.
  123. * <p>
  124. * This method should be invoked before the server is started, once for each
  125. * context the caller wants to register.
  126. *
  127. * @param path
  128. * path of the context; use "/" for the root context if binding
  129. * to the root is desired.
  130. * @return the context to add servlets into.
  131. */
  132. public ServletContextHandler addContext(String path) {
  133. assertNotYetSetUp();
  134. if ("".equals(path))
  135. path = "/";
  136. ServletContextHandler ctx = new ServletContextHandler();
  137. ctx.setContextPath(path);
  138. contexts.addHandler(ctx);
  139. return ctx;
  140. }
  141. public ServletContextHandler authBasic(ServletContextHandler ctx) {
  142. assertNotYetSetUp();
  143. auth(ctx, new BasicAuthenticator());
  144. return ctx;
  145. }
  146. private void auth(ServletContextHandler ctx, Authenticator authType) {
  147. final String role = "can-access";
  148. MappedLoginService users = new MappedLoginService() {
  149. @Override
  150. protected UserIdentity loadUser(String who) {
  151. return null;
  152. }
  153. @Override
  154. protected void loadUsers() throws IOException {
  155. putUser(username, new Password(password), new String[] { role });
  156. }
  157. };
  158. ConstraintMapping cm = new ConstraintMapping();
  159. cm.setConstraint(new Constraint());
  160. cm.getConstraint().setAuthenticate(true);
  161. cm.getConstraint().setDataConstraint(Constraint.DC_NONE);
  162. cm.getConstraint().setRoles(new String[] { role });
  163. cm.setPathSpec("/*");
  164. ConstraintSecurityHandler sec = new ConstraintSecurityHandler();
  165. sec.setStrict(false);
  166. sec.setRealmName(realm);
  167. sec.setAuthenticator(authType);
  168. sec.setLoginService(users);
  169. sec.setConstraintMappings(new ConstraintMapping[] { cm });
  170. sec.setHandler(ctx);
  171. contexts.removeHandler(ctx);
  172. contexts.addHandler(sec);
  173. }
  174. /**
  175. * Start the server on a random local port.
  176. *
  177. * @throws Exception
  178. * the server cannot be started, testing is not possible.
  179. */
  180. public void setUp() throws Exception {
  181. RecordingLogger.clear();
  182. log.clear();
  183. server.start();
  184. }
  185. /**
  186. * Shutdown the server.
  187. *
  188. * @throws Exception
  189. * the server refuses to halt, or wasn't running.
  190. */
  191. public void tearDown() throws Exception {
  192. RecordingLogger.clear();
  193. log.clear();
  194. server.stop();
  195. }
  196. /**
  197. * Get the URI to reference this server.
  198. * <p>
  199. * The returned URI includes the proper host name and port number, but does
  200. * not contain a path.
  201. *
  202. * @return URI to reference this server's root context.
  203. */
  204. public URI getURI() {
  205. assertAlreadySetUp();
  206. String host = connector.getHost();
  207. if (host.contains(":") && !host.startsWith("["))
  208. host = "[" + host + "]";
  209. final String uri = "http://" + host + ":" + getPort();
  210. try {
  211. return new URI(uri);
  212. } catch (URISyntaxException e) {
  213. throw new RuntimeException("Unexpected URI error on " + uri, e);
  214. }
  215. }
  216. /** @return the local port number the server is listening on. */
  217. public int getPort() {
  218. assertAlreadySetUp();
  219. return ((SelectChannelConnector) connector).getLocalPort();
  220. }
  221. /** @return all requests since the server was started. */
  222. public List<AccessEvent> getRequests() {
  223. return new ArrayList<AccessEvent>(log.getEvents());
  224. }
  225. /**
  226. * @param base
  227. * base URI used to access the server.
  228. * @param path
  229. * the path to locate requests for, relative to {@code base}.
  230. * @return all requests which match the given path.
  231. */
  232. public List<AccessEvent> getRequests(URIish base, String path) {
  233. return getRequests(HttpTestCase.join(base, path));
  234. }
  235. /**
  236. * @param path
  237. * the path to locate requests for.
  238. * @return all requests which match the given path.
  239. */
  240. public List<AccessEvent> getRequests(String path) {
  241. ArrayList<AccessEvent> r = new ArrayList<AccessEvent>();
  242. for (AccessEvent event : log.getEvents()) {
  243. if (event.getPath().equals(path)) {
  244. r.add(event);
  245. }
  246. }
  247. return r;
  248. }
  249. private void assertNotYetSetUp() {
  250. assertFalse("server is not running", server.isRunning());
  251. }
  252. private void assertAlreadySetUp() {
  253. assertTrue("server is running", server.isRunning());
  254. }
  255. }