-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Consumer.java
executable file
·51 lines (43 loc) · 1.63 KB
/
Consumer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package payment.consumer;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import payment.producer.Payment;
/**
*
* @author pthomas3
*/
public class Consumer {
private static final Logger logger = LoggerFactory.getLogger(Consumer.class);
private final String paymentServiceUrl;
private final ObjectMapper mapper = new ObjectMapper();
public Consumer(String paymentServiceUrl) {
this.paymentServiceUrl = paymentServiceUrl;
}
private HttpURLConnection getConnection(String path) throws Exception {
URL url = new URL(paymentServiceUrl + path);
return (HttpURLConnection) url.openConnection();
}
public Payment create(Payment payment) {
try {
HttpURLConnection con = getConnection("/payments");
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/json");
String json = mapper.writeValueAsString(payment);
IOUtils.write(json, con.getOutputStream(), "utf-8");
int status = con.getResponseCode();
if (status != 200) {
throw new RuntimeException("status code was " + status);
}
String content = IOUtils.toString(con.getInputStream(), StandardCharsets.UTF_8);
return mapper.readValue(content, Payment.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}