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      @Override
45      public Resource locate(final String name) {
46          return new HttpResource(name);
47      }
48  
49      private class HttpResource implements Resource {
50          private final String name;
51  
52          private HttpResource(final String name) {
53              this.name = name;
54          }
55  
56          @Override
57          public InputStream read() throws IOException {
58              HttpRequest request =
59                      HttpRequest.newBuilder().uri(root.resolve(name)).GET().build();
60              try {
61                  HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
62                  if (response.statusCode() == HttpURLConnection.HTTP_OK) {
63                      return response.body();
64                  } else {
65                      throw new IOException("Unexpected response: " + response);
66                  }
67              } catch (InterruptedException e) {
68                  Thread.currentThread().interrupt();
69                  throw new IOException(e);
70              }
71          }
72      }
73  }