1
|
|
|
package com.base.Http.Server; |
2
|
|
|
|
3
|
|
|
import com.base.Http.Request.Request; |
4
|
|
|
import com.base.Http.Response.Response; |
5
|
|
|
import com.base.Http.Server.Responses.NotFoundResponse; |
6
|
|
|
import com.base.Http.Server.Responses.ServerResponseInterface; |
7
|
|
|
|
8
|
|
|
import java.util.HashMap; |
9
|
|
|
import java.util.Map; |
10
|
|
|
|
11
|
|
|
public class TestHttpServer { |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Route Mappings. |
15
|
|
|
*/ |
16
|
|
|
private static Map<String, ServerResponseInterface> routeMappings; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Create new TestHttpServer. |
20
|
|
|
*/ |
21
|
|
|
public TestHttpServer() { |
22
|
|
|
TestHttpServer.routeMappings = new HashMap<>(); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Create new TestHttpServer with Route Mappings. |
27
|
|
|
* |
28
|
|
|
* @param mappings Route Mappings. |
29
|
|
|
*/ |
30
|
|
|
public TestHttpServer(Map<String, ServerResponseInterface> mappings) { |
31
|
|
|
TestHttpServer.routeMappings = mappings; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Handle the Request. |
36
|
|
|
* |
37
|
|
|
* @param request Request to Handle. |
38
|
|
|
* @param response Pre-instantiated Response. |
39
|
|
|
* @return Server Response. |
40
|
|
|
*/ |
41
|
|
|
public Response handle(Request request, Response response) { |
42
|
|
|
// Fetch (Dummy) Response from Server. |
43
|
|
|
ServerResponseInterface responseFromServer = |
44
|
|
|
TestHttpServer.getServerResponse( |
45
|
|
|
request.getMethod(), |
46
|
|
|
request.getUrl() |
47
|
|
|
); |
48
|
|
|
|
49
|
|
|
// No Response was fetched. |
50
|
|
|
if (responseFromServer == null) { |
51
|
|
|
ServerResponseInterface res = new NotFoundResponse(); |
52
|
|
|
return res.getResponse(request, response); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
// Get Response. |
56
|
|
|
return responseFromServer.getResponse(request, response); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Fetch Response for the given method-url combo. |
61
|
|
|
* |
62
|
|
|
* @param method Request Method. (GET|PUT|PATCH|POST|UPDATE|DELETE) |
63
|
|
|
* @param url Request URL. |
64
|
|
|
* @return (Dummy) Server Response. |
65
|
|
|
*/ |
66
|
|
|
private static ServerResponseInterface getServerResponse(String method, String url) { |
67
|
|
|
String signature = method.concat(" ").concat(url); |
68
|
|
|
return TestHttpServer.routeMappings.getOrDefault(signature, null); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|