1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.rribbit.dispatching;
17
18 import org.rribbit.Request;
19 import org.rribbit.Response;
20 import org.rribbit.processing.HttpRequestProcessorServlet;
21 import org.rribbit.util.Base64Util;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 import java.io.ByteArrayInputStream;
26 import java.net.URI;
27 import java.net.http.HttpClient;
28 import java.net.http.HttpRequest;
29 import java.net.http.HttpRequest.BodyPublishers;
30 import java.net.http.HttpResponse;
31 import java.net.http.HttpResponse.BodyHandlers;
32
33
34
35
36
37
38
39
40
41
42
43
44
45 public class HttpRequestDispatcher implements RequestDispatcher {
46
47 private static final Logger log = LoggerFactory.getLogger(HttpRequestDispatcher.class);
48
49 protected String url;
50
51
52
53
54 public HttpRequestDispatcher() {}
55
56
57
58
59
60
61
62
63
64
65 public HttpRequestDispatcher(String url) {
66 this.url = url;
67 }
68
69 @Override
70 public <T> Response<T> dispatchRequest(Request request) {
71
72 log.info("Dispatching HTTP Request");
73 try {
74 log.info("Encoding Request");
75 String requestString = Base64Util.encodeObject(request);
76
77 HttpRequest httpRequest = HttpRequest.newBuilder()
78 .uri(new URI(url))
79 .POST(BodyPublishers.ofString(requestString))
80 .build();
81
82 log.info("Dispatching encoded Request");
83 try(HttpClient httpClient = HttpClient.newHttpClient()) {
84 HttpResponse<String> httpResponse = httpClient.send(httpRequest, BodyHandlers.ofString());
85
86 log.info("Decoding Response");
87 Response<T> response = Base64Util.decodeInputStream(new ByteArrayInputStream(httpResponse.body().getBytes()));
88
89 log.info("Returning Response");
90 return response;
91 }
92 } catch(Exception e) {
93 log.error("Something went wrong during the Request. Below are some common errors that can occur in the stacktrace: ");
94 log.error("\tStreamCorruptedException: Indicates that the client does not understand the response from the server. This may mean that the client gets " +
95 "a 404 page back, which it cannot decode. Please see the client's logs to see the response that the client got from the server. Please " +
96 "also check the URL that you have given the client.");
97 log.error("\tEOFException: Indicates that the client does not get a response from the server. Please check the server logs to see what's wrong.");
98
99 throw new RuntimeException(e);
100 }
101 }
102
103 public String getUrl() {
104 return url;
105 }
106
107 public void setUrl(String url) {
108 this.url = url;
109 }
110 }