1 package com.github.davidmoten.aws.lw.client;
2
3 import java.io.Closeable;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.net.HttpURLConnection;
7 import java.util.List;
8 import java.util.Map;
9 import java.util.Optional;
10 import java.util.stream.Collectors;
11
12 public final class ResponseInputStream extends InputStream {
13
14 private final Closeable closeable;
15 private final int statusCode;
16 private final Map<String, List<String>> headers;
17 private final InputStream content;
18
19 public ResponseInputStream(HttpURLConnection connection, int statusCode,
20 Map<String, List<String>> headers, InputStream content) {
21 this(() -> connection.disconnect(), statusCode, headers, content);
22 }
23
24 public ResponseInputStream(Closeable closeable, int statusCode,
25 Map<String, List<String>> headers, InputStream content) {
26 this.closeable = closeable;
27 this.statusCode = statusCode;
28 this.headers = headers;
29 this.content = content;
30 }
31
32 @Override
33 public int read(byte[] b, int off, int len) throws IOException {
34 return content.read(b, off, len);
35 }
36
37 @Override
38 public int read() throws IOException {
39 return content.read();
40 }
41
42 @Override
43 public void close() throws IOException {
44 try {
45 content.close();
46 } finally {
47 closeable.close();
48 }
49 }
50
51 public int statusCode() {
52 return statusCode;
53 }
54
55 public Map<String, List<String>> headers() {
56 return headers;
57 }
58
59 public Optional<String> header(String name) {
60 for (String key : headers.keySet()) {
61 if (name.equalsIgnoreCase(key)) {
62 return Optional.of(headers.get(key).stream().collect(Collectors.joining(",")));
63 }
64 }
65 return Optional.empty();
66 }
67 }