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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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 java.io.IOException;
  45. import java.net.InetAddress;
  46. import java.net.URI;
  47. import java.net.URISyntaxException;
  48. import java.net.UnknownHostException;
  49. import java.util.ArrayList;
  50. import java.util.List;
  51. import junit.framework.Assert;
  52. import org.eclipse.jetty.http.security.Constraint;
  53. import org.eclipse.jetty.http.security.Password;
  54. import org.eclipse.jetty.security.Authenticator;
  55. import org.eclipse.jetty.security.ConstraintMapping;
  56. import org.eclipse.jetty.security.ConstraintSecurityHandler;
  57. import org.eclipse.jetty.security.MappedLoginService;
  58. import org.eclipse.jetty.security.authentication.BasicAuthenticator;
  59. import org.eclipse.jetty.server.Connector;
  60. import org.eclipse.jetty.server.Server;
  61. import org.eclipse.jetty.server.UserIdentity;
  62. import org.eclipse.jetty.server.handler.ContextHandlerCollection;
  63. import org.eclipse.jetty.server.nio.SelectChannelConnector;
  64. import org.eclipse.jetty.servlet.ServletContextHandler;
  65. import org.eclipse.jetty.util.thread.QueuedThreadPool;
  66. import org.eclipse.jgit.transport.URIish;
  67. /**
  68. * Tiny web application server for unit testing.
  69. * <p>
  70. * Tests should start the server in their {@code setUp()} method and stop the
  71. * server in their {@code tearDown()} method. Only while started the server's
  72. * URL and/or port number can be obtained.
  73. */
  74. public class AppServer {
  75. /** Realm name for the secure access areas. */
  76. public static final String realm = "Secure Area";
  77. /** Username for secured access areas. */
  78. public static final String username = "agitter";
  79. /** Password for {@link #username} in secured access areas. */
  80. public static final String password = "letmein";
  81. static {
  82. // Install a logger that throws warning messages.
  83. //
  84. final String prop = "org.eclipse.jetty.util.log.class";
  85. System.setProperty(prop, RecordingLogger.class.getName());
  86. }
  87. private final Server server;
  88. private final Connector connector;
  89. private final ContextHandlerCollection contexts;
  90. private final TestRequestLog log;
  91. public AppServer() {
  92. connector = new SelectChannelConnector();
  93. connector.setPort(0);
  94. try {
  95. final InetAddress me = InetAddress.getByName("localhost");
  96. connector.setHost(me.getHostAddress());
  97. } catch (UnknownHostException e) {
  98. throw new RuntimeException("Cannot find localhost", e);
  99. }
  100. // We need a handful of threads in the thread pool, otherwise
  101. // our tests will deadlock when they can't open enough requests.
  102. // In theory we only need 1 concurrent connection at a time, but
  103. // I suspect the JRE isn't doing request pipelining on existing
  104. // connections like we want it to.
  105. //
  106. final QueuedThreadPool pool = new QueuedThreadPool();
  107. pool.setMinThreads(1);
  108. pool.setMaxThreads(4);
  109. pool.setMaxQueued(8);
  110. contexts = new ContextHandlerCollection();
  111. log = new TestRequestLog();
  112. log.setHandler(contexts);
  113. server = new Server();
  114. server.setConnectors(new Connector[] { connector });
  115. server.setThreadPool(pool);
  116. server.setHandler(log);
  117. server.setStopAtShutdown(false);
  118. server.setGracefulShutdown(0);
  119. }
  120. /**
  121. * Create a new servlet context within the server.
  122. * <p>
  123. * This method should be invoked before the server is started, once for each
  124. * context the caller wants to register.
  125. *
  126. * @param path
  127. * path of the context; use "/" for the root context if binding
  128. * to the root is desired.
  129. * @return the context to add servlets into.
  130. */
  131. public ServletContextHandler addContext(String path) {
  132. assertNotYetSetUp();
  133. if ("".equals(path))
  134. path = "/";
  135. ServletContextHandler ctx = new ServletContextHandler();
  136. ctx.setContextPath(path);
  137. contexts.addHandler(ctx);
  138. return ctx;
  139. }
  140. public ServletContextHandler authBasic(ServletContextHandler ctx) {
  141. assertNotYetSetUp();
  142. auth(ctx, new BasicAuthenticator());
  143. return ctx;
  144. }
  145. private void auth(ServletContextHandler ctx, Authenticator authType) {
  146. final String role = "can-access";
  147. MappedLoginService users = new MappedLoginService() {
  148. @Override
  149. protected UserIdentity loadUser(String who) {
  150. return null;
  151. }
  152. @Override
  153. protected void loadUsers() throws IOException {
  154. putUser(username, new Password(password), new String[] { role });
  155. }
  156. };
  157. ConstraintMapping cm = new ConstraintMapping();
  158. cm.setConstraint(new Constraint());
  159. cm.getConstraint().setAuthenticate(true);
  160. cm.getConstraint().setDataConstraint(Constraint.DC_NONE);
  161. cm.getConstraint().setRoles(new String[] { role });
  162. cm.setPathSpec("/*");
  163. ConstraintSecurityHandler sec = new ConstraintSecurityHandler();
  164. sec.setStrict(false);
  165. sec.setRealmName(realm);
  166. sec.setAuthenticator(authType);
  167. sec.setLoginService(users);
  168. sec.setConstraintMappings(new ConstraintMapping[] { cm });
  169. sec.setHandler(ctx);
  170. contexts.removeHandler(ctx);
  171. contexts.addHandler(sec);
  172. }
  173. /**
  174. * Start the server on a random local port.
  175. *
  176. * @throws Exception
  177. * the server cannot be started, testing is not possible.
  178. */
  179. public void setUp() throws Exception {
  180. RecordingLogger.clear();
  181. log.clear();
  182. server.start();
  183. }
  184. /**
  185. * Shutdown the server.
  186. *
  187. * @throws Exception
  188. * the server refuses to halt, or wasn't running.
  189. */
  190. public void tearDown() throws Exception {
  191. RecordingLogger.clear();
  192. log.clear();
  193. server.stop();
  194. }
  195. /**
  196. * Get the URI to reference this server.
  197. * <p>
  198. * The returned URI includes the proper host name and port number, but does
  199. * not contain a path.
  200. *
  201. * @return URI to reference this server's root context.
  202. */
  203. public URI getURI() {
  204. assertAlreadySetUp();
  205. String host = connector.getHost();
  206. if (host.contains(":") && !host.startsWith("["))
  207. host = "[" + host + "]";
  208. final String uri = "http://" + host + ":" + getPort();
  209. try {
  210. return new URI(uri);
  211. } catch (URISyntaxException e) {
  212. throw new RuntimeException("Unexpected URI error on " + uri, e);
  213. }
  214. }
  215. /** @return the local port number the server is listening on. */
  216. public int getPort() {
  217. assertAlreadySetUp();
  218. return ((SelectChannelConnector) connector).getLocalPort();
  219. }
  220. /** @return all requests since the server was started. */
  221. public List<AccessEvent> getRequests() {
  222. return new ArrayList<AccessEvent>(log.getEvents());
  223. }
  224. /**
  225. * @param base
  226. * base URI used to access the server.
  227. * @param path
  228. * the path to locate requests for, relative to {@code base}.
  229. * @return all requests which match the given path.
  230. */
  231. public List<AccessEvent> getRequests(URIish base, String path) {
  232. return getRequests(HttpTestCase.join(base, path));
  233. }
  234. /**
  235. * @param path
  236. * the path to locate requests for.
  237. * @return all requests which match the given path.
  238. */
  239. public List<AccessEvent> getRequests(String path) {
  240. ArrayList<AccessEvent> r = new ArrayList<AccessEvent>();
  241. for (AccessEvent event : log.getEvents()) {
  242. if (event.getPath().equals(path)) {
  243. r.add(event);
  244. }
  245. }
  246. return r;
  247. }
  248. private void assertNotYetSetUp() {
  249. Assert.assertFalse("server is not running", server.isRunning());
  250. }
  251. private void assertAlreadySetUp() {
  252. Assert.assertTrue("server is running", server.isRunning());
  253. }
  254. }