1
2
3
4
5
6
7
8
9
10
11 package org.eclipse.jgit.junit.http;
12
13 import java.net.URI;
14 import java.net.URISyntaxException;
15
16 import javax.servlet.http.HttpServletRequest;
17
18 import org.eclipse.jetty.servlet.ServletContextHandler;
19 import org.eclipse.jetty.servlet.ServletHolder;
20 import org.eclipse.jgit.errors.RepositoryNotFoundException;
21 import org.eclipse.jgit.http.server.GitServlet;
22 import org.eclipse.jgit.lib.Repository;
23 import org.eclipse.jgit.transport.URIish;
24
25
26
27
28
29 public class SimpleHttpServer {
30
31 AppServer server;
32
33 private final Repository db;
34
35 private URIish uri;
36
37 private URIish secureUri;
38
39
40
41
42
43
44 public SimpleHttpServer(Repository repository) {
45 this(repository, false);
46 }
47
48
49
50
51
52
53
54 public SimpleHttpServer(Repository repository, boolean withSsl) {
55 this.db = repository;
56 server = new AppServer(0, withSsl ? 0 : -1);
57 }
58
59
60
61
62
63
64 public void start() throws Exception {
65 ServletContextHandler sBasic = server.authBasic(smart("/sbasic"));
66 server.setUp();
67 final String srcName = db.getDirectory().getName();
68 uri = toURIish(sBasic, srcName);
69 int sslPort = server.getSecurePort();
70 if (sslPort > 0) {
71 secureUri = uri.setPort(sslPort).setScheme("https");
72 }
73 }
74
75
76
77
78
79
80 public void stop() throws Exception {
81 server.tearDown();
82 }
83
84
85
86
87
88
89 public URIish getUri() {
90 return uri;
91 }
92
93
94
95
96
97
98 public URIish getSecureUri() {
99 return secureUri;
100 }
101
102 private ServletContextHandler smart(String path) {
103 GitServlet gs = new GitServlet();
104 gs.setRepositoryResolver((HttpServletRequest req, String name) -> {
105 if (!name.equals(nameOf(db))) {
106 throw new RepositoryNotFoundException(name);
107 }
108 db.incrementOpen();
109 return db;
110 });
111
112 ServletContextHandler ctx = server.addContext(path);
113 ctx.addServlet(new ServletHolder(gs), "/*");
114 return ctx;
115 }
116
117 private static String nameOf(Repository db) {
118 return db.getDirectory().getName();
119 }
120
121 private URIish toURIish(String path) throws URISyntaxException {
122 URI u = server.getURI().resolve(path);
123 return new URIish(u.toString());
124 }
125
126 private URIish toURIish(ServletContextHandler app, String name)
127 throws URISyntaxException {
128 String p = app.getContextPath();
129 if (!p.endsWith("/") && !name.startsWith("/"))
130 p += "/";
131 p += name;
132 return toURIish(p);
133 }
134 }