1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.index.reader;
20
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.net.HttpURLConnection;
24 import java.net.URI;
25 import java.net.http.HttpClient;
26 import java.net.http.HttpRequest;
27 import java.net.http.HttpResponse;
28
29 import static java.util.Objects.requireNonNull;
30
31
32
33
34
35 public class HttpResourceHandler implements ResourceHandler {
36 private final HttpClient client =
37 HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER).build();
38 private final URI root;
39
40 public HttpResourceHandler(final URI root) {
41 this.root = requireNonNull(root);
42 }
43
44 public Resource locate(final String name) {
45 return new HttpResource(name);
46 }
47
48 private class HttpResource implements Resource {
49 private final String name;
50
51 private HttpResource(final String name) {
52 this.name = name;
53 }
54
55 public InputStream read() throws IOException {
56 HttpRequest request =
57 HttpRequest.newBuilder().uri(root.resolve(name)).GET().build();
58 try {
59 HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
60 if (response.statusCode() == HttpURLConnection.HTTP_OK) {
61 return response.body();
62 } else {
63 throw new IOException("Unexpected response: " + response);
64 }
65 } catch (InterruptedException e) {
66 Thread.currentThread().interrupt();
67 throw new IOException(e);
68 }
69 }
70 }
71 }