|
| 1 | +/* |
| 2 | + * Copyright (c) 2021 Oracle and/or its affiliates. All rights reserved. |
| 3 | + * |
| 4 | + * This program and the accompanying materials are made available under the |
| 5 | + * terms of the Eclipse Public License v. 2.0, which is available at |
| 6 | + * http://www.eclipse.org/legal/epl-2.0. |
| 7 | + * |
| 8 | + * This Source Code may also be made available under the following Secondary |
| 9 | + * Licenses when the conditions for such availability set forth in the |
| 10 | + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, |
| 11 | + * version 2 with the GNU Classpath Exception, which is available at |
| 12 | + * https://www.gnu.org/software/classpath/license.html. |
| 13 | + * |
| 14 | + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 |
| 15 | + */ |
| 16 | + |
| 17 | +package org.glassfish.jersey.java.connector; |
| 18 | + |
| 19 | +import jakarta.ws.rs.ProcessingException; |
| 20 | +import jakarta.ws.rs.client.Client; |
| 21 | +import jakarta.ws.rs.core.Configuration; |
| 22 | +import jakarta.ws.rs.core.MultivaluedMap; |
| 23 | +import org.glassfish.jersey.client.ClientProperties; |
| 24 | +import org.glassfish.jersey.client.ClientRequest; |
| 25 | +import org.glassfish.jersey.client.ClientResponse; |
| 26 | +import org.glassfish.jersey.client.spi.AsyncConnectorCallback; |
| 27 | +import org.glassfish.jersey.client.spi.Connector; |
| 28 | +import org.glassfish.jersey.internal.Version; |
| 29 | +import org.glassfish.jersey.message.internal.OutboundMessageContext; |
| 30 | +import org.glassfish.jersey.message.internal.Statuses; |
| 31 | + |
| 32 | +import javax.net.ssl.SSLContext; |
| 33 | +import javax.net.ssl.SSLParameters; |
| 34 | +import java.io.ByteArrayOutputStream; |
| 35 | +import java.io.IOException; |
| 36 | +import java.io.InputStream; |
| 37 | +import java.io.OutputStream; |
| 38 | +import java.net.CookieHandler; |
| 39 | +import java.net.http.HttpClient; |
| 40 | +import java.net.http.HttpRequest; |
| 41 | +import java.net.http.HttpResponse; |
| 42 | +import java.time.Duration; |
| 43 | +import java.time.temporal.ChronoUnit; |
| 44 | +import java.util.List; |
| 45 | +import java.util.Map; |
| 46 | +import java.util.concurrent.CompletableFuture; |
| 47 | +import java.util.concurrent.Future; |
| 48 | +import java.util.logging.Logger; |
| 49 | + |
| 50 | +/** |
| 51 | + * Provides a Jersey client {@link Connector}, which internally uses Java's {@link HttpClient}. |
| 52 | + * The following properties are provided to Java's {@link HttpClient.Builder} during creation of the {@link HttpClient}: |
| 53 | + * <ul> |
| 54 | + * <li>{@link ClientProperties#CONNECT_TIMEOUT}</li> |
| 55 | + * <li>{@link ClientProperties#FOLLOW_REDIRECTS}</li> |
| 56 | + * <li>{@link JavaClientProperties#COOKIE_HANDLER}</li> |
| 57 | + * <li>{@link JavaClientProperties#SSL_PARAMETERS}</li> |
| 58 | + * </ul> |
| 59 | + * |
| 60 | + * @author Steffen Nießing |
| 61 | + */ |
| 62 | +public class JavaConnector implements Connector { |
| 63 | + private static final Logger LOGGER = Logger.getLogger(JavaConnector.class.getName()); |
| 64 | + |
| 65 | + private final HttpClient httpClient; |
| 66 | + |
| 67 | + /** |
| 68 | + * Constructs a new {@link Connector} for a Jersey client instance using Java's {@link HttpClient}. |
| 69 | + * |
| 70 | + * @param client a Jersey client instance to get additional configuration properties from (e.g. {@link SSLContext}) |
| 71 | + * @param configuration the configuration properties for this connector |
| 72 | + */ |
| 73 | + public JavaConnector(final Client client, final Configuration configuration) { |
| 74 | + HttpClient.Builder httpClientBuilder = HttpClient.newBuilder(); |
| 75 | + httpClientBuilder.version(HttpClient.Version.HTTP_1_1); |
| 76 | + SSLContext sslContext = client.getSslContext(); |
| 77 | + if (sslContext != null) { |
| 78 | + httpClientBuilder.sslContext(sslContext); |
| 79 | + } |
| 80 | + Integer connectTimeout = getPropertyOrNull(configuration, ClientProperties.CONNECT_TIMEOUT, Integer.class); |
| 81 | + if (connectTimeout != null) { |
| 82 | + httpClientBuilder.connectTimeout(Duration.of(connectTimeout, ChronoUnit.MILLIS)); |
| 83 | + } |
| 84 | + CookieHandler cookieHandler = getPropertyOrNull(configuration, JavaClientProperties.COOKIE_HANDLER, CookieHandler.class); |
| 85 | + if (cookieHandler != null) { |
| 86 | + httpClientBuilder.cookieHandler(cookieHandler); |
| 87 | + } |
| 88 | + Boolean redirect = getPropertyOrNull(configuration, ClientProperties.FOLLOW_REDIRECTS, Boolean.class); |
| 89 | + if (redirect != null) { |
| 90 | + httpClientBuilder.followRedirects(redirect ? HttpClient.Redirect.ALWAYS : HttpClient.Redirect.NEVER); |
| 91 | + } else { |
| 92 | + httpClientBuilder.followRedirects(HttpClient.Redirect.NORMAL); |
| 93 | + } |
| 94 | + SSLParameters sslParameters = getPropertyOrNull(configuration, JavaClientProperties.SSL_PARAMETERS, SSLParameters.class); |
| 95 | + if (sslParameters != null) { |
| 96 | + httpClientBuilder.sslParameters(sslParameters); |
| 97 | + } |
| 98 | + this.httpClient = httpClientBuilder.build(); |
| 99 | + } |
| 100 | + |
| 101 | + /** |
| 102 | + * Implements a {@link org.glassfish.jersey.message.internal.OutboundMessageContext.StreamProvider} |
| 103 | + * for a {@link ByteArrayOutputStream}. |
| 104 | + */ |
| 105 | + private static class ByteArrayOutputStreamProvider implements OutboundMessageContext.StreamProvider { |
| 106 | + private ByteArrayOutputStream byteArrayOutputStream; |
| 107 | + |
| 108 | + public ByteArrayOutputStream getByteArrayOutputStream() { |
| 109 | + return byteArrayOutputStream; |
| 110 | + } |
| 111 | + |
| 112 | + @Override |
| 113 | + public OutputStream getOutputStream(int contentLength) throws IOException { |
| 114 | + return this.byteArrayOutputStream = new ByteArrayOutputStream(contentLength); |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + /** |
| 119 | + * Builds a request for the {@link HttpClient} from Jersey's {@link ClientRequest}. |
| 120 | + * |
| 121 | + * @param request the Jersey request to get request data from |
| 122 | + * @return the {@link HttpRequest} instance for the {@link HttpClient} request |
| 123 | + */ |
| 124 | + private HttpRequest getHttpRequest(ClientRequest request) { |
| 125 | + HttpRequest.Builder builder = HttpRequest.newBuilder(); |
| 126 | + builder.uri(request.getUri()); |
| 127 | + HttpRequest.BodyPublisher bodyPublisher = HttpRequest.BodyPublishers.noBody(); |
| 128 | + if (request.hasEntity()) { |
| 129 | + try { |
| 130 | + request.enableBuffering(); |
| 131 | + ByteArrayOutputStreamProvider byteBufferStreamProvider = new ByteArrayOutputStreamProvider(); |
| 132 | + request.setStreamProvider(byteBufferStreamProvider); |
| 133 | + request.writeEntity(); |
| 134 | + bodyPublisher = HttpRequest.BodyPublishers.ofByteArray( |
| 135 | + byteBufferStreamProvider.getByteArrayOutputStream().toByteArray() |
| 136 | + ); |
| 137 | + } catch (IOException e) { |
| 138 | + throw new ProcessingException(LocalizationMessages.ERROR_INVALID_ENTITY(), e); |
| 139 | + } |
| 140 | + } |
| 141 | + builder.method(request.getMethod(), bodyPublisher); |
| 142 | + for (Map.Entry<String, List<String>> entry : request.getRequestHeaders().entrySet()) { |
| 143 | + String headerName = entry.getKey(); |
| 144 | + for (String headerValue : entry.getValue()) { |
| 145 | + builder.header(headerName, headerValue); |
| 146 | + } |
| 147 | + } |
| 148 | + return builder.build(); |
| 149 | + } |
| 150 | + |
| 151 | + /** |
| 152 | + * Retrieves a property from the configuration, if it was provided. |
| 153 | + * |
| 154 | + * @param configuration the {@link Configuration} to get the property information from |
| 155 | + * @param propertyKey the name of the property to retrieve |
| 156 | + * @param resultClass the type to which the property value should be case |
| 157 | + * @param <T> the generic type parameter of the result type |
| 158 | + * @return the requested property or {@code null}, if it was not provided or has the wrong type |
| 159 | + */ |
| 160 | + @SuppressWarnings("unchecked") |
| 161 | + private <T> T getPropertyOrNull(final Configuration configuration, final String propertyKey, final Class<T> resultClass) { |
| 162 | + Object propertyObject = configuration.getProperty(propertyKey); |
| 163 | + if (propertyObject == null) { |
| 164 | + return null; |
| 165 | + } |
| 166 | + if (!resultClass.isInstance(propertyObject)) { |
| 167 | + LOGGER.warning(LocalizationMessages.ERROR_INVALID_CLASS(propertyKey, resultClass.getName())); |
| 168 | + return null; |
| 169 | + } |
| 170 | + return (T) propertyObject; |
| 171 | + } |
| 172 | + |
| 173 | + /** |
| 174 | + * Translates a {@link HttpResponse} from the {@link HttpClient} to a Jersey {@link ClientResponse}. |
| 175 | + * |
| 176 | + * @param request the {@link ClientRequest} to get additional information (e.g. header values) from |
| 177 | + * @param response the {@link HttpClient} response object |
| 178 | + * @return the translated Jersey {@link ClientResponse} object |
| 179 | + */ |
| 180 | + private ClientResponse buildClientResponse(ClientRequest request, HttpResponse<InputStream> response) { |
| 181 | + ClientResponse clientResponse = new ClientResponse(Statuses.from(response.statusCode()), request); |
| 182 | + MultivaluedMap<String, String> headers = clientResponse.getHeaders(); |
| 183 | + for (Map.Entry<String, List<String>> entry : response.headers().map().entrySet()) { |
| 184 | + String headerName = entry.getKey(); |
| 185 | + if (headers.get(headerName) != null) { |
| 186 | + headers.get(headerName).addAll(entry.getValue()); |
| 187 | + } else { |
| 188 | + headers.put(headerName, entry.getValue()); |
| 189 | + } |
| 190 | + } |
| 191 | + clientResponse.setEntityStream(response.body()); |
| 192 | + return clientResponse; |
| 193 | + } |
| 194 | + |
| 195 | + /** |
| 196 | + * Returns the underlying {@link HttpClient} instance used by this connector. |
| 197 | + * |
| 198 | + * @return the Java {@link HttpClient} instance |
| 199 | + */ |
| 200 | + public HttpClient getHttpClient() { |
| 201 | + return httpClient; |
| 202 | + } |
| 203 | + |
| 204 | + @Override |
| 205 | + public ClientResponse apply(ClientRequest request) { |
| 206 | + HttpRequest httpRequest = getHttpRequest(request); |
| 207 | + try { |
| 208 | + HttpResponse<InputStream> response = this.httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofInputStream()); |
| 209 | + return buildClientResponse(request, response); |
| 210 | + } catch (IOException | InterruptedException e) { |
| 211 | + throw new ProcessingException(e); |
| 212 | + } |
| 213 | + } |
| 214 | + |
| 215 | + @Override |
| 216 | + public Future<?> apply(ClientRequest request, AsyncConnectorCallback callback) { |
| 217 | + HttpRequest httpRequest = getHttpRequest(request); |
| 218 | + CompletableFuture<ClientResponse> response = this.httpClient |
| 219 | + .sendAsync(httpRequest, HttpResponse.BodyHandlers.ofInputStream()) |
| 220 | + .thenApply(httpResponse -> buildClientResponse(request, httpResponse)); |
| 221 | + response.thenAccept(callback::response); |
| 222 | + return response; |
| 223 | + } |
| 224 | + |
| 225 | + @Override |
| 226 | + public String getName() { |
| 227 | + return "Java HttpClient Connector " + Version.getVersion(); |
| 228 | + } |
| 229 | + |
| 230 | + @Override |
| 231 | + public void close() { |
| 232 | + |
| 233 | + } |
| 234 | +} |
0 commit comments