View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
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   * A trivial HTTP {@link ResourceHandler} that uses {@link URI} to fetch remote content. This implementation does not
33   * handle any advanced cases, like redirects, authentication, etc.
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  }