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;
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 org.apache.maven.index.updater.ResourceFetcher;
30  
31  /**
32   * {@link ResourceFetcher} backed by Java11 HttpClient to be used in tests.
33   */
34  public class Java11HttpClient implements ResourceFetcher {
35      private final HttpClient client =
36              HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER).build();
37  
38      private URI uri;
39  
40      @Override
41      public void connect(String id, String url) {
42          this.uri = URI.create(url + "/");
43      }
44  
45      @Override
46      public void disconnect() {}
47  
48      @Override
49      public InputStream retrieve(String name) throws IOException {
50          HttpRequest request =
51                  HttpRequest.newBuilder().uri(uri.resolve(name)).GET().build();
52          try {
53              HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
54              if (response.statusCode() == HttpURLConnection.HTTP_OK) {
55                  return response.body();
56              } else {
57                  throw new IOException("Unexpected response: " + response);
58              }
59          } catch (InterruptedException e) {
60              Thread.currentThread().interrupt();
61              throw new IOException(e);
62          }
63      }
64  }